diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 5985624de..43d65d5b5 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -1,6 +1,9 @@ name: Create Automatic Release on: + push: + branches: + - nate/auto-main-release-draft schedule: - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday workflow_dispatch: # Keep manual trigger option @@ -13,30 +16,13 @@ jobs: steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Important for getting all tags and commits - - name: Get latest tag - id: get_latest_tag + - name: Get version from package.json + id: get_version run: | - # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" | head -n 1 || echo "v1.1.0-vscode") - echo "Latest tag: $latest_tag" - echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV - - - name: Generate next version - id: generate_version - run: | - # Extract version numbers (handle the -vscode suffix) - version=${LATEST_TAG#v} # Remove v prefix - version=${version%-vscode} # Remove -vscode suffix - IFS='.' read -ra VERSION_PARTS <<< "$version" - - # Increment patch version - ((VERSION_PARTS[2]++)) - - # Create new version string with -vscode suffix - new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-vscode" + # Read version from package.json and add -vscode suffix + version=$(node -p "require('./extensions/vscode/package.json').version") + new_version="v${version}-vscode" echo "New version will be: $new_version" echo "NEW_VERSION=$new_version" >> $GITHUB_ENV @@ -49,7 +35,7 @@ jobs: --generate-notes \ --title "$NEW_VERSION" \ --draft \ - --latest + --latest \ --prerelease create-jetbrains-release: @@ -60,29 +46,14 @@ jobs: steps: - uses: actions/checkout@v4 with: - fetch-depth: 0 # Important for getting all tags and commits + fetch-depth: 0 - - name: Get latest tag - id: get_latest_tag + - name: Get version from gradle.properties + id: get_version run: | - # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" | head -n 1 || echo "v1.1.0-jetbrains") - echo "Latest tag: $latest_tag" - echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV - - - name: Generate next version - id: generate_version - run: | - # Extract version numbers (handle the -jetbrains suffix) - version=${LATEST_TAG#v} # Remove v prefix - version=${version%-jetbrains} # Remove -jetbrains suffix - IFS='.' read -ra VERSION_PARTS <<< "$version" - - # Increment patch version - ((VERSION_PARTS[2]++)) - - # Create new version string with -jetbrains suffix - new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-jetbrains" + # Read version from gradle.properties and add -jetbrains suffix + version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2) + new_version="v${version}-jetbrains" echo "New version will be: $new_version" echo "NEW_VERSION=$new_version" >> $GITHUB_ENV @@ -95,5 +66,5 @@ jobs: --generate-notes \ --title "$NEW_VERSION" \ --draft \ - --latest + --latest \ --prerelease diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index a968dcc19..629fa97b7 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -37,6 +37,52 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi + bump-version: + runs-on: ubuntu-latest + needs: + - check_release_name + if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' + permissions: + contents: write + pull-requests: write + steps: + # 0. Setup git + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Git + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + - name: Create PR branch + run: | + BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" + git checkout -b $BRANCH_NAME + echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + + - name: Bump version in gradle.properties + run: | + cd extensions/intelllij + awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties + rm -rf tmp + NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) + echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.CI_GITHUB_TOKEN }} + commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + body: | + Automated PR to bump the JetBrains extension version after successful pre-release publication. + + - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} + branch: ${{ env.BRANCH_NAME }} + base: main + delete-branch: true + # Prepare and publish the plugin to JetBrains Marketplace repository build: needs: check_release_name @@ -121,6 +167,21 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build and check config-yaml + run: | + cd ../../packages/config-yaml + npm i + npx tsc --noEmit + # Tests are currently failing, commenting out for now + # npm test + npm run build + # npm install core - name: Install core node_modules run: | diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index bf8ce2ecb..4d0a4039b 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -31,6 +31,62 @@ jobs: if: steps.root-cache.outputs.cache-hit != 'true' run: npm ci + install-config-yaml: + needs: install-root + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Install config-yaml dependencies + if: steps.config-yaml-cache.outputs.cache-hit != 'true' + run: | + cd packages/config-yaml + npm ci + + config-yaml-checks: + needs: install-config-yaml + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build and check config-yaml + run: | + cd packages/config-yaml + npx tsc --noEmit + # Tests are currently failing, commenting out for now + # npm test + npm run build + install-core: needs: install-root runs-on: ubuntu-latest @@ -60,7 +116,7 @@ jobs: npm ci core-checks: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -81,6 +137,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd core @@ -90,7 +157,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -115,6 +182,17 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install gui dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: | @@ -147,13 +225,24 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check run: | cd gui npx tsc --noEmit binary-checks: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -178,6 +267,17 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install binary dependencies if: steps.binary-cache.outputs.cache-hit != 'true' run: | @@ -190,7 +290,7 @@ jobs: npx tsc --noEmit install-vscode: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -215,6 +315,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install vscode dependencies if: steps.vscode-cache.outputs.cache-hit != 'true' run: | @@ -249,14 +360,26 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd extensions/vscode + npm run write-build-timestamp npx tsc --noEmit npm run lint core-tests: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -270,6 +393,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Run core tests run: | cd core @@ -285,7 +419,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [install-root, install-vscode] + needs: [install-root, install-vscode, install-config-yaml] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -297,6 +431,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Get test files id: vscode-get-test-file-matrix run: | @@ -320,7 +465,7 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -340,6 +485,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Package extension run: | cd extensions/vscode @@ -353,7 +509,7 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -373,6 +529,17 @@ jobs: path: extensions/vscode/e2e/storage key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Download Dependencies if: steps.storage-cache.outputs.cache-hit != 'true' run: | @@ -394,6 +561,7 @@ jobs: vscode-package-extension, install-vscode, install-core, + install-config-yaml, ] runs-on: ubuntu-latest # Tests requiring secrets need approval from maintainers @@ -434,6 +602,17 @@ jobs: name: vscode-e2e-dependencies path: extensions/vscode/e2e/storage + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Fix VSCode binary permissions run: | chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code @@ -476,7 +655,7 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [install-gui, install-core] + needs: [install-gui, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -496,6 +675,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install GUI dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: cd gui && npm ci @@ -508,7 +698,7 @@ jobs: npm test jetbrains-tests: - needs: [install-root, core-checks] + needs: [install-root, core-checks, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -517,6 +707,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Setup Java uses: actions/setup-java@v4.5.0 with: @@ -627,11 +828,11 @@ jobs: - vscode-e2e-tests - gui-tests - jetbrains-tests + - config-yaml-checks + - install-config-yaml steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: - allowed-failures: - allowed-skips: jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 80eaa4931..23ea26bf6 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -263,7 +263,7 @@ jobs: echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV - name: Create Pull Request - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v7 with: token: ${{ secrets.CI_GITHUB_TOKEN }} commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}" diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index 39dc5b7f1..c05da185f 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -1,4 +1,4 @@ -name: VS Code Extension Version Bump +name: Create VS Code main release draft on: schedule: # Runs at 7 AM PST (15:00 UTC) every Friday @@ -15,6 +15,10 @@ jobs: with: fetch-depth: 0 # Fetch all history and tags + - name: Setup GitHub CLI + run: | + gh auth login --with-token <<< "${{ github.token }}" + - name: Use Node.js from .nvmrc uses: actions/setup-node@v4 with: @@ -97,6 +101,15 @@ jobs: echo "Pushing branch to origin..." git push origin $NEW_BRANCH + # Add release creation + echo "Creating draft release..." + gh release create "${NEW_BRANCH}" \ + --title "${NEW_BRANCH}" \ + --generate-notes \ + --draft \ + --latest \ + --notes-start-tag "${LAST_1_0_TAG}" + echo "Version bump process completed successfully!" - name: Check for errors diff --git a/binary/package-lock.json b/binary/package-lock.json index 51ea6b1f1..5c2324e82 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index bd8504986..fb1be39bb 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -234,15 +234,17 @@ describe("Test Suite", () => { result: { config }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(config!.models.some((m) => m.title === model.title)).toBe(true); + expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe( + true, + ); await messenger.request("config/deleteModel", { title: model.title }); const { result: { config: configAfterDelete }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe( - false, - ); + expect( + configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title), + ).toBe(false); }); it("should make an LLM completion", async () => { diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 633895fb7..fbd390fb4 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -12,11 +12,11 @@ "curly": "off", "@typescript-eslint/semi": "off", "eqeqeq": "error", - "complexity": ["error", { "max": 38 }], - "max-lines-per-function": ["error", { "max": 996 }], - "max-statements": ["error", { "max": 114 }], + "complexity": ["error", { "max": 36 }], + "max-lines-per-function": ["error", { "max": 472 }], + "max-statements": ["error", { "max": 108 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], - "max-params": ["error", { "max": 11 }] + "max-params": ["error", { "max": 8 }] } } diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index a640dbd25..637013476 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -32,7 +32,7 @@ const DraftIssueCommand: SlashCommand = { let title = await llm.complete( `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, - { maxTokens: 20 }, + { maxTokens: 30 }, ); title = `${removeQuotesAndEscapes(title.trim())}\n\n`; @@ -40,7 +40,7 @@ const DraftIssueCommand: SlashCommand = { let body = ""; const messages: ChatMessage[] = [ - ...history, + ...history.filter((msg) => msg.role !== "system"), { role: "user", content: PROMPT(input, title) }, ]; diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index 91c9dcd16..84df38989 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -1,5 +1,6 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { PromptMessage } from "@modelcontextprotocol/sdk/types.js"; import { ChatMessage, SlashCommand } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; export function constructMcpSlashCommand( @@ -22,8 +23,8 @@ export function constructMcpSlashCommand( } const result = await client.getPrompt({ name, arguments: argsObject }); - - const messages: ChatMessage[] = result.messages.map((msg) => { + const mcpMessages: PromptMessage[] = result.messages; + const messages: ChatMessage[] = mcpMessages.map((msg) => { if (msg.content.type !== "text") { throw new Error( "Continue currently only supports text prompts through MCP", @@ -40,12 +41,22 @@ export function constructMcpSlashCommand( return; } - const reversedMessages = [...messages].reverse(); - const messageToAppendInput = - reversedMessages.find((m) => m.role === "user") ?? - reversedMessages.find((m) => m.role === "assistant") ?? - reversedMessages[0]; - messageToAppendInput.content += ` ${userInput}`; + if (userInput) { + const lastMessage = messages.at(-1); + if (!lastMessage || lastMessage.role !== "user") { + messages.push({ + role: "user", + content: userInput, + }); + } else { + let newContent = renderChatMessage(lastMessage); + if (newContent) { + newContent += "\n\n"; + } + newContent += userInput; + lastMessage.content = newContent; + } + } for await (const chunk of context.llm.streamChat( messages, diff --git a/core/commands/util.ts b/core/commands/util.ts index 5a0ea32e4..3785b4f52 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -34,13 +34,18 @@ export function ctxItemToRifWithContents( ): RangeInFileWithContents { let startLine = 0; let endLine = 0; + let adjustLines = linesOffByOne ? 1 : 0; const nameSplit = item.name.split("("); if (nameSplit.length > 1) { const lines = nameSplit[1].split(")")[0].split("-"); - startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0); - endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0); + startLine = Number.parseInt(lines[0], 10); + if (startLine === 0) { + adjustLines = 0; // safety to make sure doesn't go negative + } + startLine -= adjustLines; + endLine = Number.parseInt(lines[1], 10) - adjustLines; } const rif: RangeInFileWithContents = { diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index bf71952e9..4b4be0762 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -19,7 +19,9 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should load the default config successfully", async () => { const result = await testConfigHandler.loadConfig(); - expect(result.config!.models.length).toBe(defaultConfig.models?.length); + expect(result.config!.modelsByRole.chat.length).toBe( + defaultConfig.models?.length, + ); }); test.skip("should add a system message from config.ts", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2d4a471d5..96e676ce6 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -4,25 +4,18 @@ import { ControlPlaneClient, ControlPlaneSessionInfo, } from "../control-plane/client.js"; -import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; +import { getControlPlaneEnv } from "../control-plane/env.js"; import { BrowserSerializedContinueConfig, ContinueConfig, IContextProvider, IDE, IdeSettings, - ILLM, ILLMLogger, } from "../index.js"; -import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { getAllAssistantFiles } from "./loadLocalAssistants.js"; -import { - LOCAL_ONBOARDING_CHAT_MODEL, - LOCAL_ONBOARDING_PROVIDER_TITLE, -} from "./onboarding.js"; -import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { @@ -141,16 +134,11 @@ export class ConfigHandler { const userId = await this.controlPlaneClient.userId; if (userId) { const orgDescs = await this.controlPlaneClient.listOrganizations(); - if (await useHub(this.ideSettingsPromise)) { - const personalHubOrg = await this.getPersonalHubOrg(); - const hubOrgs = await Promise.all( - orgDescs.map((org) => this.getNonPersonalHubOrg(org)), - ); - return [...hubOrgs, personalHubOrg]; - } else { - // Should only ever be one teams org. Will be removed soon anyways - return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org))); - } + const personalHubOrg = await this.getPersonalHubOrg(); + const hubOrgs = await Promise.all( + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ); + return [...hubOrgs, personalHubOrg]; } else { return [await this.getLocalOrg()]; } @@ -172,22 +160,22 @@ export class ConfigHandler { return await Promise.all( assistants.map(async (assistant) => { - const profileLoader = await PlatformProfileLoader.create( - { + const profileLoader = await PlatformProfileLoader.create({ + configResult: { ...assistant.configResult, config: assistant.configResult.config, }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.llmLogger, - assistant.rawYaml, - orgScopeId, - ); + ownerSlug: assistant.ownerSlug, + packageSlug: assistant.packageSlug, + iconUrl: assistant.iconUrl, + versionSlug: assistant.configResult.config?.version ?? "latest", + controlPlaneClient: this.controlPlaneClient, + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + llmLogger: this.llmLogger, + rawYaml: assistant.rawYaml, + orgScopeId: orgScopeId, + }); return new ProfileLifecycleManager(profileLoader, this.ide); }), @@ -219,25 +207,6 @@ export class ConfigHandler { return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); } - async getTeamsOrg(org: OrganizationDescription): Promise { - const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.llmLogger, - this.reloadConfig.bind(this), - ); - - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); - }); - return this.rectifyProfilesForOrg(org, profiles); - } - private async rectifyProfilesForOrg( org: OrganizationDescription, profiles: ProfileLifecycleManager[], @@ -473,27 +442,6 @@ export class ConfigHandler { } } - // Only used till we move to using selectedModelByRole.chat - async llmFromTitle(title?: string): Promise { - const { config } = await this.loadConfig(); - const model = config?.models.find((m) => m.title === title); - if (!model) { - if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) { - // Special case, make calls to Ollama before we have it in the config - const ollama = new Ollama({ - model: LOCAL_ONBOARDING_CHAT_MODEL, - }); - return ollama; - } else if (config?.models?.length) { - return config?.models[0]; - } - - throw new Error("No model found"); - } - - return model; - } - // Ancient method of adding custom providers through vs code private additionalContextProviders: IContextProvider[] = []; registerCustomContextProvider(contextProvider: IContextProvider) { diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts deleted file mode 100644 index 550144cd8..000000000 --- a/core/config/getSystemPromptDotFile.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { IDE } from ".."; -import { joinPathsToUri } from "../util/uri"; -export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; - -export async function getSystemPromptDotFile(ide: IDE): Promise { - const dirs = await ide.getWorkspaceDirs(); - - let prompts: string[] = []; - for (const dir of dirs) { - const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE); - if (await ide.fileExists(dotFile)) { - try { - const content = await ide.readFile(dotFile); - prompts.push(content); - } catch (e) { - // ignore if file doesn't exist - } - } - } - - if (!prompts.length) { - return null; - } - - return prompts.join("\n\n"); -} diff --git a/core/config/getWorkspaceContinueRuleDotFiles.ts b/core/config/getWorkspaceContinueRuleDotFiles.ts new file mode 100644 index 000000000..8a14d2405 --- /dev/null +++ b/core/config/getWorkspaceContinueRuleDotFiles.ts @@ -0,0 +1,32 @@ +import { ConfigValidationError } from "@continuedev/config-yaml"; +import { IDE, RuleWithSource } from ".."; +import { joinPathsToUri } from "../util/uri"; +export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; + +export async function getWorkspaceContinueRuleDotFiles(ide: IDE) { + const dirs = await ide.getWorkspaceDirs(); + + const errors: ConfigValidationError[] = []; + const rules: RuleWithSource[] = []; + for (const dir of dirs) { + try { + const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE); + const exists = await ide.fileExists(dotFile); + if (exists) { + const content = await ide.readFile(dotFile); + rules.push({ + rule: content, + ruleFile: dotFile, + source: ".continuerules", + }); + } + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to load system prompt dot file from workspace ${dir}: ${e instanceof Error ? e.message : e}`, + }); + } + } + + return { rules, errors }; +} diff --git a/core/config/load.ts b/core/config/load.ts index b85359641..4c89651ad 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -8,7 +8,6 @@ import { ConfigValidationError, ModelRole, } from "@continuedev/config-yaml"; -import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as JSONC from "comment-json"; import * as tar from "tar"; @@ -19,7 +18,6 @@ import { ContinueConfig, ContinueRcJson, CustomContextProvider, - CustomLLM, EmbeddingsProviderDescription, IContextProvider, IDE, @@ -38,7 +36,6 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index"; -import { AllRerankers } from "../context/allRerankers"; import { MCPManagerSingleton } from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; @@ -46,9 +43,8 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import { useHub } from "../control-plane/env"; -import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; -import { llmFromDescription } from "../llm/llms"; +import { LLMClasses, llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; import { LLMReranker } from "../llm/llms/llm"; @@ -71,9 +67,12 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; -import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; +import { + getModelByRole, + isSupportedLanceDbCpuTargetForLinux, + serializePromptTemplates, +} from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -204,12 +203,6 @@ async function serializedToIntermediateConfig( return config; } -function isModelDescription( - llm: ModelDescription | CustomLLM, -): llm is ModelDescription { - return (llm as ModelDescription).title !== undefined; -} - export function isContextProviderWithParams( contextProvider: CustomContextProvider | ContextProviderWithParams, ): contextProvider is ContextProviderWithParams { @@ -217,96 +210,106 @@ export function isContextProviderWithParams( } /** Only difference between intermediate and final configs is the `models` array */ -async function intermediateToFinalConfig( - config: Config, - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - llmLogger: ILLMLogger, - workOsAccessToken: string | undefined, - loadPromptFiles: boolean = true, - allowFreeTrial: boolean = true, -): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { +async function intermediateToFinalConfig({ + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + workOsAccessToken, + loadPromptFiles = true, + allowFreeTrial = true, +}: { + config: Config; + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + workOsAccessToken: string | undefined; + loadPromptFiles?: boolean; + allowFreeTrial?: boolean; +}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { const errors: ConfigValidationError[] = []; // Auto-detect models let models: BaseLLM[] = []; - for (const desc of config.models) { - if (isModelDescription(desc)) { - const llm = await llmFromDescription( - desc, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - llmLogger, - config.completionOptions, - config.systemMessage, - ); - if (!llm) { - continue; - } - - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const detectedModels = await Promise.all( - modelNames.map(async (modelName) => { - return await llmFromDescription( - { - ...desc, - model: modelName, - title: modelName, - }, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - llmLogger, - copyOf(config.completionOptions), - config.systemMessage, - ); - }), - ); - models.push( - ...(detectedModels.filter( - (x) => typeof x !== "undefined", - ) as BaseLLM[]), - ); - } catch (e) { - console.warn("Error listing models: ", e); + await Promise.all( + config.models.map(async (desc) => { + if ("title" in desc) { + const llm = await llmFromDescription( + desc, + ide.readFile.bind(ide), + uniqueId, + ideSettings, + llmLogger, + config.completionOptions, + ); + if (!llm) { + return; } - } else { - models.push(llm); - } - } else { - const llm = new CustomLLMClass({ - ...desc, - options: { ...desc.options, logger: llmLogger } as any, - }); - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const models = modelNames.map( - (modelName) => - new CustomLLMClass({ - ...desc, - options: { - ...desc.options, - model: modelName, - logger: llmLogger, - }, + + if (llm.model === "AUTODETECT") { + try { + const modelNames = await llm.listModels(); + const detectedModels = await Promise.all( + modelNames.map(async (modelName) => { + return await llmFromDescription( + { + ...desc, + model: modelName, + title: modelName, + }, + ide.readFile.bind(ide), + uniqueId, + ideSettings, + llmLogger, + copyOf(config.completionOptions), + ); }), - ); - - models.push(...models); - } catch (e) { - console.warn("Error listing models: ", e); + ); + models.push( + ...(detectedModels.filter( + (x) => typeof x !== "undefined", + ) as BaseLLM[]), + ); + } catch (e) { + console.warn("Error listing models: ", e); + } + } else { + models.push(llm); } } else { - models.push(llm); + const llm = new CustomLLMClass({ + ...desc, + options: { ...desc.options, logger: llmLogger } as any, + }); + if (llm.model === "AUTODETECT") { + try { + const modelNames = await llm.listModels(); + const models = modelNames.map( + (modelName) => + new CustomLLMClass({ + ...desc, + options: { + ...desc.options, + model: modelName, + logger: llmLogger, + }, + }), + ); + + models.push(...models); + } catch (e) { + console.warn("Error listing models: ", e); + } + } else { + models.push(llm); + } } - } - } + }), + ); // Prepare models for (const model of models) { @@ -342,7 +345,7 @@ async function intermediateToFinalConfig( ? config.tabAutocompleteModel : [config.tabAutocompleteModel] ).map(async (desc) => { - if (isModelDescription(desc)) { + if ("title" in desc) { const llm = await llmFromDescription( desc, ide.readFile.bind(ide), @@ -350,7 +353,6 @@ async function intermediateToFinalConfig( ideSettings, llmLogger, config.completionOptions, - config.systemMessage, ); if (llm?.providerName === "free-trial") { @@ -425,38 +427,32 @@ async function intermediateToFinalConfig( function getEmbeddingsILLM( embedConfig: EmbeddingsProviderDescription | ILLM | undefined, ): ILLM | null { - if (!embedConfig) { - return null; - } - if ("providerName" in embedConfig) { - return embedConfig; - } - const { provider, ...options } = embedConfig; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - return new embeddingsProviderClass(); - } else { - const llmOptions: LLMOptions = { - model: options.model ?? "UNSPECIFIED", - ...options, - }; - return new embeddingsProviderClass( - llmOptions, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...config.requestOptions, - ...options.requestOptions, - }), - ); + if (embedConfig) { + // config.ts-injected ILLM + if ("providerName" in embedConfig) { + return embedConfig; } - } else { - errors.push({ - fatal: false, - message: `Embeddings provider ${provider} not found. Using default`, - }); + const { provider, ...options } = embedConfig; + if (provider === "transformers.js") { + return new TransformersJsEmbeddingsProvider(); + } else { + const cls = LLMClasses.find((c) => c.providerName === provider); + if (cls) { + const llmOptions: LLMOptions = { + model: options.model ?? "UNSPECIFIED", + ...options, + }; + return new cls(llmOptions); + } else { + errors.push({ + fatal: false, + message: `Embeddings provider ${provider} not found`, + }); + } + } + } + if (ideInfo.ideType === "vscode") { + return new TransformersJsEmbeddingsProvider(); } return null; } @@ -469,11 +465,11 @@ async function intermediateToFinalConfig( if (!rerankingConfig) { return null; } + // config.ts-injected ILLM if ("providerName" in rerankingConfig) { return rerankingConfig; } const { name, params } = config.reranker as RerankerDescription; - const rerankerClass = AllRerankers[name]; if (name === "llm") { const llm = models.find((model) => model.title === params?.modelTitle); @@ -486,16 +482,20 @@ async function intermediateToFinalConfig( } else { return new LLMReranker(llm); } - } else if (rerankerClass) { - const llmOptions: LLMOptions = { - model: "rerank-2", - ...params, - }; - return new rerankerClass(llmOptions, (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...params?.requestOptions, - }), - ); + } else { + const cls = LLMClasses.find((c) => c.providerName === name); + if (cls) { + const llmOptions: LLMOptions = { + model: params?.model, + ...params, + }; + return new cls(llmOptions); + } else { + errors.push({ + fatal: false, + message: `Unknown reranking provider ${name}`, + }); + } } return null; } @@ -504,7 +504,6 @@ async function intermediateToFinalConfig( const continueConfig: ContinueConfig = { ...config, contextProviders, - models, tools: [...allTools], mcpServerStatuses: [], slashCommands: config.slashCommands ?? [], @@ -526,8 +525,16 @@ async function intermediateToFinalConfig( rerank: newReranker ?? null, summarize: null, // Not implemented }, + rules: [], }; + if (config.systemMessage) { + continueConfig.rules.unshift({ + rule: config.systemMessage, + source: "json-systemMessage", + }); + } + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( @@ -544,7 +551,7 @@ async function intermediateToFinalConfig( // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; if (inlineEditModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === inlineEditModel, ); if (match) { @@ -563,7 +570,7 @@ async function intermediateToFinalConfig( "applyCodeBlock", )?.title; if (applyBlockModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === applyBlockModel, ); if (match) { @@ -602,11 +609,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { contextLength: llm.contextLength, template: llm.template, completionOptions: llm.completionOptions, - systemMessage: llm.systemMessage, + baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, - promptTemplates: llm.promptTemplates as any, + promptTemplates: serializePromptTemplates(llm.promptTemplates), capabilities: llm.capabilities, roles: llm.roles, + configurationStatus: llm.getConfigurationStatus(), }; } @@ -616,8 +624,6 @@ async function finalToBrowserConfig( ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map(llmToSerializedModelDescription), - systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map( ({ run, ...slashCommandDescription }) => slashCommandDescription, @@ -857,11 +863,6 @@ async function loadContinueConfigFromJson( return { errors, config: undefined, configLoadInterrupted: true }; } - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - serialized.systemMessage = systemPromptDotFile; - } - // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); @@ -930,15 +931,15 @@ async function loadContinueConfigFromJson( // Convert to final config format const { config: finalConfig, errors: finalErrors } = - await intermediateToFinalConfig( - intermediate, + await intermediateToFinalConfig({ + config: intermediate, ide, ideSettings, ideInfo, uniqueId, llmLogger, workOsAccessToken, - ); + }); return { config: finalConfig, errors: [...(errors ?? []), ...finalErrors], diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index cf689b45d..e1e66000d 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -1,3 +1,10 @@ +/** + * I'm disabling this rule for the entire file under the assumption + * that this is a one-time migration script. I'm expecting this + * code to be removed in the future. + */ +/* eslint-disable max-statements */ + import { IDE } from ".."; import { deduplicateArray } from "../util"; import { GlobalContext } from "../util/GlobalContext"; diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts deleted file mode 100644 index 21ea27e14..000000000 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { ConfigJson } from "@continuedev/config-types"; -import { ConfigResult } from "@continuedev/config-yaml"; - -import { ControlPlaneClient } from "../../control-plane/client.js"; -import { PRODUCTION_ENV } from "../../control-plane/env.js"; -import { - ContinueConfig, - IDE, - IdeSettings, - ILLMLogger, - SerializedContinueConfig, -} from "../../index.js"; -import { ProfileDescription } from "../ProfileLifecycleManager.js"; - -import doLoadConfig from "./doLoadConfig.js"; -import { IProfileLoader } from "./IProfileLoader.js"; - -export default class ControlPlaneProfileLoader implements IProfileLoader { - private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes - - description: ProfileDescription; - - workspaceSettings: ConfigJson | undefined; - - constructor( - private readonly workspaceId: string, - private workspaceTitle: string, - private readonly controlPlaneClient: ControlPlaneClient, - private readonly ide: IDE, - private ideSettingsPromise: Promise, - private llmLogger: ILLMLogger, - private readonly onReload: () => void, - ) { - this.description = { - id: workspaceId, - profileType: "control-plane", - iconUrl: "", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - title: workspaceTitle, - errors: undefined, - uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, - }; - - setInterval(async () => { - this.workspaceSettings = - await this.controlPlaneClient.getSettingsForWorkspace( - this.description.id, - ); - this.onReload(); - }, ControlPlaneProfileLoader.RELOAD_INTERVAL); - } - - async doLoadConfig(): Promise> { - const settings = - this.workspaceSettings ?? - ((await this.controlPlaneClient.getSettingsForWorkspace( - this.description.id, - )) as any); - const serializedConfig: SerializedContinueConfig = settings; - - return await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - serializedConfig, - undefined, - undefined, - this.workspaceId, - undefined, - null, - ); - } - - setIsActive(isActive: boolean): void {} -} diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index f49c8bb7a..5b73a13e6 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -55,18 +55,18 @@ export default class LocalProfileLoader implements IProfileLoader { description: ProfileDescription; async doLoadConfig(): Promise> { - const result = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - undefined, - undefined, - undefined, - this.description.id, - this.overrideAssistantFile?.path, - null, - ); + const result = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: undefined, + overrideConfigYaml: undefined, + platformConfigMetadata: undefined, + profileId: this.description.id, + overrideConfigYamlByPath: this.overrideAssistantFile?.path, + orgScopeId: null, + }); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index cf9efb399..66bea1ef2 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -21,33 +21,81 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - private constructor( - private configResult: ConfigResult, - private readonly ownerSlug: string, - private readonly packageSlug: string, - private readonly iconUrl: string, - private readonly versionSlug: string, - private readonly controlPlaneClient: ControlPlaneClient, - private readonly ide: IDE, - private ideSettingsPromise: Promise, - private llmLogger: ILLMLogger, - readonly description: ProfileDescription, - private readonly orgScopeId: string | null, - ) {} + private configResult: ConfigResult; + private readonly ownerSlug: string; + private readonly packageSlug: string; + private readonly iconUrl: string; + private readonly versionSlug: string; + private readonly controlPlaneClient: ControlPlaneClient; + private readonly ide: IDE; + private ideSettingsPromise: Promise; + private llmLogger: ILLMLogger; + readonly description: ProfileDescription; + private readonly orgScopeId: string | null; - static async create( - configResult: ConfigResult, - ownerSlug: string, - packageSlug: string, - iconUrl: string, - versionSlug: string, - controlPlaneClient: ControlPlaneClient, - ide: IDE, - ideSettingsPromise: Promise, - llmLogger: ILLMLogger, - rawYaml: string, - orgScopeId: string | null, - ): Promise { + private constructor({ + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + llmLogger, + description, + orgScopeId, + }: { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + versionSlug: string; + controlPlaneClient: ControlPlaneClient; + ide: IDE; + ideSettingsPromise: Promise; + llmLogger: ILLMLogger; + description: ProfileDescription; + orgScopeId: string | null; + }) { + this.configResult = configResult; + this.ownerSlug = ownerSlug; + this.packageSlug = packageSlug; + this.iconUrl = iconUrl; + this.versionSlug = versionSlug; + this.controlPlaneClient = controlPlaneClient; + this.ide = ide; + this.ideSettingsPromise = ideSettingsPromise; + this.llmLogger = llmLogger; + this.description = description; + this.orgScopeId = orgScopeId; + } + + static async create({ + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + llmLogger, + rawYaml, + orgScopeId, + }: { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + versionSlug: string; + controlPlaneClient: ControlPlaneClient; + ide: IDE; + ideSettingsPromise: Promise; + llmLogger: ILLMLogger; + rawYaml: string; + orgScopeId: string | null; + }): Promise { const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); const description: ProfileDescription = { @@ -65,7 +113,7 @@ export default class PlatformProfileLoader implements IProfileLoader { rawYaml, }; - return new PlatformProfileLoader( + return new PlatformProfileLoader({ configResult, ownerSlug, packageSlug, @@ -77,7 +125,7 @@ export default class PlatformProfileLoader implements IProfileLoader { llmLogger, description, orgScopeId, - ); + }); } async doLoadConfig(): Promise> { @@ -89,21 +137,21 @@ export default class PlatformProfileLoader implements IProfileLoader { }; } - const results = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - undefined, - this.configResult.config, - { + const results = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: undefined, + overrideConfigYaml: this.configResult.config, + platformConfigMetadata: { ownerSlug: this.ownerSlug, packageSlug: this.packageSlug, }, - this.description.id, - undefined, - this.orgScopeId, - ); + profileId: this.description.id, + overrideConfigYamlByPath: undefined, + orgScopeId: this.orgScopeId, + }); return { config: results.config, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 626546b74..99845ddbf 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -34,20 +34,32 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; +import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -export default async function doLoadConfig( - ide: IDE, - ideSettingsPromise: Promise, - controlPlaneClient: ControlPlaneClient, - llmLogger: ILLMLogger, - overrideConfigJson: SerializedContinueConfig | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - profileId: string, - overrideConfigYamlByPath: string | undefined, - orgScopeId: string | null, -): Promise> { +export default async function doLoadConfig({ + ide, + ideSettingsPromise, + controlPlaneClient, + llmLogger, + overrideConfigJson, + overrideConfigYaml, + platformConfigMetadata, + profileId, + overrideConfigYamlByPath, + orgScopeId, +}: { + ide: IDE; + ideSettingsPromise: Promise; + controlPlaneClient: ControlPlaneClient; + llmLogger: ILLMLogger; + overrideConfigJson: SerializedContinueConfig | undefined; + overrideConfigYaml: AssistantUnrolled | undefined; + platformConfigMetadata: PlatformConfigMetadata | undefined; + profileId: string; + overrideConfigYamlByPath: string | undefined; + orgScopeId: string | null; +}): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); @@ -70,19 +82,18 @@ export default async function doLoadConfig( let configLoadInterrupted = false; if (overrideConfigYaml || fs.existsSync(configYamlPath)) { - const result = await loadContinueConfigFromYaml( + const result = await loadContinueConfigFromYaml({ ide, ideSettings, ideInfo, uniqueId, llmLogger, - workOsAccessToken, overrideConfigYaml, platformConfigMetadata, controlPlaneClient, configYamlPath, orgScopeId, - ); + }); newConfig = result.config; errors = result.errors; configLoadInterrupted = result.configLoadInterrupted; @@ -110,6 +121,12 @@ export default async function doLoadConfig( // Remove ability have undefined errors, just have an array errors = [...(errors ?? [])]; + // Add rules from .continuerules files + const { rules, errors: continueRulesErrors } = + await getWorkspaceContinueRuleDotFiles(ide); + newConfig.rules.unshift(...rules); + errors.push(...continueRulesErrors); + // Rectify model selections for each role newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); @@ -258,7 +275,7 @@ async function injectControlPlaneProxyInfo( } }); - config.models.forEach((model) => { + config.modelsByRole.chat.forEach((model) => { if (model.providerName === "continue-proxy") { (model as ContinueProxy).controlPlaneProxyInfo = info; } diff --git a/core/config/selectedModels.ts b/core/config/selectedModels.ts index dd537665d..42b966cf7 100644 --- a/core/config/selectedModels.ts +++ b/core/config/selectedModels.ts @@ -1,6 +1,7 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ContinueConfig, ILLM } from ".."; +import { LLMConfigurationStatuses } from "../llm/constants"; import { GlobalContext, GlobalContextModelSelections, @@ -19,19 +20,20 @@ export function rectifySelectedModelsFromGlobalContext( let fellBack = false; - // chat and summarize not implemented yet - // default chat model is stored in GUI still - + // summarize not implemented yet const roles: ModelRole[] = [ "autocomplete", "apply", "edit", "embed", "rerank", + "chat", ]; + for (const role of roles) { let newModel: ILLM | null = null; const currentSelection = currentForProfile[role] ?? null; + if (currentSelection) { const match = continueConfig.modelsByRole[role].find( (m) => m.title === currentSelection, @@ -40,12 +42,23 @@ export function rectifySelectedModelsFromGlobalContext( newModel = match; } } + if (!newModel && continueConfig.modelsByRole[role].length > 0) { newModel = continueConfig.modelsByRole[role][0]; } + if (!(currentSelection === (newModel?.title ?? null))) { fellBack = true; } + + // Currently only check for configuration status for apply + if ( + role === "apply" && + newModel?.getConfigurationStatus() !== LLMConfigurationStatuses.VALID + ) { + continue; + } + configCopy.selectedModelByRole[role] = newModel; } diff --git a/core/config/types.ts b/core/config/types.ts index 3cf978540..f168bcbaa 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -658,7 +658,6 @@ declare global { remoteConfigServerUrl: string | undefined; remoteConfigSyncPeriod: number; userToken: string; - enableControlServerBeta: boolean; pauseCodebaseIndexOnStart: boolean; } @@ -958,7 +957,7 @@ declare global { cacheBehavior?: CacheBehavior; } - export interface EmbedOptions { + export interface JSONEmbedOptions { apiBase?: string; apiKey?: string; model?: string; diff --git a/core/config/util.test.ts b/core/config/util.test.ts new file mode 100644 index 000000000..e7de79e1b --- /dev/null +++ b/core/config/util.test.ts @@ -0,0 +1,45 @@ +import { PromptTemplate } from ".."; +import { serializePromptTemplates } from "./util"; + +describe("serializePromptTemplates", () => { + it("should return undefined for undefined input", () => { + expect(serializePromptTemplates(undefined)).toBeUndefined(); + }); + + it("should convert function templates to empty strings", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + template1: functionTemplate, + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ template1: "" }); + }); + + it("should pass through string templates unchanged", () => { + const templates: Record = { + template1: "This is a static template", + template2: "Another static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual(templates); + }); + + it("should handle mixed template types", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + function: functionTemplate, + string: "This is a static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ + function: "", + string: "This is a static template", + }); + }); +}); diff --git a/core/config/util.ts b/core/config/util.ts index ee827c2f9..9460986bb 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,13 +1,16 @@ import fs from "fs"; import os from "os"; +import { ModelConfig } from "@continuedev/config-yaml"; import { ContinueConfig, ExperimentalModelRoles, IDE, ILLM, - ModelDescription, + JSONModelDescription, + PromptTemplate, } from "../"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -22,16 +25,21 @@ function stringify(obj: any, indentation?: number): string { } export function addModel( - model: ModelDescription, + model: JSONModelDescription, role?: keyof ExperimentalModelRoles, ) { editConfigFile( (config) => { - if (config.models?.some((m: any) => stringify(m) === stringify(model))) { + if (config.models?.some((m) => stringify(m) === stringify(model))) { return config; } - if (config.models?.some((m: any) => m?.title === model.title)) { - model.title = `${model.title} (1)`; + + const numMatches = config.models?.reduce( + (prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev), + 0, + ); + if (numMatches !== 0) { + model.title = `${model.title} (${numMatches})`; } config.models.push(model); @@ -50,22 +58,34 @@ export function addModel( return config; }, (config) => { - if (config.models?.some((m: any) => m?.title === model.title)) { - model.title = `${model.title} (1)`; + const numMatches = config.models?.reduce( + (prev, curr) => + "name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev, + 0, + ); + if (numMatches !== 0) { + model.title = `${model.title} (${numMatches})`; } if (!config.models) { config.models = []; } - config.models.push({ + const desc: ModelConfig = { name: model.title, provider: model.provider, model: model.model, apiKey: model.apiKey, apiBase: model.apiBase, defaultCompletionOptions: model.completionOptions, - }); + }; + if (model.systemMessage) { + desc.chatOptions = { + baseSystemMessage: + DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage, + }; + } + config.models.push(desc); return config; }, ); @@ -94,7 +114,7 @@ export function getModelByRole( return undefined; } - const matchingModel = config.models.find( + const matchingModel = config.modelsByRole.chat.find( (model) => model.title === roleTitle, ); @@ -169,3 +189,22 @@ async function showUnsupportedCpuToast(ide: IDE) { ); } } + +/** + * This is required because users are only able to define prompt templates as a + * string, while internally we also allow prompt templates to be functions + * @param templates + * @returns + */ +export function serializePromptTemplates( + templates: Record | undefined, +): Record | undefined { + if (!templates) return undefined; + + return Object.fromEntries( + Object.entries(templates).map(([key, template]) => { + const serialized = typeof template === "function" ? "" : template; + return [key, serialized]; + }), + ); +} diff --git a/core/config/workspace/workspaceBlocks.ts b/core/config/workspace/workspaceBlocks.ts new file mode 100644 index 000000000..009e3cdff --- /dev/null +++ b/core/config/workspace/workspaceBlocks.ts @@ -0,0 +1,97 @@ +import { BlockType, ConfigYaml } from "@continuedev/config-yaml"; +import * as YAML from "yaml"; +import { IDE } from "../.."; +import { joinPathsToUri } from "../../util/uri"; + +function getContentsForNewBlock(blockType: BlockType): ConfigYaml { + const configYaml: ConfigYaml = { + name: `New ${blockType.slice(0, -1)}`, + version: "0.0.1", + schema: "v1", + }; + switch (blockType) { + case "context": + configYaml.context = [ + { + provider: "file", + }, + ]; + break; + case "models": + configYaml.models = [ + { + provider: "anthropic", + model: "claude-3-7-sonnet-latest", + apiKey: "${{ secrets.ANTHROPIC_API_KEY }}", + name: "Claude 3.7 Sonnet", + roles: ["chat", "edit"], + }, + ]; + break; + case "rules": + configYaml.rules = ["Always give concise responses"]; + break; + case "docs": + configYaml.docs = [ + { + name: "New docs", + startUrl: "https://docs.continue.dev", + }, + ]; + break; + case "prompts": + configYaml.prompts = [ + { + name: "New prompt", + description: "New prompt", + prompt: + "Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases", + }, + ]; + break; + case "mcpServers": + configYaml.mcpServers = [ + { + name: "New MCP server", + command: "npx", + args: ["-y", ""], + env: {}, + }, + ]; + break; + } + + return configYaml; +} + +export async function createNewWorkspaceBlockFile( + ide: IDE, + blockType: BlockType, +): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + throw new Error( + "No workspace directories found. Make sure you've opened a folder in your IDE.", + ); + } + + const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`); + + // Find the first available filename + let counter = 0; + let fileUri: string; + do { + const suffix = counter === 0 ? "" : `-${counter}`; + fileUri = joinPathsToUri( + baseDirUri, + `new-${blockType.slice(0, -1)}${suffix}.yaml`, + ); + counter++; + } while (await ide.fileExists(fileUri)); + + await ide.writeFile( + fileUri, + YAML.stringify(getContentsForNewBlock(blockType)), + ); + await ide.openFile(fileUri); +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 1edb48604..6afd0abf4 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -5,32 +5,34 @@ import { ConfigResult, ConfigValidationError, FQSN, + isAssistantUnrolledNonNullable, + MCPServer, ModelRole, PlatformClient, RegistryClient, + Rule, SecretResult, unrollAssistantFromContent, validateConfigYaml, } from "@continuedev/config-yaml"; -import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ContinueConfig, + ExperimentalMCPOptions, IContextProvider, IDE, IdeInfo, IdeSettings, ILLMLogger, + RuleWithSource, } from "../.."; import { slashFromCustomCommand } from "../../commands"; -import { AllRerankers } from "../../context/allRerankers"; import { MCPManagerSingleton } from "../../context/mcp"; import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; import { ControlPlaneClient } from "../../control-plane/client"; -import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders"; import FreeTrial from "../../llm/llms/FreeTrial"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; @@ -38,7 +40,6 @@ import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { allTools } from "../../tools"; import { GlobalContext } from "../../util/GlobalContext"; import { getConfigYamlPath } from "../../util/paths"; -import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; @@ -61,6 +62,35 @@ export class LocalPlatformClient implements PlatformClient { } } +function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { + if (typeof rule === "string") { + return { + rule: rule, + source: "rules-block", + }; + } else { + return { + source: "rules-block", + rule: rule.rule, + if: rule.if, + name: rule.name, + }; + } +} + +function convertYamlMcpToContinueMcp( + server: MCPServer, +): ExperimentalMCPOptions { + return { + transport: { + type: "stdio", + command: server.command, + args: server.args ?? [], + env: server.env, + }, + }; +} + async function loadConfigYaml( rawYaml: string, overrideConfigYaml: AssistantUnrolled | undefined, @@ -82,7 +112,6 @@ async function loadConfigYaml( await controlPlaneClient.getAccessToken(), getControlPlaneEnvSync( ideSettings.continueTestEnvironment, - ideSettings.enableControlServerBeta, ).CONTROL_PLANE_URL, ), { @@ -93,7 +122,15 @@ async function loadConfigYaml( renderSecrets: true, }, )); - const errors = validateConfigYaml(config); + + const errors = isAssistantUnrolledNonNullable(config) + ? validateConfigYaml(config) + : [ + { + fatal: true, + message: "Assistant includes blocks that don't exist", + }, + ]; if (errors?.some((error) => error.fatal)) { return { @@ -111,41 +148,31 @@ async function loadConfigYaml( }; } -async function configYamlToContinueConfig( - config: AssistantUnrolled, - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - llmLogger: ILLMLogger, - workOsAccessToken: string | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - allowFreeTrial: boolean = true, -): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { +async function configYamlToContinueConfig({ + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + platformConfigMetadata, + allowFreeTrial = true, +}: { + config: AssistantUnrolled; + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + allowFreeTrial: boolean; +}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { const localErrors: ConfigValidationError[] = []; + const continueConfig: ContinueConfig = { slashCommands: [], - models: [], tools: [...allTools], mcpServerStatuses: [], - systemMessage: undefined, - experimental: { - modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ - transport: { - type: "stdio", - command: mcpServer.command, - args: mcpServer.args ?? [], - env: mcpServer.env, - }, - })), - }, - docs: config.docs?.map((doc) => ({ - title: doc.name, - startUrl: doc.startUrl, - rootUrl: doc.rootUrl, - faviconUrl: doc.faviconUrl, - })), - rules: config.rules, contextProviders: [], modelsByRole: { chat: [], @@ -157,7 +184,7 @@ async function configYamlToContinueConfig( summarize: [], }, selectedModelByRole: { - chat: null, // not currently used - defaultModel on GUI is used + chat: null, edit: null, // not currently used apply: null, embed: null, @@ -165,14 +192,44 @@ async function configYamlToContinueConfig( rerank: null, summarize: null, }, - data: config.data, + rules: [], + }; + + // Right now, if there are any missing packages in the config, then we will just throw an error + if (!isAssistantUnrolledNonNullable(config)) { + return { + config: continueConfig, + errors: [ + { + message: "Found missing blocks in config.yaml", + fatal: true, + }, + ], + }; + } + + for (const rule of config.rules ?? []) { + continueConfig.rules.push(convertYamlRuleToContinueRule(rule)); + } + + continueConfig.data = config.data; + continueConfig.docs = config.docs?.map((doc) => ({ + title: doc.name, + startUrl: doc.startUrl, + rootUrl: doc.rootUrl, + faviconUrl: doc.faviconUrl, + })); + continueConfig.experimental = { + modelContextProtocolServers: config.mcpServers?.map( + convertYamlMcpToContinueMcp, + ), }; // Prompt files - try { const promptFiles = await getAllPromptFiles(ide, undefined, true); - for (const file of promptFiles) { + promptFiles.forEach((file) => { try { const slashCommand = slashCommandFromPromptFileV1( file.path, @@ -187,7 +244,7 @@ async function configYamlToContinueConfig( message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`, }); } - } + }); } catch (e) { localErrors.push({ fatal: false, @@ -208,9 +265,9 @@ async function configYamlToContinueConfig( }); // Models - const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; + const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { - model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified + model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified try { const llms = await llmsFromModelConfig({ model, @@ -222,10 +279,6 @@ async function configYamlToContinueConfig( config: continueConfig, }); - if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - continueConfig.models.push(...llms); - } - if (model.roles?.includes("chat")) { continueConfig.modelsByRole.chat.push(...llms); } @@ -247,59 +300,25 @@ async function configYamlToContinueConfig( } if (model.roles?.includes("embed")) { - const { provider, ...options } = model; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { + const { provider } = model; + if (provider === "transformers.js") { + if (ideInfo.ideType === "vscode") { continueConfig.modelsByRole.embed.push( - new embeddingsProviderClass(), + new TransformersJsEmbeddingsProvider(), ); } else { - continueConfig.modelsByRole.embed.push( - new embeddingsProviderClass( - { - ...options, - title: options.name, - }, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ), - ); + localErrors.push({ + fatal: false, + message: `Transformers.js embeddings provider not supported in this IDE.`, + }); } } else { - localErrors.push({ - fatal: false, - message: `Unsupported embeddings model provider found: ${provider}`, - }); + continueConfig.modelsByRole.embed.push(...llms); } } if (model.roles?.includes("rerank")) { - const { provider, ...options } = model; - const rerankerClass = AllRerankers[provider]; - if (rerankerClass) { - continueConfig.modelsByRole.rerank.push( - new rerankerClass( - { - ...options, - title: options.name, - }, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ), - ); - } else { - localErrors.push({ - fatal: false, - message: `Unsupported reranking model provider found: ${provider}`, - }); - } + continueConfig.modelsByRole.rerank.push(...llms); } } catch (e) { localErrors.push({ @@ -323,7 +342,7 @@ async function configYamlToContinueConfig( if (allowFreeTrial) { // Obtain auth token (iff free trial being used) - const freeTrialModels = continueConfig.models.filter( + const freeTrialModels = continueConfig.modelsByRole.chat.filter( (model) => model.providerName === "free-trial", ); if (freeTrialModels.length > 0) { @@ -338,14 +357,15 @@ async function configYamlToContinueConfig( message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`, }); // Remove free trial models - continueConfig.models = continueConfig.models.filter( - (model) => model.providerName !== "free-trial", - ); + continueConfig.modelsByRole.chat = + continueConfig.modelsByRole.chat.filter( + (model) => model.providerName !== "free-trial", + ); } } } else { // Remove free trial models - continueConfig.models = continueConfig.models.filter( + continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter( (model) => model.providerName !== "free-trial", ); } @@ -375,7 +395,10 @@ async function configYamlToContinueConfig( } return undefined; } - const instance: IContextProvider = new cls(context.params ?? {}); + const instance: IContextProvider = new cls({ + name: context.name, + ...context.params, + }); return instance; }) .filter((p) => !!p) ?? []) as IContextProvider[]; @@ -408,19 +431,29 @@ async function configYamlToContinueConfig( return { config: continueConfig, errors: localErrors }; } -export async function loadContinueConfigFromYaml( - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - llmLogger: ILLMLogger, - workOsAccessToken: string | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - controlPlaneClient: ControlPlaneClient, - configYamlPath: string | undefined, - orgScopeId: string | null, -): Promise> { +export async function loadContinueConfigFromYaml({ + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + overrideConfigYaml, + platformConfigMetadata, + controlPlaneClient, + configYamlPath, + orgScopeId, +}: { + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + overrideConfigYaml: AssistantUnrolled | undefined; + platformConfigMetadata: PlatformConfigMetadata | undefined; + controlPlaneClient: ControlPlaneClient; + configYamlPath: string | undefined; + orgScopeId: string | null; +}): Promise> { const rawYaml = overrideConfigYaml === undefined ? fs.readFileSync( @@ -446,32 +479,16 @@ export async function loadContinueConfigFromYaml( } const { config: continueConfig, errors: localErrors } = - await configYamlToContinueConfig( - configYamlResult.config, + await configYamlToContinueConfig({ + config: configYamlResult.config, ide, ideSettings, ideInfo, uniqueId, llmLogger, - workOsAccessToken, platformConfigMetadata, - ); - - try { - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - if (continueConfig.systemMessage) { - continueConfig.systemMessage += "\n\n" + systemPromptDotFile; - } else { - continueConfig.systemMessage = systemPromptDotFile; - } - } - } catch (e) { - localErrors.push({ - fatal: false, - message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`, + allowFreeTrial: true, }); - } // Apply shared config // TODO: override several of these values with user/org shared config diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index fa9c92cac..7b5994317 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -63,9 +63,8 @@ async function modelConfigToBaseLLM({ logger: llmLogger, uniqueId, title: model.name, - systemMessage: config.systemMessage, - rules: config.rules, promptTemplates: model.promptTemplates, + baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { tools: model.capabilities?.includes("tool_use"), uploadImage: model.capabilities?.includes("image_input"), diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts deleted file mode 100644 index e87cd06e3..000000000 --- a/core/context/allRerankers.ts +++ /dev/null @@ -1,21 +0,0 @@ -import Bedrock from "../llm/llms/Bedrock"; -import Cohere from "../llm/llms/Cohere"; -import FreeTrial from "../llm/llms/FreeTrial"; -import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI"; -import { LLMReranker } from "../llm/llms/llm"; -import SiliconFlow from "../llm/llms/SiliconFlow"; -import ContinueProxy from "../llm/llms/stubs/ContinueProxy"; -import Voyage from "../llm/llms/Voyage"; -import WatsonX from "../llm/llms/WatsonX"; - -export const AllRerankers: { [key: string]: any } = { - cohere: Cohere, - bedrock: Bedrock, - llm: LLMReranker, - voyage: Voyage, - watsonx: WatsonX, - "free-trial": FreeTrial, - "huggingface-tei": HuggingFaceTEI, - "continue-proxy": ContinueProxy, - siliconflow: SiliconFlow, -}; diff --git a/core/context/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index 278a12678..77e47c9f3 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider { this.options.title || ContinueProxyContextProvider.description.title, displayTitle: this.options.displayTitle || + this.options.name || ContinueProxyContextProvider.description.displayTitle, description: this.options.description || diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 067035806..bcca31177 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -16,18 +16,20 @@ class HttpContextProvider extends BaseContextProvider { override get description(): ContextProviderDescription { return { - title: this.options.title || "http", - displayTitle: this.options.displayTitle || "HTTP", + title: this.options.title || HttpContextProvider.description.title, + displayTitle: + this.options.displayTitle || + this.options.name || + HttpContextProvider.description.displayTitle, description: - this.options.description || - "Retrieve a context item from a custom server", - type: "normal", + this.options.description || HttpContextProvider.description.description, + type: HttpContextProvider.description.type, renderInlineAs: this.options.renderInlineAs || HttpContextProvider.description.renderInlineAs, }; } - + async getContextItems( query: string, extras: ContextProviderExtras, diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index d8eb90ef9..468aac6ec 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -45,7 +45,7 @@ async function getContextProviderExtras( config, embeddingsProvider: config.selectedModelByRole.embed, fetch: fetch, - llm: config.models[0], + llm: config.modelsByRole.chat[0], reranker: config.selectedModelByRole.rerank, selectedCode: [], }; diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 7d3ae9eb0..acbc20b59 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -21,16 +21,6 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -export const PRODUCTION_ENV: ControlPlaneEnv = { - DEFAULT_CONTROL_PLANE_PROXY_URL: - "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", - CONTROL_PLANE_URL: - "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", - AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, - WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, - APP_URL: "https://app.continue.dev/", -}; - const PRODUCTION_HUB_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", CONTROL_PLANE_URL: "https://api.continue.dev/", @@ -71,15 +61,11 @@ export async function getControlPlaneEnv( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; - return getControlPlaneEnvSync( - ideSettings.continueTestEnvironment, - ideSettings.enableControlServerBeta, - ); + return getControlPlaneEnvSync(ideSettings.continueTestEnvironment); } export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], - enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { // Note .local overrides .staging if (fs.existsSync(getLocalEnvironmentDotFilePath())) { @@ -90,10 +76,6 @@ export function getControlPlaneEnvSync( return STAGING_ENV; } - if (enableControlServerBeta === true) { - return PRODUCTION_ENV; - } - const env = ideTestEnvironment === "production" ? "hub" @@ -109,17 +91,12 @@ export function getControlPlaneEnvSync( ? STAGING_ENV : env === "test" ? TEST_ENV - : env === "hub" - ? PRODUCTION_HUB_ENV - : PRODUCTION_ENV; + : PRODUCTION_HUB_ENV; } export async function useHub( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; - if (ideSettings.enableControlServerBeta) { - return false; - } return ideSettings.continueTestEnvironment !== "none"; } diff --git a/core/core.ts b/core/core.ts index d59900cec..c8d30ce41 100644 --- a/core/core.ts +++ b/core/core.ts @@ -4,12 +4,7 @@ import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; -import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; -import { - setupBestConfig, - setupLocalConfig, - setupQuickstartConfig, -} from "./config/onboarding"; +import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; @@ -19,9 +14,9 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { getControlPlaneEnv } from "./control-plane/env"; import { DevDataSqliteDb } from "./data/devdataSqlite"; import { DataLogger } from "./data/log"; -import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { countTokens } from "./llm/countTokens"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -31,11 +26,20 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { + isProcessBackgrounded, + markProcessAsBackgrounded, +} from "./util/processTerminalBackgroundStates"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import { + ContextItemWithId, DiffLine, + IdeSettings, + ModelDescription, + RangeInFile, + type ContextItem, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -43,7 +47,14 @@ import { import { ConfigYaml } from "@continuedev/config-yaml"; import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { + setupBestConfig, + setupLocalConfig, + setupQuickstartConfig, +} from "./config/onboarding"; +import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp"; +import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; @@ -51,6 +62,43 @@ import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; +async function* streamDiffLinesGenerator( + configHandler: ConfigHandler, + abortedMessageIds: Set, + msg: Message, +): AsyncGenerator { + const data = msg.data; + + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Failed to load config"); + } + + const llm = config.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + for await (const diffLine of streamDiffLines({ + highlighted: data.highlighted, + prefix: data.prefix, + suffix: data.suffix, + llm, + rules: config.rules, + input: data.input, + language: data.language, + onlyOneInsertion: false, + overridePrompt: undefined, + })) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + break; + } + yield diffLine; + } +} + export class Core { configHandler: ConfigHandler; codebaseIndexerPromise: Promise; @@ -117,8 +165,7 @@ export class Core { this.messenger, ); - const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.onConnectionsRefreshed = async () => { + MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => { await this.configHandler.reloadConfig(); }; @@ -130,8 +177,6 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id || null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, - usingContinueForTeams: (await ideSettingsPromise) - .enableControlServerBeta, }); // update additional submenu context providers registered via VSCode API @@ -209,6 +254,11 @@ export class Core { (..._) => Promise.resolve([]), ); + this.registerMessageHandlers(ideSettingsPromise); + } + + /* eslint-disable max-lines-per-function */ + private registerMessageHandlers(ideSettingsPromise: Promise) { const on = this.messenger.on.bind(this.messenger); // Note, VsCode's in-process messenger doesn't do anything with this @@ -219,9 +269,7 @@ export class Core { stack: err.stack, }); - // Again, specifically for jetbrains to prevent duplicate error messages - // The same logic can currently be found in the webview protocol - // bc streaming errors are handled in the GUI + // just to prevent duplicate error messages in jetbrains (same logic in webview protocol) if ( ["llm/streamChat", "chatDescriber/describe"].includes( message.messageType, @@ -233,7 +281,6 @@ export class Core { } }); - // Special on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); }); @@ -262,12 +309,14 @@ export class Core { historyManager.save(msg.data); }); - // Dev data + on("history/clear", (msg) => { + historyManager.clearAll(); + }); + on("devdata/log", async (msg) => { void DataLogger.getInstance().logDevData(msg.data); }); - // Edit config on("config/addModel", (msg) => { const model = msg.data.model; addModel(model, msg.data.role); @@ -285,6 +334,11 @@ export class Core { await this.configHandler.reloadConfig(); }); + on("config/addLocalWorkspaceBlock", async (msg) => { + await createNewWorkspaceBlockFile(this.ide, msg.data.blockType); + await this.configHandler.reloadConfig(); + }); + on("config/openProfile", async (msg) => { await this.configHandler.openConfigProfile(msg.data.profileId); }); @@ -299,7 +353,13 @@ export class Core { }); on("config/refreshProfiles", async (msg) => { + const { selectOrgId, selectProfileId } = msg.data ?? {}; await this.configHandler.refreshAll(); + if (selectOrgId) { + await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId); + } else if (selectProfileId) { + await this.configHandler.setSelectedProfileId(selectProfileId); + } }); on("config/updateSharedConfig", async (msg) => { @@ -328,7 +388,7 @@ export class Core { }); on("mcp/reloadServer", async (msg) => { - mcpManager.refreshConnection(msg.data.id); + MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); // Context providers on("context/addDocs", async (msg) => { @@ -348,7 +408,6 @@ export class Core { if (!config) { return []; } - const items = await config.contextProviders ?.find((provider) => provider.description.title === msg.data.title) ?.loadSubmenuItems({ @@ -360,94 +419,7 @@ export class Core { return items || []; }); - on("context/getContextItems", async (msg) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - return []; - } - - const { name, query, fullInput, selectedCode, selectedModelTitle } = - msg.data; - - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const provider = - config.contextProviders?.find( - (provider) => provider.description.title === name, - ) ?? - [ - // user doesn't need these in their config.json for the shortcuts to work - // option+enter - new CurrentFileContextProvider({}), - // cmd+enter - new CodebaseContextProvider({}), - ].find((provider) => provider.description.title === name); - if (!provider) { - return []; - } - - try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; - - const items = await provider.getContextItems(query, { - config, - llm, - embeddingsProvider: config.selectedModelByRole.embed, - fullInput, - ide, - selectedCode, - reranker: config.selectedModelByRole.rerank, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - }); - - void Telemetry.capture( - "useContextProvider", - { - name: provider.description.title, - }, - true, - ); - - return items.map((item) => ({ - ...item, - id, - })); - } catch (e) { - let knownError = false; - - if (e instanceof Error) { - // After removing transformers JS embeddings provider from jetbrains - // Should no longer see this error - // if (e.message.toLowerCase().includes("embeddings provider")) { - // knownError = true; - // const toastOption = "See Docs"; - // void this.ide - // .showToast( - // "error", - // `Set up an embeddings model to use @${name}`, - // toastOption, - // ) - // .then((userSelection) => { - // if (userSelection === toastOption) { - // void this.ide.openUrl( - // "https://docs.continue.dev/customize/model-roles/embeddings", - // ); - // } - // }); - // } - } - if (!knownError) { - void this.ide.showToast( - "error", - `Error getting context items from ${name}: ${e}`, - ); - } - return []; - } - }); + on("context/getContextItems", this.getContextItems.bind(this)); on("context/getSymbolsForFiles", async (msg) => { const { uris } = msg.data; @@ -461,8 +433,6 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id ?? null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, - usingContinueForTeams: (await ideSettingsPromise) - .enableControlServerBeta, }; }); @@ -480,13 +450,19 @@ export class Core { this.configHandler, this.abortedMessageIds, msg, - ide, + this.ide, this.messenger, ), ); on("llm/complete", async (msg) => { - const model = await this.configHandler.llmFromTitle(msg.data.title); + const model = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } + const completion = await model.complete( msg.data.prompt, new AbortController().signal, @@ -494,31 +470,7 @@ export class Core { ); return completion; }); - on("llm/listModels", async (msg) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - return []; - } - - const model = - config.models.find((model) => model.title === msg.data.title) ?? - config.models.find((model) => model.title?.startsWith(msg.data.title)); - try { - if (model) { - return await model.listModels(); - } else { - if (msg.data.title === "Ollama") { - const models = await new Ollama({ model: "" }).listModels(); - return models; - } else { - return undefined; - } - } - } catch (e) { - console.debug(`Error listing Ollama models: ${e}`); - return undefined; - } - }); + on("llm/listModels", this.handleListModels.bind(this)); // Provide messenger to utils so they can interact with GUI + state TTS.messenger = this.messenger; @@ -529,9 +481,13 @@ export class Core { }); on("chatDescriber/describe", async (msg) => { - const currentModel = await this.configHandler.llmFromTitle( - msg.data.selectedModelTitle, - ); + const currentModel = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!currentModel) { + throw new Error("No chat model selected"); + } + return await ChatDescriber.describe(currentModel, {}, msg.data.text); }); @@ -551,93 +507,13 @@ export class Core { this.completionProvider.cancel(); }); - async function* streamDiffLinesGenerator( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, - ): AsyncGenerator { - const data = msg.data; - const llm = await configHandler.llmFromTitle(msg.data.modelTitle); - for await (const diffLine of streamDiffLines( - data.prefix, - data.highlighted, - data.suffix, - llm, - data.input, - data.language, - false, - undefined, - )) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - yield diffLine; - } - } - on("streamDiffLines", (msg) => streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg), ); - on("completeOnboarding", (msg) => { - const mode = msg.data.mode; + on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); - if (mode === "Custom") { - return; - } - - let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; - - switch (mode) { - case "Local": - editConfigYamlCallback = setupLocalConfig; - break; - - case "Quickstart": - editConfigYamlCallback = setupQuickstartConfig; - break; - - case "Best": - editConfigYamlCallback = setupBestConfig; - break; - - default: - console.error(`Invalid mode: ${mode}`); - editConfigYamlCallback = (config) => config; - } - - editConfigFile((c) => c, editConfigYamlCallback); - - void this.configHandler.reloadConfig(); - }); - - on("addAutocompleteModel", (msg) => { - const model = msg.data.model; - editConfigFile( - (config) => { - return { - ...config, - tabAutocompleteModel: model, - }; - }, - (config) => ({ - ...config, - models: [ - ...(config.models ?? []), - { - name: model.title, - provider: model.provider, - model: model.model, - apiKey: model.apiKey, - roles: ["autocomplete"], - apiBase: model.apiBase, - }, - ], - }), - ); - void this.configHandler.reloadConfig(); - }); + on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this)); on("stats/getTokensPerDay", async (msg) => { const rows = await DevDataSqliteDb.getTokensPerDay(); @@ -648,7 +524,6 @@ export class Core { return rows; }); - // Codebase indexing on("index/forceReIndex", async ({ data }) => { const { config } = await this.configHandler.loadConfig(); if (!config || config.disableIndexing) { @@ -678,65 +553,12 @@ export class Core { } }); - // File changes - // TODO - remove remaining logic for these from IDEs where possible - on("files/changed", async ({ data }) => { - if (data?.uris?.length) { - walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes - for (const uri of data.uris) { - const currentProfileUri = - this.configHandler.currentProfile?.profileDescription.uri ?? ""; - - if (URI.equal(uri, currentProfileUri)) { - // Trigger a toast notification to provide UI feedback that config has been updated - const showToast = - this.globalContext.get("showConfigUpdateToast") ?? true; - if (showToast) { - const selection = await this.ide.showToast( - "info", - "Config updated", - "Don't show again", - ); - if (selection === "Don't show again") { - this.globalContext.update("showConfigUpdateToast", false); - } - } - await this.configHandler.reloadConfig(); - continue; - } - - if ( - uri.endsWith(".continuerc.json") || - uri.endsWith(".prompt") || - uri.endsWith(SYSTEM_PROMPT_DOT_FILE) - ) { - await this.configHandler.reloadConfig(); - } else if ( - uri.endsWith(".continueignore") || - uri.endsWith(".gitignore") - ) { - // Reindex the workspaces - this.invoke("index/forceReIndex", { - shouldClearIndexes: true, - }); - } else { - const { config } = await this.configHandler.loadConfig(); - if (config && !config.disableIndexing) { - // Reindex the file - const ignore = await shouldIgnore(uri, this.ide); - if (!ignore) { - await this.refreshCodebaseIndexFiles([uri]); - } - } - } - } - } - }); - + // File changes - TODO - remove remaining logic for these from IDEs where possible + on("files/changed", this.handleFilesChanged.bind(this)); const refreshIfNotIgnored = async (uris: string[]) => { const toRefresh: string[] = []; for (const uri of uris) { - const ignore = await shouldIgnore(uri, ide); + const ignore = await shouldIgnore(uri, this.ide); if (!ignore) { toRefresh.push(uri); } @@ -785,11 +607,7 @@ export class Core { } }); - on("files/opened", async ({ data }) => { - if (data?.uris?.length) { - // Do something on files opened - } - }); + on("files/opened", async () => {}); // Docs, etc. indexing on("indexing/reindex", async (msg) => { @@ -804,7 +622,6 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - // this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet } }); on("docs/initStatuses", async (msg) => { @@ -813,20 +630,26 @@ export class Core { on("docs/getDetails", async (msg) => { return await this.docsService.getDetails(msg.data.startUrl); }); - // on("didChangeSelectedProfile", async (msg) => { - await this.configHandler.setSelectedProfileId(msg.data.id); + if (msg.data.id) { + await this.configHandler.setSelectedProfileId(msg.data.id); + } }); on("didChangeSelectedOrg", async (msg) => { - await this.configHandler.setSelectedOrgId( - msg.data.id, - msg.data.profileId, - ); + if (msg.data.id) { + await this.configHandler.setSelectedOrgId( + msg.data.id, + msg.data.profileId || undefined, + ); + } }); on("didChangeControlPlaneSessionInfo", async (msg) => { + this.messenger.send("sessionUpdate", { + sessionInfo: msg.data.sessionInfo, + }); await this.configHandler.updateControlPlaneSessionInfo( msg.data.sessionInfo, ); @@ -853,44 +676,352 @@ export class Core { } }); - on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } + on( + "tools/call", + async ({ data: { toolCall, selectedModelTitle }, messageId }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } - const tool = config.tools.find( - (t) => t.function.name === toolCall.function.name, - ); + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); - if (!tool) { - throw new Error(`Tool ${toolCall.function.name} not found`); - } + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + if (!config.selectedModelByRole.chat) { + throw new Error("No chat model selected"); + } - const contextItems = await callTool( - tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), + // Define a callback for streaming output updates + const onPartialOutput = (params: { + toolCallId: string; + contextItems: ContextItem[]; + }) => { + this.messenger.send("toolCallPartialOutput", params); + }; + + const contextItems = await callTool( tool, - }, + JSON.parse(toolCall.function.arguments || "{}"), + { + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + tool, + toolCallId: toolCall.id, + onPartialOutput, + }, + ); + + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + + return { contextItems }; + }, + ); + + on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + return this.isItemTooBig(item); + }); + + // Process state handlers + on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => { + markProcessAsBackgrounded(toolCallId); + }); + + on( + "process/isBackgrounded", + async ({ data: { toolCallId }, messageId }) => { + const isBackgrounded = isProcessBackgrounded(toolCallId); + return isBackgrounded; // Return true to indicate the message was handled successfully + }, + ); + } + + private async isItemTooBig(item: ContextItemWithId) { + const { config } = await this.configHandler.loadConfig(); + + if (!config) { + return false; + } + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + const tokens = countTokens(item.content); + + if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { + return true; + } + + return false; + } + + private handleAddAutocompleteModel( + msg: Message<{ + model: ModelDescription; + }>, + ) { + const model = msg.data.model; + editConfigFile( + (config) => { + return { + ...config, + tabAutocompleteModel: model, + }; + }, + (config) => ({ + ...config, + models: [ + ...(config.models ?? []), + { + name: model.title, + provider: model.provider, + model: model.model, + apiKey: model.apiKey, + roles: ["autocomplete"], + apiBase: model.apiBase, + }, + ], + }), + ); + void this.configHandler.reloadConfig(); + } + + private async handleFilesChanged({ + data, + }: Message<{ + uris?: string[]; + }>) { + if (data?.uris?.length) { + walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes + for (const uri of data.uris) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { + // Trigger a toast notification to provide UI feedback that config has been updated + const showToast = + this.globalContext.get("showConfigUpdateToast") ?? true; + if (showToast) { + const selection = await this.ide.showToast( + "info", + "Config updated", + "Don't show again", + ); + if (selection === "Don't show again") { + this.globalContext.update("showConfigUpdateToast", false); + } + } + await this.configHandler.reloadConfig(); + continue; + } + + if ( + uri.endsWith(".continuerc.json") || + uri.endsWith(".prompt") || + uri.endsWith(SYSTEM_PROMPT_DOT_FILE) + ) { + await this.configHandler.reloadConfig(); + } else if ( + uri.endsWith(".continueignore") || + uri.endsWith(".gitignore") + ) { + // Reindex the workspaces + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); + } else { + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } + } + } + } + } + } + + private async handleListModels(msg: Message<{ title: string }>) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + + const model = + config.modelsByRole.chat.find( + (model) => model.title === msg.data.title, + ) ?? + config.modelsByRole.chat.find((model) => + model.title?.startsWith(msg.data.title), ); - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); + try { + if (model) { + return await model.listModels(); + } else { + if (msg.data.title === "Ollama") { + const models = await new Ollama({ model: "" }).listModels(); + return models; + } else { + return undefined; + } } - - return { contextItems }; - }); + } catch (e) { + console.debug(`Error listing Ollama models: ${e}`); + return undefined; + } } + private async handleCompleteOnboarding(msg: Message<{ mode: string }>) { + const mode = msg.data.mode; + + if (mode === "Custom") { + return; + } + + let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; + + switch (mode) { + case "Local": + editConfigYamlCallback = setupLocalConfig; + break; + + case "Quickstart": + editConfigYamlCallback = setupQuickstartConfig; + break; + + case "Best": + editConfigYamlCallback = setupBestConfig; + break; + + default: + console.error(`Invalid mode: ${mode}`); + editConfigYamlCallback = (config) => config; + } + + editConfigFile((c) => c, editConfigYamlCallback); + + void this.configHandler.reloadConfig(); + } + + private getContextItems = async ( + msg: Message<{ + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + selectedModelTitle: string; + }>, + ) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + + const { name, query, fullInput, selectedCode } = msg.data; + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + const provider = + config.contextProviders?.find( + (provider) => provider.description.title === name, + ) ?? + [ + // user doesn't need these in their config.json for the shortcuts to work + // option+enter + new CurrentFileContextProvider({}), + // cmd+enter + new CodebaseContextProvider({}), + ].find((provider) => provider.description.title === name); + if (!provider) { + return []; + } + + try { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + + const items = await provider.getContextItems(query, { + config, + llm, + embeddingsProvider: config.selectedModelByRole.embed, + fullInput, + ide: this.ide, + selectedCode, + reranker: config.selectedModelByRole.rerank, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + }); + + void Telemetry.capture( + "useContextProvider", + { + name: provider.description.title, + }, + true, + ); + + return items.map((item) => ({ + ...item, + id, + })); + } catch (e) { + let knownError = false; + + if (e instanceof Error) { + // After removing transformers JS embeddings provider from jetbrains + // Should no longer see this error + // if (e.message.toLowerCase().includes("embeddings provider")) { + // knownError = true; + // const toastOption = "See Docs"; + // void this.ide + // .showToast( + // "error", + // `Set up an embeddings model to use @${name}`, + // toastOption, + // ) + // .then((userSelection) => { + // if (userSelection === toastOption) { + // void this.ide.openUrl( + // "https://docs.continue.dev/customize/model-roles/embeddings", + // ); + // } + // }); + // } + } + if (!knownError) { + void this.ide.showToast( + "error", + `Error getting context items from ${name}: ${e}`, + ); + } + return []; + } + }; + private indexingCancellationController: AbortController | undefined; private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) { console.debug( diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index f30751d70..8ca9a8154 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -2,10 +2,9 @@ import { DiffLine, ILLM } from "../.."; import { generateLines } from "../../diff/util"; import { supportedLanguages } from "../../util/treeSitter"; import { getUriFileExtension } from "../../util/uri"; - import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; -import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply"; +import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; function canUseInstantApply(filename: string) { const fileExtension = getUriFileExtension(filename); @@ -14,36 +13,44 @@ function canUseInstantApply(filename: string) { export async function applyCodeBlock( oldFile: string, - newFile: string, + newLazyFile: string, filename: string, llm: ILLM, - fastLlm: ILLM, -): Promise<[boolean, AsyncGenerator]> { - // This was buggy, removed for now, maybe forever - if (false && canUseInstantApply(filename)) { - const diffLines = await deterministicApplyLazyEdit( +): Promise<{ + isInstantApply: boolean; + diffLinesGenerator: AsyncGenerator; +}> { + if (canUseInstantApply(filename)) { + const diffLines = await deterministicApplyLazyEdit({ oldFile, - newFile, + newLazyFile, filename, - ); + onlyFullFileRewrite: true, + }); - // Fall back to LLM method if we couldn't apply deterministically if (diffLines !== undefined) { - const diffGenerator = generateLines(diffLines!); - return [true, diffGenerator]; + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; } } // If the code block is a diff - if (isUnifiedDiffFormat(newFile)) { + if (isUnifiedDiffFormat(newLazyFile)) { try { - const diffLines = applyUnifiedDiff(oldFile, newFile); - const diffGenerator = generateLines(diffLines!); - return [true, diffGenerator]; + const diffLines = applyUnifiedDiff(oldFile, newLazyFile); + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; } catch (e) { console.error("Failed to apply unified diff", e); } } - return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; + return { + isInstantApply: false, + diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), + }; } diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index 7590e5025..adfaafa5e 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -21,11 +21,11 @@ async function collectDiffs( ): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> { const ourDiffs: DiffLine[] = []; - for (const diffLine of (await deterministicApplyLazyEdit( + for (const diffLine of (await deterministicApplyLazyEdit({ oldFile, - newFile, + newLazyFile: newFile, filename, - )) ?? []) { + })) ?? []) { ourDiffs.push(diffLine); } diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 1e3a0ec4e..87fc7c66d 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -15,6 +15,11 @@ type AstReplacements = Array<{ replacementNodes: Parser.SyntaxNode[]; }>; +const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; +export function isLazyText(text: string): boolean { + return LAZY_COMMENT_REGEX.test(text); +} + function reconstructNewFile( oldFile: string, newFile: string, @@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks( } // TODO: If we don't have high confidence, return undefined to fall back to slower methods -export async function deterministicApplyLazyEdit( - oldFile: string, - newLazyFile: string, - filename: string, -): Promise { +export async function deterministicApplyLazyEdit({ + oldFile, + newLazyFile, + filename, + /** + * Using this as a flag to slowly reintroduce lazy applies. + * With this set, we will only attempt to deterministically apply + * when there are no lazy blocks and then just replace the whole file, + * and otherwise never use instant apply + */ + onlyFullFileRewrite = false, +}: { + oldFile: string; + newLazyFile: string; + filename: string; + onlyFullFileRewrite?: boolean; +}): Promise { const parser = await getParserForFile(filename); if (!parser) { return undefined; @@ -135,6 +152,20 @@ export async function deterministicApplyLazyEdit( let newTree = parser.parse(newLazyFile); let reconstructedNewFile: string | undefined = undefined; + if (onlyFullFileRewrite) { + if (!isLazyText(newTree.rootNode.text)) { + const diff = myersDiff(oldFile, newLazyFile); + + if (shouldRejectDiff(diff)) { + return undefined; + } + + return diff; + } else { + return undefined; + } + } + // If there is no lazy block anywhere, we add our own to the outsides // so that large chunks of the file don't get removed if (!findInAst(newTree.rootNode, isLazyBlock)) { @@ -198,11 +229,6 @@ export async function deterministicApplyLazyEdit( return diff; } -const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; -export function isLazyLine(text: string): boolean { - return LAZY_COMMENT_REGEX.test(text); -} - function isLazyBlock(node: Parser.SyntaxNode): boolean { // Special case for "{/* ... existing code ... */}" if ( @@ -213,7 +239,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean { return true; } - return node.type.includes("comment") && isLazyLine(node.text); + return node.type.includes("comment") && isLazyText(node.text); } function stringsWithinLevDistThreshold( diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 982e263e8..ce7af0ef7 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -16,7 +16,6 @@ export async function* streamLazyApply( filename: string, newCode: string, llm: ILLM, - fastLlm: ILLM, ): AsyncGenerator { const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); if (!promptFactory) { @@ -39,7 +38,7 @@ export async function* streamLazyApply( oldCode, linesBefore, linesAfter, - fastLlm, + llm, )) { yield line; } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 4f530cd60..1f5c8ffc0 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -1,4 +1,11 @@ -import { ChatMessage, DiffLine, ILLM, Prediction } from "../"; +import { + ChatMessage, + DiffLine, + ILLM, + Prediction, + RuleWithSource, + UserChatMessage, +} from "../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, @@ -10,7 +17,9 @@ import { } from "../autocomplete/filtering/streamTransforms/lineStream"; import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; +import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; +import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; function constructPrompt( @@ -47,16 +56,27 @@ function modelIsInept(model: string): boolean { return !(model.includes("gpt") || model.includes("claude")); } -export async function* streamDiffLines( - prefix: string, - highlighted: string, - suffix: string, - llm: ILLM, - input: string, - language: string | undefined, - onlyOneInsertion: boolean, - overridePrompt: ChatMessage[] | undefined, -): AsyncGenerator { +export async function* streamDiffLines({ + prefix, + highlighted, + suffix, + llm, + input, + language, + onlyOneInsertion, + overridePrompt, + rules, +}: { + prefix: string; + highlighted: string; + suffix: string; + llm: ILLM; + input: string; + language: string | undefined; + onlyOneInsertion: boolean; + overridePrompt: ChatMessage[] | undefined; + rules: RuleWithSource[]; +}): AsyncGenerator { void Telemetry.capture( "inlineEdit", { @@ -78,9 +98,54 @@ export async function* streamDiffLines( oldLines = []; } - const prompt = + let prompt = overridePrompt ?? constructPrompt(prefix, highlighted, suffix, llm, input, language); + + // Rules will be included with edit prompt + // If any rules are present this will result in using chat instead of legacy completion + const lastUserMessage: UserChatMessage | undefined = + typeof prompt === "string" + ? { + role: "user", + content: prompt, + } + : (findLast(prompt, (msg) => msg.role === "user") as + | UserChatMessage + | undefined); + + const systemMessage = getSystemMessageWithRules({ + currentModel: llm.model, + rules, + userMessage: lastUserMessage, + baseSystemMessage: undefined, + }); + + if (systemMessage) { + if (typeof prompt === "string") { + prompt = [ + { + role: "system", + content: systemMessage, + }, + { + role: "user", + content: prompt, + }, + ]; + } else { + const curSysMsg = prompt.find((msg) => msg.role === "system"); + if (curSysMsg) { + curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content; + } else { + prompt.unshift({ + role: "system", + content: systemMessage, + }); + } + } + } + const inept = modelIsInept(llm.model); const prediction: Prediction = { diff --git a/core/index.d.ts b/core/index.d.ts index e7fb25ef9..696876f07 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,5 +1,6 @@ -import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; +import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -76,39 +77,19 @@ export type PromptTemplateFunction = ( export type PromptTemplate = string | PromptTemplateFunction; -export interface ILLM extends LLMOptions { +type RequiredLLMOptions = + | "uniqueId" + | "contextLength" + | "embeddingId" + | "maxEmbeddingChunkSize" + | "maxEmbeddingBatchSize" + | "completionOptions"; + +export interface ILLM + extends Omit, + Required> { get providerName(): string; - uniqueId: string; - model: string; - - title?: string; - systemMessage?: string; - contextLength: number; - maxStopWords?: number; - completionOptions: CompletionOptions; - requestOptions?: RequestOptions; - promptTemplates?: Record; - templateMessages?: (messages: ChatMessage[]) => string; - llmLogger?: ILLMLogger; - llmRequestHook?: (model: string, prompt: string) => any; - apiKey?: string; - apiBase?: string; - cacheBehavior?: CacheBehavior; - capabilities?: ModelCapability; - roles?: ModelRole[]; - - deployment?: string; - apiVersion?: string; - apiType?: string; - region?: string; - projectId?: string; - - // Embedding options - embeddingId: string; - maxEmbeddingChunkSize: number; - maxEmbeddingBatchSize: number; - complete( prompt: string, signal: AbortSignal, @@ -162,6 +143,8 @@ export interface ILLM extends LLMOptions { otherData: Record, canPutWordsInModelsMouth?: boolean, ): string | ChatMessage[]; + + getConfigurationStatus(): LLMConfigurationStatuses; } export interface ModelInstaller { @@ -412,6 +395,7 @@ export interface ContextItem { icon?: string; uri?: ContextItemUri; hidden?: boolean; + status?: string; } export interface ContextItemWithId extends ContextItem { @@ -576,7 +560,7 @@ export interface LLMOptions { title?: string; uniqueId?: string; - systemMessage?: string; + baseChatSystemMessage?: string; contextLength?: number; maxStopWords?: number; completionOptions?: CompletionOptions; @@ -586,7 +570,6 @@ export interface LLMOptions { templateMessages?: (messages: ChatMessage[]) => string; logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; - rules?: Rule[]; apiKey?: string; // continueProperties @@ -717,7 +700,6 @@ export interface IdeSettings { remoteConfigServerUrl: string | undefined; remoteConfigSyncPeriod: number; userToken: string; - enableControlServerBeta: boolean; continueTestEnvironment: "none" | "production" | "staging" | "local"; pauseCodebaseIndexOnStart: boolean; } @@ -983,6 +965,8 @@ export interface ToolExtras { llm: ILLM; fetch: FetchFunction; tool: Tool; + toolCallId?: string; + onPartialOutput?: (params: { toolCallId: string, contextItems: ContextItem[] }) => void; } export interface Tool { @@ -1044,9 +1028,8 @@ export interface ModelDescription { model: string; apiKey?: string; - // continueProperties - apiKeyLocation?: string; apiBase?: string; + apiKeyLocation?: string; orgScopeId?: string | null; onPremProxyUrl?: string | null; @@ -1055,15 +1038,16 @@ export interface ModelDescription { maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; - systemMessage?: string; + baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + configurationStatus?: LLMConfigurationStatuses; } -export interface EmbedOptions { +export interface JSONEmbedOptions { apiBase?: string; apiKey?: string; model?: string; @@ -1084,7 +1068,7 @@ export interface EmbedOptions { projectId?: string; } -export interface EmbeddingsProviderDescription extends EmbedOptions { +export interface EmbeddingsProviderDescription extends JSONEmbedOptions { provider: string; } @@ -1308,11 +1292,39 @@ export interface AnalyticsConfig { clientKey?: string; } +export interface JSONModelDescription { + title: string; + provider: string; + model: string; + apiKey?: string; + apiBase?: string; + + contextLength?: number; + maxStopWords?: number; + template?: TemplateType; + completionOptions?: BaseCompletionOptions; + systemMessage?: string; + requestOptions?: RequestOptions; + cacheBehavior?: CacheBehavior; + + region?: string; + profile?: string; + modelArn?: string; + apiType?: "openai" | "azure"; + apiVersion?: string; + deployment?: string; + projectId?: string; + accountId?: string; + aiGatewaySlug?: string; + useLegacyCompletionsEndpoint?: boolean; + deploymentId?: string; +} + // config.json export interface SerializedContinueConfig { env?: string[]; allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; + models: JSONModelDescription[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; @@ -1323,7 +1335,7 @@ export interface SerializedContinueConfig { disableSessionTitles?: boolean; userToken?: string; embeddingsProvider?: EmbeddingsProviderDescription; - tabAutocompleteModel?: ModelDescription | ModelDescription[]; + tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; reranker?: RerankerDescription; @@ -1343,11 +1355,11 @@ export type ContinueRcJson = Partial & { export interface Config { /** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */ allowAnonymousTelemetry?: boolean; - /** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs. + /** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs. * A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both). * Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc. */ - models: (CustomLLM | ModelDescription)[]; + models: (CustomLLM | JSONModelDescription)[]; /** A system message to be followed by all of your models */ systemMessage?: string; /** The default completion options for all models */ @@ -1371,8 +1383,8 @@ export interface Config { /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | JSONModelDescription + | (CustomLLM | JSONModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1389,8 +1401,7 @@ export interface Config { // in the actual Continue source code export interface ContinueConfig { allowAnonymousTelemetry?: boolean; - models: ILLM[]; - systemMessage?: string; + // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; slashCommands: SlashCommand[]; @@ -1405,7 +1416,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: Rule[]; + rules: RuleWithSource[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1413,8 +1424,7 @@ export interface ContinueConfig { export interface BrowserSerializedContinueConfig { allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; - systemMessage?: string; + // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; slashCommands: SlashCommandDescription[]; @@ -1428,7 +1438,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: Rule[]; + rules: RuleWithSource[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; @@ -1475,4 +1485,20 @@ export type PackageDocsResult = { export interface TerminalOptions { reuseTerminal?: boolean; terminalName?: string; + waitForCompletion?: boolean; +} + +export interface RuleWithSource { + name?: string; + slug?: string; + source: + | "default" + | "model-chat-options" + | "rules-block" + | "json-systemMessage" + | ".continuerules"; + if?: string; + rule: string; + description?: string; + ruleFile?: string; } diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.skip.ts similarity index 100% rename from core/indexing/LanceDbIndex.test.ts rename to core/indexing/LanceDbIndex.test.skip.ts diff --git a/core/indexing/allEmbeddingsProviders.ts b/core/indexing/allEmbeddingsProviders.ts deleted file mode 100644 index 3986fa2c0..000000000 --- a/core/indexing/allEmbeddingsProviders.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { ILLM } from "../index.js"; -import Bedrock from "../llm/llms/Bedrock.js"; -import Cohere from "../llm/llms/Cohere.js"; -import DeepInfra from "../llm/llms/DeepInfra.js"; -import FreeTrial from "../llm/llms/FreeTrial.js"; -import FunctionNetwork from "../llm/llms/FunctionNetwork.js"; -import Gemini from "../llm/llms/Gemini.js"; -import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js"; -import LMStudio from "../llm/llms/LMStudio.js"; -import Mistral from "../llm/llms/Mistral.js"; -import NCompass from "../llm/llms/NCompass.js"; -import Nebius from "../llm/llms/Nebius.js"; -import Nvidia from "../llm/llms/Nvidia.js"; -import Ollama from "../llm/llms/Ollama.js"; -import OpenAI from "../llm/llms/OpenAI.js"; -import SageMaker from "../llm/llms/SageMaker.js"; -import Scaleway from "../llm/llms/Scaleway.js"; -import SiliconFlow from "../llm/llms/SiliconFlow.js"; -import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js"; -import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js"; -import VertexAI from "../llm/llms/VertexAI.js"; -import Voyage from "../llm/llms/Voyage.js"; -import WatsonX from "../llm/llms/WatsonX.js"; - -type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM; - -export const allEmbeddingsProviders: Record< - string, - EmbeddingsProviderConstructor -> = { - sagemaker: SageMaker, - bedrock: Bedrock, - ollama: Ollama, - "transformers.js": TransformersJsEmbeddingsProvider, - openai: OpenAI, - cohere: Cohere, - "free-trial": FreeTrial, - "function-network": FunctionNetwork, - "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, - gemini: Gemini, - "continue-proxy": ContinueProxy, - deepinfra: DeepInfra, - ncompass: NCompass, - nvidia: Nvidia, - voyage: Voyage, - mistral: Mistral, - nebius: Nebius, - vertexai: VertexAI, - watsonx: WatsonX, - lmstudio: LMStudio, - siliconflow: SiliconFlow, - scaleway: Scaleway, -}; diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 9677abfef..35ef612a2 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -39,7 +39,6 @@ // const ideSettingsPromise = Promise.resolve({ // remoteConfigSyncPeriod: 60, // userToken: "", -// enableControlServerBeta: false, // continueTestEnvironment: "none" as const, // pauseCodebaseIndexOnStart: false, // ideSettings: {} as any, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 99dc1d539..0bd7ba93a 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -64,6 +64,48 @@ export type AddParams = { favicon?: string; }; +const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + newFailedDocs.push(siteIndexingConfig); + globalContext.update("failedDocs", newFailedDocs); +}; + +const removeFromFailedGlobalContext = ( + siteIndexingConfig: SiteIndexingConfig, +) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + const newFailedDocs = failedDocs.filter( + (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); + globalContext.update("failedDocs", newFailedDocs); +}; + +const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => { + const globalContext = new GlobalContext(); + const failedDocs = globalContext.get("failedDocs") ?? []; + return failedDocs.find((d) => + siteIndexingConfigsAreEqual(siteIndexingConfig, d), + ); +}; + +const siteIndexingConfigsAreEqual = ( + config1: SiteIndexingConfig, + config2: SiteIndexingConfig, +) => { + return ( + config1.startUrl === config2.startUrl && + config1.faviconUrl === config2.faviconUrl && + config1.title === config2.title && + config1.maxDepth === config2.maxDepth && + config1.useLocalCrawling === config2.useLocalCrawling + ); +}; + /* General process: - On config update: @@ -433,12 +475,7 @@ export default class DocsService { // If not force-reindexing and has failed with same config, don't reattempt if (!forceReindex) { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const hasFailed = failedDocs.find((d) => - this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - if (hasFailed) { + if (hasIndexingFailed(siteIndexingConfig)) { console.log( `Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`, ); @@ -473,25 +510,6 @@ export default class DocsService { return; } - const markFailedInGlobalContext = () => { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const newFailedDocs = failedDocs.filter( - (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - newFailedDocs.push(siteIndexingConfig); - globalContext.update("failedDocs", newFailedDocs); - }; - - const removeFromFailedGlobalContext = () => { - const globalContext = new GlobalContext(); - const failedDocs = globalContext.get("failedDocs") ?? []; - const newFailedDocs = failedDocs.filter( - (d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d), - ); - globalContext.update("failedDocs", newFailedDocs); - }; - try { this.docsIndexingQueue.add(startUrl); @@ -630,7 +648,7 @@ export default class DocsService { }); // void this.ide.showToast("info", `Failed to index ${startUrl}`); - markFailedInGlobalContext(); + markFailedInGlobalContext(siteIndexingConfig); return; } @@ -690,7 +708,7 @@ export default class DocsService { providers: ["docs"], }); - removeFromFailedGlobalContext(); + removeFromFailedGlobalContext(siteIndexingConfig); } catch (e) { console.error( `Error indexing docs at: ${siteIndexingConfig.startUrl}`, @@ -711,7 +729,7 @@ export default class DocsService { status: "failed", progress: 1, }); - markFailedInGlobalContext(); + markFailedInGlobalContext(siteIndexingConfig); } finally { this.docsIndexingQueue.delete(startUrl); } @@ -973,10 +991,7 @@ export default class DocsService { (d) => d.startUrl === doc.startUrl, ); - if ( - oldConfigDoc && - !this.siteIndexingConfigsAreEqual(oldConfigDoc, doc) - ) { + if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) { changedDocs.push(doc); } else { if (forceReindex) { @@ -1163,24 +1178,11 @@ export default class DocsService { ); } - private siteIndexingConfigsAreEqual( - config1: SiteIndexingConfig, - config2: SiteIndexingConfig, - ) { - return ( - config1.startUrl === config2.startUrl && - config1.faviconUrl === config2.faviconUrl && - config1.title === config2.title && - config1.maxDepth === config2.maxDepth && - config1.useLocalCrawling === config2.useLocalCrawling - ); - } - private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesEquivalentDocExist = this.config.docs?.some((doc) => - this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig), + siteIndexingConfigsAreEqual(doc, siteIndexingConfig), ); if (!doesEquivalentDocExist) { diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 333c79e70..8532aa33b 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -32,6 +32,11 @@ const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; +export enum LLMConfigurationStatuses { + VALID = "valid", + MISSING_API_KEY = "missing-api-key", +} + export { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 69425d33e..b58a18c9f 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,24 +1,60 @@ -import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; +import { + ChatHistoryItem, + ChatMessage, + RuleWithSource, + TextMessagePart, + UserChatMessage, +} from "../"; +import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; +import { messageIsEmpty } from "./messages"; +import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -const DEFAULT_SYSTEM_MESSAGE = ` - Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'. +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8"; + +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ + + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' + + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For instance: + + \`\`\`typescript /path/to/file + // ... rest of code here ... + + {{ modified code here }} + + // ... rest of code here ... + + {{ another modification }} + + // ... rest of code here ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. `; const CANCELED_TOOL_CALL_MESSAGE = "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; -export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { +export function constructMessages( + history: ChatHistoryItem[], + baseChatSystemMessage: string | undefined, + rules: RuleWithSource[], + modelName: string, +): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", ); const msgs: ChatMessage[] = []; - msgs.push({ - role: "system", - content: DEFAULT_SYSTEM_MESSAGE, - }); - for (let i = 0; i < filteredHistory.length; i++) { const historyItem = filteredHistory[i]; @@ -26,9 +62,14 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { // Gather context items for user messages let content = normalizeToMessageParts(historyItem.message); - const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; - }); + const ctxItems = historyItem.contextItems + .map((ctxItem) => { + return { + type: "text", + text: `${ctxItem.content}\n`, + } as TextMessagePart; + }) + .filter((part) => !!part.text.trim()); content = [...ctxItems, ...content]; msgs.push({ @@ -46,6 +87,32 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { } } + const userMessage = findLast(msgs, (msg) => msg.role === "user") as + | UserChatMessage + | undefined; + const systemMessage = getSystemMessageWithRules({ + baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, + rules, + userMessage, + currentModel: modelName, + }); + if (systemMessage.trim()) { + msgs.unshift({ + role: "system", + content: systemMessage, + }); + } + + // We dispatch an empty assistant chat message to the history on submission. Don't send it + const lastMessage = msgs.at(-1); + if ( + lastMessage && + lastMessage.role === "assistant" && + messageIsEmpty(lastMessage) + ) { + msgs.pop(); + } + // Remove the "id" from all of the messages return msgs.map((msg) => { const { id, ...rest } = msg as any; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..fbe532208 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,13 +1,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { - ChatMessage, - MessageContent, - MessagePart, - UserChatMessage, -} from "../index.js"; +import { ChatMessage, MessageContent, MessagePart } from "../index.js"; -import { Rule } from "@continuedev/config-yaml"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -17,8 +11,12 @@ import { import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; -import { isRuleActive } from "./rules/isRuleActive.js"; -import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; +import { + addSpaceToAnyEmptyMessages, + chatMessageIsEmpty, + flattenMessages, + messageHasToolCalls, +} from "./messages.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -126,31 +124,6 @@ function countTokens( } } -function messageHasToolCalls(msg: ChatMessage): boolean { - return msg.role === "assistant" && !!msg.toolCalls; -} - -export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { - const flattened: ChatMessage[] = []; - - for (let i = 0; i < msgs.length; i++) { - const msg = msgs[i]; - - if ( - flattened.length > 0 && - flattened[flattened.length - 1].role === msg.role && - !messageHasToolCalls(msg) && - !messageHasToolCalls(flattened[flattened.length - 1]) - ) { - flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; - } else { - flattened.push(msg); - } - } - - return flattened; -} - function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -248,10 +221,19 @@ function summarize(message: ChatMessage): string { function pruneChatHistory( modelName: string, - chatHistory: ChatMessage[], + msgs: ChatMessage[], contextLength: number, tokensForCompletion: number, ): ChatMessage[] { + // Move system message to 2nd to last to give it priority + const systemMessage = msgs.find((msg) => msg.role === "system"); + const chatHistory: ChatMessage[] = msgs.filter( + (msg) => msg.role !== "system", + ); + if (systemMessage) { + chatHistory.splice(-1, 0, systemMessage); + } + let totalTokens = tokensForCompletion + chatHistory.reduce((acc, message) => { @@ -364,147 +346,17 @@ function pruneChatHistory( ); totalTokens = contextLength; } - return chatHistory; -} -function messageIsEmpty(message: ChatMessage): boolean { - if (typeof message.content === "string") { - return message.content.trim() === ""; - } - if (Array.isArray(message.content)) { - return message.content.every( - (item) => item.type === "text" && item.text?.trim() === "", - ); - } - return false; -} - -function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] { - return messages.map((message) => { - if (messageIsEmpty(message)) { - message.content = " "; - } - return message; - }); -} - -function chatMessageIsEmpty(message: ChatMessage): boolean { - switch (message.role) { - case "system": - case "user": - return ( - typeof message.content === "string" && message.content.trim() === "" - ); - case "assistant": - return ( - typeof message.content === "string" && - message.content.trim() === "" && - !message.toolCalls - ); - case "thinking": - case "tool": - return false; - } -} - -function addSystemMessage({ - messages, - systemMessage, - originalMessages, -}: { - messages: ChatMessage[]; - systemMessage: string | undefined; - originalMessages: ChatMessage[] | undefined; -}): ChatMessage[] { + // put system message back if applicable if ( - !(systemMessage && systemMessage.trim() !== "") && - originalMessages?.[0]?.role !== "system" + chatHistory.length > 1 && + chatHistory[chatHistory.length - 2].role === "system" ) { - return messages; + const movedSystemMessage = chatHistory.splice(-2, 1)[0]; + chatHistory.unshift(movedSystemMessage); } - let content = ""; - if (originalMessages?.[0]?.role === "system") { - content = renderChatMessage(originalMessages[0]); - } - if (systemMessage && systemMessage.trim() !== "") { - const shouldAddNewLines = content !== ""; - if (shouldAddNewLines) { - content += "\n\n"; - } - content += systemMessage; - } - - const systemChatMsg: ChatMessage = { - role: "system", - content, - }; - // Insert as second to last - messages.splice(-1, 0, systemChatMsg); - return messages; -} - -function getMessageStringContent(message?: UserChatMessage): string { - if (!message) { - return ""; - } - - if (typeof message.content === "string") { - return message.content; - } - - // Handle MessagePart array - return message.content - .map((part) => { - if (part.type === "text") { - return part.text; - } - - return ""; - }) - .join("\n"); -} - -const getSystemMessage = ({ - userMessage, - rules, - currentModel, -}: { - userMessage?: UserChatMessage; - rules: Rule[]; - currentModel: string; -}) => { - const messageStringContent = getMessageStringContent(userMessage); - const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); - - return rules - .filter((rule) => { - return isRuleActive({ - rule, - activePaths: filePathsFromMessage, - currentModel, - }); - }) - .map((rule) => { - if (typeof rule === "string") { - return rule; - } - return rule.rule; - }) - .join("\n"); -}; - -function getLastUserMessage( - messages: ChatMessage[], -): UserChatMessage | undefined { - // Iterate backwards through messages to find the last user message - for (let i = messages.length - 1; i >= 0; i--) { - if (messages[i].role === "user") { - return messages[i] as UserChatMessage; - } - } - - return undefined; + return chatHistory; } function compileChatMessages({ @@ -513,64 +365,19 @@ function compileChatMessages({ contextLength, maxTokens, supportsImages, - prompt, - functions, - systemMessage, - rules, }: { modelName: string; - msgs: ChatMessage[] | undefined; + msgs: ChatMessage[]; contextLength: number; maxTokens: number; supportsImages: boolean; - prompt: string | undefined; - functions: any[] | undefined; - systemMessage: string | undefined; - rules: Rule[]; }): ChatMessage[] { - let msgsCopy = msgs - ? msgs - .map((msg) => ({ ...msg })) - .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") - : []; + let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); + + msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - if (prompt) { - const promptMsg: ChatMessage = { - role: "user", - content: prompt, - }; - msgsCopy.push(promptMsg); - } - - const lastUserMessage = getLastUserMessage(msgsCopy); - - msgsCopy = addSystemMessage({ - messages: msgsCopy, - systemMessage: - systemMessage ?? - getSystemMessage({ - userMessage: lastUserMessage, - rules, - currentModel: modelName, - }), - originalMessages: msgs, - }); - - let functionTokens = 0; - if (functions) { - for (const func of functions) { - functionTokens += countTokens(JSON.stringify(func), modelName); - } - } - - if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { - throw new Error( - `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`, - ); - } - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -585,14 +392,9 @@ function compileChatMessages({ modelName, msgsCopy, contextLength, - functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY, + maxTokens + TOKEN_BUFFER_FOR_SAFETY, ); - if (history.length >= 2 && history[history.length - 2].role === "system") { - const movedSystemMessage = history.splice(-2, 1)[0]; - history.unshift(movedSystemMessage); - } - const flattenedHistory = flattenMessages(history); return flattenedHistory; @@ -602,6 +404,7 @@ export { compileChatMessages, countTokens, countTokensAsync, + flattenMessages, pruneLinesFromBottom, pruneLinesFromTop, pruneRawPromptFromTop, diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 7f535d1fd..7584e2122 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -35,7 +35,6 @@ describe("BaseLLM", () => { const options: LLMOptions = { model: "gpt-3.5-turbo", uniqueId: "testId", - systemMessage: "Test System Message", contextLength: 1024, completionOptions: { model: "some-model", @@ -62,7 +61,6 @@ describe("BaseLLM", () => { expect(instance.title).toBeDefined(); expect(instance.uniqueId).toBe("testId"); expect(instance.model).toBe("gpt-3.5-turbo"); - expect(instance.systemMessage).toBe("Test System Message"); expect(instance.contextLength).toBe(1024); expect(instance.completionOptions.maxTokens).toBe(150); expect(instance.requestOptions).toEqual({}); diff --git a/core/llm/index.ts b/core/llm/index.ts index 7544b5292..e3d8004bb 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { ModelRole, Rule } from "@continuedev/config-yaml"; +import { ModelRole } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -46,6 +46,7 @@ import { DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, + LLMConfigurationStatuses, } from "./constants.js"; import { compileChatMessages, @@ -125,7 +126,7 @@ export abstract class BaseLLM implements ILLM { model: string; title?: string; - systemMessage?: string; + baseChatSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; completionOptions: CompletionOptions; @@ -147,7 +148,6 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; - rules?: Rule[]; deployment?: string; apiVersion?: string; @@ -193,7 +193,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; - this.systemMessage = options.systemMessage; + this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; @@ -247,7 +247,6 @@ export abstract class BaseLLM implements ILLM { this.accountId = options.accountId; this.capabilities = options.capabilities; this.roles = options.roles; - this.rules = options.rules; this.deployment = options.deployment; this.apiVersion = options.apiVersion; @@ -265,6 +264,10 @@ export abstract class BaseLLM implements ILLM { this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; } + getConfigurationStatus() { + return LLMConfigurationStatuses.VALID; + } + protected createOpenAiAdapter() { return constructLlmApi({ provider: this.providerName as any, @@ -281,7 +284,6 @@ export abstract class BaseLLM implements ILLM { private _compileChatMessages( options: CompletionOptions, messages: ChatMessage[], - functions?: any[], ) { let contextLength = this.contextLength; if ( @@ -298,10 +300,6 @@ export abstract class BaseLLM implements ILLM { contextLength, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), - prompt: undefined, - functions, - systemMessage: this.systemMessage, - rules: this.rules ?? [], }); } @@ -310,45 +308,13 @@ export abstract class BaseLLM implements ILLM { return prompt; } + // NOTE system message no longer supported here + const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; - const systemMessage = this.systemMessage; - if (systemMessage) { - msgs.unshift({ role: "system", content: systemMessage }); - } - return this.templateMessages(msgs); } - private _compilePromptForLog( - prompt: string, - completionOptions: CompletionOptions, - ): string { - const completionOptionsLog = JSON.stringify( - { - contextLength: this.contextLength, - ...completionOptions, - }, - null, - 2, - ); - - let requestOptionsLog = ""; - if (this.requestOptions) { - requestOptionsLog = JSON.stringify(this.requestOptions, null, 2); - } - - return ( - "##### Completion options #####\n" + - completionOptionsLog + - (requestOptionsLog - ? "\n\n##### Request options #####\n" + requestOptionsLog - : "") + - "\n\n##### Prompt #####\n" + - prompt - ); - } - private _logEnd( model: string, prompt: string, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index cd48ef41b..5bec42d49 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,15 +30,17 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), - thinking: options.reasoning ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, - } : undefined, + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, tool_choice: options.toolChoice ? { - type: "tool", - name: options.toolChoice.function.name, - } + type: "tool", + name: options.toolChoice.function.name, + } : undefined, }; @@ -70,19 +72,23 @@ class Anthropic extends BaseLLM { } else if (message.role === "thinking" && !message.redactedThinking) { return { role: "assistant", - content: [{ - type: "thinking", - thinking: message.content, - signature: message.signature - }] + content: [ + { + type: "thinking", + thinking: message.content, + signature: message.signature, + }, + ], }; } else if (message.role === "thinking" && message.redactedThinking) { return { role: "assistant", - content: [{ - type: "redacted_thinking", - data: message.redactedThinking - }] + content: [ + { + type: "redacted_thinking", + data: message.redactedThinking, + }, + ], }; } @@ -172,11 +178,12 @@ class Anthropic extends BaseLLM { ); } - const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( + const systemMessage = stripImages( messages.filter((m) => m.role === "system")[0]?.content ?? "", ); + const shouldCacheSystemMessage = !!( + this.cacheBehavior?.cacheSystemMessage && systemMessage + ); const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { @@ -195,12 +202,12 @@ class Anthropic extends BaseLLM { messages: msgs, system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), signal, @@ -240,7 +247,11 @@ class Anthropic extends BaseLLM { // handle redacted thinking if (value.content_block.type === "redacted_thinking") { console.log("redacted thinking", value.content_block.data); - yield { role: "thinking", content: "", redactedThinking: value.content_block.data }; + yield { + role: "thinking", + content: "", + redactedThinking: value.content_block.data, + }; } break; case "content_block_delta": @@ -253,7 +264,11 @@ class Anthropic extends BaseLLM { yield { role: "thinking", content: value.delta.thinking }; break; case "signature_delta": - yield { role: "thinking", content: "", signature: value.delta.signature }; + yield { + role: "thinking", + content: "", + signature: value.delta.signature, + }; break; case "input_json_delta": if (!lastToolUseId || !lastToolUseName) { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 7fefbd329..430e4a93b 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,9 +14,10 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; +import { getSecureID } from "../utils/getSecureID.js"; interface ModelConfig { formatPayload: (text: string) => any; @@ -284,10 +285,13 @@ class Bedrock extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): any { + const systemMessage = stripImages( + messages.find((m) => m.role === "system")?.content ?? "", + ); const convertedMessages = this._convertMessages(messages); const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + !!systemMessage && this.cacheBehavior?.cacheSystemMessage; const enablePromptCaching = shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; @@ -304,10 +308,10 @@ class Bedrock extends BaseLLM { return { modelId: options.model, messages: convertedMessages, - system: this.systemMessage + system: systemMessage ? shouldCacheSystemMessage - ? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }] - : [{ text: this.systemMessage }] + ? [{ text: systemMessage }, { cachePoint: { type: "default" } }] + : [{ text: systemMessage }] : undefined, toolConfig: supportsTools && options.tools @@ -427,6 +431,9 @@ class Bedrock extends BaseLLM { // Standard text message if (typeof message.content === "string") { + if (addCaching) { + message.content += getSecureID(); + } const content: any[] = [{ text: message.content }]; if (addCaching) { content.push({ cachePoint: { type: "default" } }); @@ -444,6 +451,9 @@ class Bedrock extends BaseLLM { // Process all parts first message.content.forEach((part) => { if (part.type === "text") { + if (addCaching) { + part.text += getSecureID(); + } content.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try { diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 86834cb74..ecc9c5208 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -4,7 +4,7 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -67,6 +67,11 @@ class Cohere extends BaseLLM { ...this.requestOptions?.headers, }; + let preamble: string | undefined = undefined; + const systemMessage = messages.find((m) => m.role === "system")?.content; + if (systemMessage) { + preamble = stripImages(systemMessage); + } const resp = await this.fetch(new URL("chat", this.apiBase), { method: "POST", headers, @@ -74,7 +79,7 @@ class Cohere extends BaseLLM { ...this._convertArgs(options), message: messages.pop()?.content, chat_history: this._convertMessages(messages), - preamble: this.systemMessage, + preamble, }), signal, }); diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1c5d24aee..1e3c35449 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,3 +1,4 @@ +import { v4 as uuidv4 } from "uuid"; import { AssistantChatMessage, ChatMessage, @@ -7,17 +8,18 @@ import { TextMessagePart, ToolCallDelta, } from "../../index.js"; -import { findLast } from "../../util/findLast.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; import { + GeminiChatContent, GeminiChatContentPart, GeminiChatRequestBody, GeminiChatResponse, GeminiGenerationConfig, GeminiToolFunctionDeclaration, -} from "./gemini-types.js"; + convertContinueToolToGeminiFunction, +} from "./gemini-types"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -155,14 +157,8 @@ class Gemini extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - // Ensure this.apiBase is used if available, otherwise use default - const apiBase = - this.apiBase || - Gemini.defaultOptions?.apiBase || - "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); + const isV1API = this.apiBase?.includes("/v1/"); - // Conditionally apply removeSystemMessage const convertedMsgs = isV1API ? this.removeSystemMessage(messages) : messages; @@ -204,20 +200,27 @@ class Gemini extends BaseLLM { options: CompletionOptions, isV1API: boolean, ): GeminiChatRequestBody { + const toolCallIdToNameMap = new Map(); + messages.forEach((msg) => { + if (msg.role === "assistant" && msg.toolCalls) { + msg.toolCalls.forEach((call) => { + if (call.id && call.function?.name) { + toolCallIdToNameMap.set(call.id, call.function.name); + } + }); + } + }); + const systemMessage = messages.find( + (msg) => msg.role === "system", + )?.content; + const body: GeminiChatRequestBody = { contents: messages .filter((msg) => !(msg.role === "system" && isV1API)) .map((msg) => { if (msg.role === "tool") { - let fn_name = ""; - const lastToolCallMessage = findLast( - messages, - (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, - ) as AssistantChatMessage; - if (lastToolCallMessage) { - fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!; - } - if (!fn_name) { + let functionName = toolCallIdToNameMap.get(msg.toolCallId); + if (!functionName) { console.warn( "Sending tool call response for unidentified tool call", ); @@ -227,7 +230,8 @@ class Gemini extends BaseLLM { parts: [ { functionResponse: { - name: fn_name || "unknown", + id: msg.toolCallId, + name: functionName || "unknown", response: { output: msg.content, // "output" key is opinionated - not all functions will output objects }, @@ -236,28 +240,35 @@ class Gemini extends BaseLLM { ], }; } - const assistantMsg = { - role: - msg.role === "assistant" ? ("model" as const) : ("user" as const), + if (msg.role === "assistant") { + const assistantMsg: GeminiChatContent = { + role: "model", + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this.continuePartToGeminiPart), + }; + if (msg.toolCalls) { + msg.toolCalls.forEach((toolCall) => { + if (toolCall.function?.name && toolCall.function?.arguments) { + assistantMsg.parts.push({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments), + }, + }); + } + }); + } + return assistantMsg; + } + return { + role: "user", parts: typeof msg.content === "string" ? [{ text: msg.content }] : msg.content.map(this.continuePartToGeminiPart), }; - if (msg.role === "assistant" && msg.toolCalls) { - msg.toolCalls.forEach((toolCall) => { - if (toolCall.function?.name && toolCall.function?.arguments) { - assistantMsg.parts.push({ - functionCall: { - name: toolCall.function.name, - args: JSON.parse(toolCall.function.arguments), - }, - }); - } - }); - } - - return assistantMsg; }), }; if (options) { @@ -266,8 +277,10 @@ class Gemini extends BaseLLM { // https://ai.google.dev/gemini-api/docs/api-versions if (!isV1API) { - if (this.systemMessage) { - body.systemInstruction = { parts: [{ text: this.systemMessage }] }; + if (systemMessage) { + body.systemInstruction = { + parts: [{ text: stripImages(systemMessage) }], + }; } // Convert and add tools if present if (options.tools?.length) { @@ -276,77 +289,12 @@ class Gemini extends BaseLLM { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; options.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - // const paramType = "TYPE_UNSPECIFIED" - // | "STRING" - // | "NUMBER" - // | "INTEGER" - // | "BOOLEAN" - // | "ARRAY" - // | "OBJECT" - - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: tool.function.parameters.type.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertContinueToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); if (functions.length) { @@ -397,75 +345,39 @@ class Gemini extends BaseLLM { // Check for existence of each level before accessing the final 'text' property const content = data?.candidates?.[0]?.content; if (content) { - const supportedParts: MessagePart[] = []; + const textParts: MessagePart[] = []; const toolCalls: ToolCallDelta[] = []; - // Process all parts first to maintain order - const processedParts: Array<{ - type: "content" | "tool" | "toolCall"; - data: any; - }> = []; - for (const part of content.parts) { if ("text" in part) { - supportedParts.push({ type: "text", text: part.text }); - } else if ("inlineData" in part) { - supportedParts.push({ - type: "imageUrl", - imageUrl: { - url: `data:image/jpeg;base64,${part.inlineData.data}`, - }, - }); + textParts.push({ type: "text", text: part.text }); } else if ("functionCall" in part) { - // Queue function call - processedParts.push({ - type: "toolCall", - data: { - type: "function", - id: "", // Not supported by gemini - function: { - name: part.functionCall.name, - arguments: - typeof part.functionCall.args === "string" - ? part.functionCall.args - : JSON.stringify(part.functionCall.args), - }, - }, - }); - } else if ("functionResponse" in part) { - // Queue function response - processedParts.push({ - type: "tool", - data: { - role: "tool", - content: part.functionResponse.response.output as string, - toolCallId: part.functionResponse.name, + toolCalls.push({ + type: "function", + id: part.functionCall.id ?? uuidv4(), + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), }, }); } else { + // Note: function responses shouldn't be streamed, images not supported console.warn("Unsupported gemini part type received", part); } } - // If we have supported content parts, yield them first - if (supportedParts.length) { - yield { - role: "assistant", - content: supportedParts, - }; + const assistantMessage: AssistantChatMessage = { + role: "assistant", + content: textParts.length ? textParts : "", + }; + if (toolCalls.length > 0) { + assistantMessage.toolCalls = toolCalls; } - - // Then process tool calls and responses in order - for (const part of processedParts) { - if (part.type === "toolCall") { - yield { - role: "assistant", - content: "", - toolCalls: [part.data], - }; - } else if (part.type === "tool") { - yield part.data; - } + if (textParts.length || toolCalls.length) { + yield assistantMessage; } } else { // Handle the case where the expected data structure is not found @@ -489,10 +401,8 @@ class Gemini extends BaseLLM { `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, this.apiBase, ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); + + const isV1API = !!this.apiBase?.includes("/v1/"); // Convert chat messages to contents const body = this.prepareBody(messages, options, isV1API); diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index a8b7e08b3..4833405ae 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM { ...this.requestOptions?.headers, }; - const resp = await this.fetch(new URL("completion", this.apiBase), { + const resp = await this.fetch(new URL("completions", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 139d033ab..6ac50795a 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -288,7 +288,10 @@ class OpenAI extends BaseLLM { // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' - body.parallel_tool_calls = false; + // o3 does not support this + if (!body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; diff --git a/core/llm/llms/Relace.ts b/core/llm/llms/Relace.ts index f7a27c9e3..d65a94dc1 100644 --- a/core/llm/llms/Relace.ts +++ b/core/llm/llms/Relace.ts @@ -1,4 +1,5 @@ import { LLMOptions } from "../.."; +import { LLMConfigurationStatuses } from "../constants"; import { LlmApiRequestType } from "../openaiTypeConverters"; import OpenAI from "./OpenAI"; @@ -9,4 +10,12 @@ export class Relace extends OpenAI { apiBase: "https://instantapply.endpoint.relace.run/v1/", }; protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"]; + + getConfigurationStatus() { + if (!this.apiKey) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } } diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index c394ed29f..44a15c61d 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -80,16 +80,6 @@ class Replicate extends BaseLLM { } } } - - // protected async *_streamChat( - // messages: ChatMessage[], - // options: CompletionOptions - // ): AsyncGenerator { - // const resp = await this.complete( - // stripImages(messages[0]?.content || ""), - // options - // ); - // } } export default Replicate; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 1b75cb690..84f471c6f 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,7 +1,7 @@ import { GoogleAuth } from "google-auth-library"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse, streamSse } from "../stream.js"; @@ -11,7 +11,7 @@ import Gemini from "./Gemini.js"; class VertexAI extends BaseLLM { static providerName = "vertexai"; declare apiBase: string; - declare vertexProvider: string; + declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown"; declare anthropicInstance: Anthropic; declare geminiInstance: Gemini; @@ -92,13 +92,13 @@ class VertexAI extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const filteredSystemMessages : ChatMessage[] = messages.filter((m) => m.role === "system"); - let systemMessage: string = ""; - if(filteredSystemMessages.length > 0) { - systemMessage = renderChatMessage(filteredSystemMessages[0]); - } + const systemMessage = stripImages( + messages.filter((m) => m.role === "system")[0]?.content ?? "", + ); + const shouldCacheSystemMessage = !!( + this.cacheBehavior?.cacheSystemMessage && systemMessage + ); + const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, this.apiBase, @@ -118,7 +118,7 @@ class VertexAI extends BaseLLM { ? [ { type: "text", - text: this.systemMessage, + text: systemMessage, cache_control: { type: "ephemeral" }, }, ] @@ -142,8 +142,7 @@ class VertexAI extends BaseLLM { } } - //Gemini - + // Gemini private async *streamChatGemini( messages: ChatMessage[], options: CompletionOptions, @@ -306,7 +305,7 @@ class VertexAI extends BaseLLM { yield (await resp.json()).predictions[0].content; } - //Manager functions + // Manager functions protected async *_streamChat( messages: ChatMessage[], @@ -328,6 +327,8 @@ class VertexAI extends BaseLLM { } else { if (options.model.includes("bison")) { yield* this.streamChatBison(convertedMsgs, options); + } else { + throw new Error(`Unsupported model: ${options.model}`); } } } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 7f1fe2e0c..ac91d3fa9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -1,4 +1,9 @@ -import { ChatMessage, Chunk, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + Chunk, + CompletionOptions, + LLMOptions, +} from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -139,24 +144,24 @@ class WatsonX extends BaseLLM { } protected async updateWatsonxToken() { - var now = new Date().getTime() / 1000; - if ( - watsonxToken === undefined || - now > watsonxToken.expiration || - watsonxToken.token === undefined - ) { - watsonxToken = await this.getBearerToken(); - } else { - console.log( - `Reusing token (expires in ${ - (watsonxToken.expiration - now) / 60 - } mins)`, - ); - } - if (watsonxToken.token === undefined) { - throw new Error("Something went wrong. Check your credentials, please."); - } + var now = new Date().getTime() / 1000; + if ( + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined + ) { + watsonxToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 + } mins)`, + ); } + if (watsonxToken.token === undefined) { + throw new Error("Something went wrong. Check your credentials, please."); + } + } protected async _complete( prompt: string, @@ -312,64 +317,60 @@ class WatsonX extends BaseLLM { return embeddings.map((e: any) => e.embedding); } - async rerank(query: string, chunks: Chunk[]): Promise { - if (!query || !chunks.length) { - throw new Error("Query and chunks must not be empty"); - } - try { - await this.updateWatsonxToken(); - - const headers = { - "Content-Type": "application/json", - Authorization: `${ - watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxToken.token}`, - }; - - const payload: any = { - inputs: chunks.map((chunk) => ({ text: chunk.content })), - query: query, - parameters: { - truncate_input_tokens: 500, - return_options: { - top_n: chunks.length - }, + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + try { + await this.updateWatsonxToken(); + + const headers = { + "Content-Type": "application/json", + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, + }; + + const payload: any = { + inputs: chunks.map((chunk) => ({ text: chunk.content })), + query: query, + parameters: { + truncate_input_tokens: 500, + return_options: { + top_n: chunks.length, }, - model_id: this.model, - project_id: this.projectId, - }; + }, + model_id: this.model, + project_id: this.projectId, + }; - const resp = await this.fetch( - new URL( - `${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`, - ), - { - method: "POST", - headers: headers, - body: JSON.stringify(payload), - }, - ); + const resp = await this.fetch( + new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`), + { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }, + ); - if (!resp.ok) { - throw new Error(`Failed to rerank chunks: ${await resp.text()}`); - } - const data = await resp.json(); - const ranking = data.results; - - if (!ranking) { - throw new Error("Empty response received from Watsonx"); - } - - // Sort results by index to maintain original order - return ranking - .sort((a: any, b: any) => a.index - b.index) - .map((result: any) => result.score); - - } catch (error) { - console.error("Error in WatsonxReranker.rerank:", error); - throw error; + if (!resp.ok) { + throw new Error(`Failed to rerank chunks: ${await resp.text()}`); } + const data = await resp.json(); + const ranking = data.results; + + if (!ranking) { + throw new Error("Empty response received from Watsonx"); + } + + // Sort results by index to maintain original order + return ranking + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.score); + } catch (error) { + console.error("Error in WatsonxReranker.rerank:", error); + throw error; + } } } diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts index b9fb52c1d..355d1c942 100644 --- a/core/llm/llms/gemini-types.ts +++ b/core/llm/llms/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { Tool } from "../.."; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,70 +17,225 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; } +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertContinueToolToGeminiFunction( + tool: Tool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; +} + +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; @@ -88,7 +244,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cef09098c..c932b5db4 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -3,10 +3,11 @@ import { IdeSettings, ILLM, ILLMLogger, + JSONModelDescription, LLMOptions, - ModelDescription, } from "../.."; import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; @@ -27,6 +28,7 @@ import FunctionNetwork from "./FunctionNetwork"; import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; +import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEI"; import HuggingFaceTGI from "./HuggingFaceTGI"; import Inception from "./Inception"; import Kindo from "./Kindo"; @@ -56,6 +58,7 @@ import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; +import Voyage from "./Voyage"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; @@ -73,6 +76,7 @@ export const LLMClasses = [ Together, Novita, HuggingFaceTGI, + HuggingFaceTEIEmbeddingsProvider, HuggingFaceInferenceAPI, Kindo, LlamaCpp, @@ -109,16 +113,16 @@ export const LLMClasses = [ Scaleway, Relace, Inception, + Voyage, ]; export async function llmFromDescription( - desc: ModelDescription, + desc: JSONModelDescription, readFile: (filepath: string) => Promise, uniqueId: string, ideSettings: IdeSettings, llmLogger: ILLMLogger, completionOptions?: BaseCompletionOptions, - systemMessage?: string, ): Promise { const cls = LLMClasses.find((llm) => llm.providerName === desc.provider); @@ -131,9 +135,15 @@ export async function llmFromDescription( ...desc.completionOptions, }; - systemMessage = desc.systemMessage ?? systemMessage; - if (systemMessage !== undefined) { - systemMessage = await renderTemplatedString(systemMessage, readFile, {}); + let baseChatSystemMessage: string | undefined = undefined; + if (desc.systemMessage !== undefined) { + baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; + baseChatSystemMessage += "\n\n"; + baseChatSystemMessage += await renderTemplatedString( + desc.systemMessage, + readFile, + {}, + ); } let options: LLMOptions = { @@ -145,7 +155,7 @@ export async function llmFromDescription( finalCompletionOptions.maxTokens ?? cls.defaultOptions?.completionOptions?.maxTokens, }, - systemMessage, + baseChatSystemMessage, logger: llmLogger, uniqueId, }; diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 181db2abd..e43e2bfe2 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,10 +1,15 @@ -import { ContinueProperties } from "@continuedev/config-yaml"; +import { + ContinueProperties, + decodeSecretLocation, + SecretType, +} from "@continuedev/config-yaml"; import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; import type { Chunk, LLMOptions } from "../../../index.js"; +import { LLMConfigurationStatuses } from "../../constants.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { @@ -49,6 +54,19 @@ class ContinueProxy extends OpenAI { }; } + getConfigurationStatus() { + if (!this.apiKeyLocation) { + return LLMConfigurationStatuses.VALID; + } + + const secretLocation = decodeSecretLocation(this.apiKeyLocation); + if (secretLocation.secretType === SecretType.NotFound) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } + protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; diff --git a/core/llm/flattenMessages.test.ts b/core/llm/messages.test.ts similarity index 100% rename from core/llm/flattenMessages.test.ts rename to core/llm/messages.test.ts diff --git a/core/llm/messages.ts b/core/llm/messages.ts new file mode 100644 index 000000000..d3f7ab477 --- /dev/null +++ b/core/llm/messages.ts @@ -0,0 +1,69 @@ +import { ChatMessage } from ".."; + +export function messageHasToolCalls(msg: ChatMessage): boolean { + return msg.role === "assistant" && !!msg.toolCalls; +} + +export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { + const flattened: ChatMessage[] = []; + + for (let i = 0; i < msgs.length; i++) { + const msg = msgs[i]; + + if ( + flattened.length > 0 && + flattened[flattened.length - 1].role === msg.role && + !messageHasToolCalls(msg) && + !messageHasToolCalls(flattened[flattened.length - 1]) + ) { + flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; + } else { + flattened.push(msg); + } + } + + return flattened; +} + +export function messageIsEmpty(message: ChatMessage): boolean { + if (typeof message.content === "string") { + return message.content.trim() === ""; + } + if (Array.isArray(message.content)) { + return message.content.every( + (item) => item.type === "text" && item.text?.trim() === "", + ); + } + return false; +} + +// some providers don't support empty messages +export function addSpaceToAnyEmptyMessages( + messages: ChatMessage[], +): ChatMessage[] { + return messages.map((message) => { + if (messageIsEmpty(message)) { + message.content = " "; + } + return message; + }); +} + +export function chatMessageIsEmpty(message: ChatMessage): boolean { + switch (message.role) { + case "system": + case "user": + return ( + typeof message.content === "string" && message.content.trim() === "" + ); + case "assistant": + return ( + typeof message.content === "string" && + message.content.trim() === "" && + !message.toolCalls + ); + case "thinking": + case "tool": + return false; + } +} diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts new file mode 100644 index 000000000..2387145d4 --- /dev/null +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -0,0 +1,35 @@ +import { RuleWithSource, UserChatMessage } from "../.."; +import { renderChatMessage } from "../../util/messageContent"; +import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; +import { isRuleActive } from "./isRuleActive"; + +export const getSystemMessageWithRules = ({ + baseSystemMessage, + userMessage, + rules, + currentModel, +}: { + baseSystemMessage?: string; + userMessage: UserChatMessage | undefined; + rules: RuleWithSource[]; + currentModel: string; +}) => { + const filePathsFromMessage = userMessage + ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) + : []; + + let systemMessage = baseSystemMessage ?? ""; + for (const rule of rules) { + if ( + isRuleActive({ + rule, + activePaths: filePathsFromMessage, + currentModel, + }) + ) { + systemMessage += `\n\n${rule.rule}`; + } + } + + return systemMessage; +}; diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts index f50b9972a..89e06e148 100644 --- a/core/llm/rules/isRuleActive.test.ts +++ b/core/llm/rules/isRuleActive.test.ts @@ -1,10 +1,12 @@ +import { RuleWithSource } from "../.."; import { isRuleActive } from "./isRuleActive"; describe("isRuleActive", () => { - const rule = { + const rule: RuleWithSource = { name: "My Rule", rule: "Do no harm", if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', + source: "rules-block", }; it("should return false when activePaths is empty", () => { diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 47125c644..9c80f67ec 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -1,6 +1,6 @@ -import { Rule } from "@continuedev/config-yaml"; import { compileExpression } from "filtrex"; import { minimatch } from "minimatch"; +import { RuleWithSource } from "../.."; const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; @@ -52,14 +52,10 @@ export const isRuleActive = ({ activePaths, currentModel, }: { - rule: Rule; + rule: RuleWithSource; activePaths: string[]; currentModel: string; }): boolean => { - if (typeof rule === "string") { - return true; - } - if (rule.if) { return evaluateIf({ condition: rule.if, activePaths, currentModel }); } diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 9b1ea87b3..223b5b20e 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -23,19 +23,22 @@ export async function* llmStreamChat( void TTS.kill(); } - const { title, legacySlashCommandData, completionOptions, messages } = - msg.data; + const { legacySlashCommandData, completionOptions, messages } = msg.data; - const model = await configHandler.llmFromTitle(title); + const model = config.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } // Log to return in case of error const errorPromptLog = { - modelTitle: model.title ?? model.model, + modelTitle: model?.title ?? model?.model, completion: "", prompt: "", completionOptions: { ...msg.data.completionOptions, - model: model.model, + model: model?.model, }, }; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 7f4975170..3d0d72cc8 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -82,7 +82,7 @@ export const PROVIDER_TOOL_SUPPORT: Record< } else { modelName = model; } - + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( (part) => modelName.toLowerCase().includes(part), @@ -92,6 +92,7 @@ export const PROVIDER_TOOL_SUPPORT: Record< } if ( [ + "cogito", "llama3.3", "qwq", "llama3.2", diff --git a/core/llm/utils/__tests__/getSecureID.test.ts b/core/llm/utils/__tests__/getSecureID.test.ts new file mode 100644 index 000000000..9c4ffd6e7 --- /dev/null +++ b/core/llm/utils/__tests__/getSecureID.test.ts @@ -0,0 +1,49 @@ +import { getSecureID } from '../getSecureID'; + +// Mock the crypto.randomUUID function +const mockRandomUUID = jest.fn(); +global.crypto = { + ...global.crypto, + randomUUID: mockRandomUUID +}; + +describe('getSecureID', () => { + beforeEach(() => { + // Reset the static property before each test + (getSecureID as any).uuid = undefined; + + // Reset the mock implementation + mockRandomUUID.mockReset(); + // Setup a mock implementation that returns a fixed value for testing + mockRandomUUID.mockReturnValue('test-uuid-1234'); + }); + + test('should generate a UUID on first call', () => { + const result = getSecureID(); + expect(mockRandomUUID).toHaveBeenCalledTimes(1); + expect(result).toBe(''); + }); + + test('should reuse the same UUID on subsequent calls', () => { + const firstResult = getSecureID(); + const secondResult = getSecureID(); + + // The UUID generation should only happen once + expect(mockRandomUUID).toHaveBeenCalledTimes(1); + + // Both results should be identical + expect(firstResult).toBe(secondResult); + expect(firstResult).toBe(''); + }); + + test('should maintain the same UUID across different test cases if not reset', () => { + // Don't reset the UUID here to test persistence + (getSecureID as any).uuid = 'persistent-uuid'; + + const result = getSecureID(); + + // No new UUID should be generated + expect(mockRandomUUID).not.toHaveBeenCalled(); + expect(result).toBe(''); + }); +}); \ No newline at end of file diff --git a/core/llm/utils/getSecureID.ts b/core/llm/utils/getSecureID.ts new file mode 100644 index 000000000..b05fefab6 --- /dev/null +++ b/core/llm/utils/getSecureID.ts @@ -0,0 +1,8 @@ +// Utility function to get or generate UUID for LLM prompts +export function getSecureID(): string { + // Adding a type declaration for the static property + if (!(getSecureID as any).uuid) { + (getSecureID as any).uuid = crypto.randomUUID(); + } + return ``; +} diff --git a/core/package-lock.json b/core/package-lock.json index 24aeb4f18..0a0e8622b 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -108,6 +108,52 @@ "node": ">=20.11.0" } }, + "../../../../../documents/code/continuedev/continue/packages/config-yaml": { + "version": "1.0.78", + "extraneous": true, + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2" + } + }, + "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { + "extraneous": true + }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" + } + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -2856,118 +2902,6 @@ "node": ">=14.21.3" } }, - "node_modules/@biomejs/cli-darwin-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.6.4.tgz", - "integrity": "sha512-uo1zgM7jvzcoDpF6dbGizejDLCqNpUIRkCj/oEK0PB0NUw8re/cn1EnxuOLZqDpn+8G75COLQTOx8UQIBBN/Kg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.6.4.tgz", - "integrity": "sha512-wAOieaMNIpLrxGc2/xNvM//CIZg7ueWy3V5A4T7gDZ3OL/Go27EKE59a+vMKsBCYmTt7jFl4yHz0TUkUbodA/w==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64-musl": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.6.4.tgz", - "integrity": "sha512-Hp8Jwt6rjj0wCcYAEN6/cfwrrPLLlGOXZ56Lei4Pt4jy39+UuPeAVFPeclrrCfxyL1wQ2xPrhd/saTHSL6DoJg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-1.6.4.tgz", - "integrity": "sha512-qTWhuIw+/ePvOkjE9Zxf5OqSCYxtAvcTJtVmZT8YQnmY2I62JKNV2m7tf6O5ViKZUOP0mOQ6NgqHKcHH1eT8jw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64-musl": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.6.4.tgz", - "integrity": "sha512-wqi0hr8KAx5kBO0B+m5u8QqiYFFBJOSJVSuRqTeGWW+GYLVUtXNidykNqf1JsW6jJDpbkSp2xHKE/bTlVaG2Kg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-arm64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.6.4.tgz", - "integrity": "sha512-Wp3FiEeF6v6C5qMfLkHwf4YsoNHr/n0efvoC8jCKO/kX05OXaVExj+1uVQ1eGT7Pvx0XVm/TLprRO0vq/V6UzA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-1.6.4.tgz", - "integrity": "sha512-mz183Di5hTSGP7KjNWEhivcP1wnHLGmOxEROvoFsIxMYtDhzJDad4k5gI/1JbmA0xe4n52vsgqo09tBhrMT/Zg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, "node_modules/@continuedev/config-types": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", @@ -2977,14 +2911,8 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.71", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", - "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@continuedev/fetch": { "version": "1.0.4", @@ -3018,52 +2946,17 @@ "zod": "^3.24.2" } }, - "node_modules/@esbuild/android-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", - "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz", - "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz", - "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" + "node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": { + "version": "1.0.86", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz", + "integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" } }, "node_modules/@esbuild/darwin-arm64": { @@ -3082,294 +2975,6 @@ "node": ">=12" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", - "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz", - "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz", - "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz", - "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", - "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz", - "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz", - "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz", - "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz", - "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz", - "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz", - "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", - "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", - "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", - "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz", - "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", - "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz", - "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", - "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", @@ -4110,54 +3715,6 @@ "darwin" ] }, - "node_modules/@lancedb/vectordb-darwin-x64": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.20.tgz", - "integrity": "sha512-GSYsXE20RIehDu30FjREhJdEzhnwOTV7ZsrSXagStzLY1gr7pyd7sfqxmmUtdD09di7LnQoiM71AOpPTa01YwQ==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@lancedb/vectordb-linux-arm64-gnu": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.20.tgz", - "integrity": "sha512-FpNOjOsz3nJVm6EBGyNgbOW2aFhsWZ/igeY45Z8hbZaaK2YBwrg/DASoNlUzgv6IR8cUaGJ2irNVJfsKR2cG6g==", - "cpu": [ - "arm64" - ], - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@lancedb/vectordb-linux-x64-gnu": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.20.tgz", - "integrity": "sha512-pOqWjrRZQSrLTlQPkjidRii7NZDw8Xu9pN6ouVu2JAK8n81FXaPtFCyAI+Y3v9GpnYDN0rvD4eQ36aHAVPsa2g==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@lancedb/vectordb-win32-x64-msvc": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.20.tgz", - "integrity": "sha512-5J5SsYSJ7jRCmU/sgwVHdrGz43B/7R2T9OEoFTKyVAtqTZdu75rkytXyn9SyEayXVhlUOaw76N0ASm0hAoDS/A==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz", @@ -15962,27 +15519,6 @@ "node": ">=4" } }, - "node_modules/win-export-certificate-and-key": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/win-export-certificate-and-key/-/win-export-certificate-and-key-1.1.2.tgz", - "integrity": "sha512-3Su7Xdt9UR8pZicWQDcGSWNL6We/NzAGxe7AeQ1Z/zAeGHWlTKAh3HemGvIvxLRPsk4NW9D/QL3cL6SIvFcTvQ==", - "hasInstallScript": true, - "optional": true, - "os": [ - "win32" - ], - "dependencies": { - "bindings": "^1.5.0", - "node-addon-api": "^3.1.0", - "node-forge": "^1.2.1" - } - }, - "node_modules/win-export-certificate-and-key/node_modules/node-addon-api": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", - "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", - "optional": true - }, "node_modules/wink-distance": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", diff --git a/core/package.json b/core/package.json index a405bad55..296b8834a 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index fd0b48b2c..a934b2586 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -64,9 +64,6 @@ export function slashCommandFromPromptFileV1( description, prompt, run: async function* (context) { - const originalSystemMessage = context.llm.systemMessage; - context.llm.systemMessage = systemMessage; - const userInput = extractUserInput(context.input, name); const [_, renderedPrompt] = await renderPromptFileV2(prompt, { config: context.config, @@ -86,6 +83,18 @@ export function slashCommandFromPromptFileV1( systemMessage, ); + if (systemMessage) { + const currentSystemMsg = messages.find((msg) => msg.role === "system"); + if (currentSystemMsg) { + currentSystemMsg.content = systemMessage; + } else { + messages.unshift({ + role: "system", + content: systemMessage, + }); + } + } + for await (const chunk of context.llm.streamChat( messages, new AbortController().signal, @@ -93,8 +102,6 @@ export function slashCommandFromPromptFileV1( )) { yield renderChatMessage(chunk); } - - context.llm.systemMessage = originalSystemMessage; }, }; } diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 04cbcd91b..70b3ce1bd 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,9 +1,11 @@ +import { ChatMessage } from "../.."; + export function replaceSlashCommandWithPromptInChatHistory( - history: any[], + history: ChatMessage[], commandName: string, renderedPrompt: string, - systemMessage?: string, -) { + systemMessageOverride?: string, +): ChatMessage[] { const messages = [...history]; for (let i = messages.length - 1; i >= 0; i--) { @@ -13,7 +15,12 @@ export function replaceSlashCommandWithPromptInChatHistory( } if (Array.isArray(content)) { - if (content.some((part) => part.text?.startsWith(`/${commandName}`))) { + if ( + content.some( + (part) => + part.type === "text" && part.text?.startsWith(`/${commandName}`), + ) + ) { messages[i] = updateArrayContent( messages[i], commandName, @@ -30,10 +37,12 @@ export function replaceSlashCommandWithPromptInChatHistory( } } - if (systemMessage) { - messages[0]?.role === "system" - ? (messages[0].content = systemMessage) - : messages.unshift({ role: "system", content: systemMessage }); + if (systemMessageOverride) { + if (messages[0]?.role === "system") { + messages[0].content = systemMessageOverride; + } else { + messages.unshift({ role: "system", content: systemMessageOverride }); + } } return messages; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 0213cd0e5..38a51c098 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,4 +1,5 @@ import { + BlockType, ConfigResult, DevDataLogEvent, ModelRole, @@ -31,6 +32,7 @@ import type { ToolCall, } from "../"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; +import { ControlPlaneSessionInfo } from "../control-plane/client"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -49,6 +51,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, Session]; "history/save": [Session, void]; + "history/clear": [undefined, void]; "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ @@ -58,6 +61,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; "config/newPromptFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; "config/getSerializedProfileInfo": [ @@ -67,12 +71,20 @@ export type ToCoreFromIdeOrWebviewProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string; - usingContinueForTeams: boolean; }, ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, ConfigResult]; - "config/refreshProfiles": [undefined, void]; + "config/refreshProfiles": [ + ( + | undefined + | { + selectOrgId?: string; + selectProfileId?: string; + } + ), + void, + ]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ @@ -196,4 +208,14 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; + isItemTooBig: [ + { item: ContextItemWithId; selectedModelTitle: string | undefined }, + boolean, + ]; + didChangeControlPlaneSessionInfo: [ + { sessionInfo: ControlPlaneSessionInfo | undefined }, + void, + ]; + "process/markAsBackgrounded": [{ toolCallId: string }, void]; + "process/isBackgrounded": [{ toolCallId: string }, boolean]; }; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 1646d848e..e590c0ec9 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -103,8 +103,4 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; - didChangeControlPlaneSessionInfo: [ - { sessionInfo: ControlPlaneSessionInfo | undefined }, - void, - ]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 6aae337f0..cc1191d92 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -11,13 +11,10 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB applyToFile: [ { text: string; streamId: string; - curSelectedModelTitle: string; filepath?: string; toolCallId?: string; }, @@ -52,7 +49,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { prompt: MessageContent; range: RangeInFileWithContents; - selectedModelTitle: string; }, void, ]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 272a6d148..51c8f4a78 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -14,10 +14,12 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", "config/ideSettingsUpdate", + "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", @@ -59,6 +61,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "isItemTooBig", + "process/markAsBackgrounded", + "process/isBackgrounded", ]; // Message types to pass through from core to webview @@ -67,7 +72,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", @@ -76,5 +80,7 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", + "sessionUpdate", "didCloseFiles", + "toolCallPartialOutput", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 6b59fa338..2e6ec3cff 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,5 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; +import { ControlPlaneSessionInfo } from "../control-plane/client.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, @@ -15,7 +16,6 @@ export type ToWebviewFromIdeOrCoreProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string | null; - usingContinueForTeams: boolean; }, void, ]; @@ -41,4 +41,6 @@ export type ToWebviewFromIdeOrCoreProtocol = { getWebviewHistoryLength: [undefined, number]; getCurrentSessionId: [undefined, string]; "jetbrains/setColors": [Record, void]; + sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; + toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; }; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 7cff1c70e..5e269c232 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -9,6 +9,7 @@ export enum BuiltInToolNames { SearchWeb = "builtin_search_web", ViewDiff = "builtin_view_diff", LSTool = "builtin_ls", + CreateRuleBlock = "builtin_create_rule_block", // excluded from allTools for now ViewRepoMap = "builtin_view_repo_map", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 28a8f8c30..436b71874 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,6 +4,7 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; +import { createRuleBlockImpl } from "./implementations/createRuleBlock"; import { fileGlobSearchImpl } from "./implementations/globSearch"; import { grepSearchImpl } from "./implementations/grepSearch"; import { lsToolImpl } from "./implementations/lsTool"; @@ -156,6 +157,8 @@ export async function callTool( return await lsToolImpl(args, extras); case BuiltInToolNames.ReadCurrentlyOpenFile: return await readCurrentlyOpenFileImpl(args, extras); + case BuiltInToolNames.CreateRuleBlock: + return await createRuleBlockImpl(args, extras); // case BuiltInToolNames.ViewRepoMap: // return await viewRepoMapImpl(args, extras); // case BuiltInToolNames.ViewSubdirectory: diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts new file mode 100644 index 000000000..bf5caa6dc --- /dev/null +++ b/core/tools/definitions/createRuleBlock.ts @@ -0,0 +1,35 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const createRuleBlock: Tool = { + type: "function", + displayTitle: "Create Rule Block", + wouldLikeTo: 'create a rule block for "{{{ rule_name }}}"', + isCurrently: 'creating a rule block for "{{{ rule_name }}}"', + hasAlready: 'created a rule block for "{{{ rule_name }}}"', + readonly: false, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.CreateRuleBlock, + description: + "Creates a persistent rule that applies to all future conversations. " + + "Use for establishing ongoing code standards or preferences (e.g. 'use named exports', 'follow Google docstrings'). " + + "Not for one-time instructions. Rules are stored as YAML in `.continue/rules`.", + parameters: { + type: "object", + required: ["rule_name", "rule_content"], + properties: { + rule_name: { + type: "string", + description: + "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')", + }, + rule_content: { + type: "string", + description: + "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index e7f48ea32..73d326902 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -12,17 +12,26 @@ export const runTerminalCommandTool: Tool = { function: { name: BuiltInToolNames.RunTerminalCommand, description: - "Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands. Do NOT perform actions requiring special/admin priveleges.", - parameters: { - type: "object", - required: ["command"], - properties: { - command: { - type: "string", - description: - "The command to run. This will be passed directly into the IDE shell.", + "Run a terminal command in the current directory.\ + The shell is not stateful and will not remember any previous commands.\ + When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\ + When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\ + Do NOT perform actions requiring special/admin privileges.", + parameters: { + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: + "The command to run. This will be passed directly into the IDE shell.", + }, + waitForCompletion: { + type: "boolean", + description: + "Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.", + }, }, }, - }, }, }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 0f98f382c..d2ce78efc 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -7,7 +7,7 @@ export const searchWebTool: Tool = { displayTitle: "Search Web", wouldLikeTo: 'search the web for "{{{ query }}}"', isCurrently: 'searching the web for "{{{ query }}}"', - hasAlready: 'searched the web fore "{{{ query }}}"', + hasAlready: 'searched the web for "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts new file mode 100644 index 000000000..4e37f8818 --- /dev/null +++ b/core/tools/implementations/createRuleBlock.ts @@ -0,0 +1,52 @@ +import { ConfigYaml } from "@continuedev/config-yaml"; +import * as YAML from "yaml"; +import { ToolImpl } from "."; +import { joinPathsToUri } from "../../util/uri"; + +export interface CreateRuleBlockArgs { + rule_name: string; + rule_content: string; +} + +export const createRuleBlockImpl: ToolImpl = async ( + args: CreateRuleBlockArgs, + extras, +) => { + // Sanitize rule name for use in filename (remove special chars, replace spaces with dashes) + const safeRuleName = args.rule_name + .toLowerCase() + .replace(/[^a-z0-9\s-]/g, "") + .replace(/\s+/g, "-"); + + const ruleBlock: ConfigYaml = { + name: args.rule_name, + version: "0.0.1", + rules: [ + // This can be either a string or an object with {name, rule} + // Since we want a simple rule, we use the string format + args.rule_content, + ], + }; + + // Convert the rule block to YAML + const ruleYaml = YAML.stringify(ruleBlock); + + const [localContinueDir] = await extras.ide.getWorkspaceDirs(); + const rulesDirUri = joinPathsToUri( + localContinueDir, + ".continue", + "rules", + `${safeRuleName}.yaml`, + ); + + await extras.ide.writeFile(rulesDirUri, ruleYaml); + await extras.ide.openFile(rulesDirUri); + + return [ + { + name: "Rule Block Created", + description: `Created ${args.rule_name} rule`, + content: ruleYaml, + }, + ]; +}; diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.test.ts new file mode 100644 index 000000000..a26ff7e67 --- /dev/null +++ b/core/tools/implementations/runTerminalCommand.test.ts @@ -0,0 +1,334 @@ +import { jest } from "@jest/globals"; +import * as childProcess from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { IDE, ToolExtras } from "../.."; +import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; +import { runTerminalCommandImpl } from "./runTerminalCommand"; + +// We're using real child processes, so ensure these aren't mocked +jest.unmock("node:child_process"); +jest.unmock("node:util"); + +describe("runTerminalCommandImpl", () => { + // Setup mocks and spies + const mockGetIdeInfo = jest.fn(); + const mockGetWorkspaceDirs = jest.fn(); + const mockOnPartialOutput = jest.fn(); + const mockRunCommand = jest.fn(); + + // Use a simple approach to ensure background processes are terminated + let testPid: number | null = null; + + // Create a temp directory for our tests + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-')); + + beforeEach(() => { + jest.resetAllMocks(); + + // Setup backgrounded processes handling - don't mock, just make sure it's empty + // Get any processes that might be already tracked and clear them + const processMap = (processBackgroundStates as any).processTerminalBackgroundStates; + if (processMap && typeof processMap.clear === 'function') { + processMap.clear(); + } + + // Setup IDE mocks + mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); + mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`])); + }); + + afterEach(async () => { + // Clean up any lingering test processes + if (testPid !== null) { + try { + // Platform-independent way to kill a process + if (process.platform === 'win32') { + await new Promise(resolve => { + childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null)); + }); + } else { + process.kill(testPid); + } + } catch (e) { + // Process might already be gone, ignore + } + testPid = null; + } + }); + + afterAll(() => { + // Clean up the temp directory after tests + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + // Helper function to create a ToolExtras object + const createMockExtras = (overrides: Partial<{ + onPartialOutput?: jest.Mock; + remoteName?: string; + }> = {}): ToolExtras => { + // Update IDE info if remoteName is provided + if (overrides.remoteName) { + mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName })); + } + + // Create a minimally compliant IDE mock + const mockIde = { + getIdeInfo: mockGetIdeInfo, + getWorkspaceDirs: mockGetWorkspaceDirs, + runCommand: mockRunCommand, + // Add stubs for other required IDE methods + getIdeSettings: jest.fn(), + getDiff: jest.fn(), + getClipboardContent: jest.fn(), + isTelemetryEnabled: jest.fn(), + readFile: jest.fn(), + writeFile: jest.fn(), + renameFile: jest.fn(), + deleteFile: jest.fn(), + globFiles: jest.fn(), + ls: jest.fn(), + }; + + // Create a base ToolExtras object with required properties + const baseExtras = { + ide: mockIde as unknown as IDE, + llm: {} as any, + fetch: {} as any, + tool: {} as any, + toolCallId: "test-tool-call" + } as ToolExtras; + + // Apply overrides + if (overrides.onPartialOutput) { + baseExtras.onPartialOutput = overrides.onPartialOutput; + } + + return baseExtras; + }; + + it("should execute a command synchronously and capture output", async () => { + // Use Node.js for cross-platform output generation + const command = `node -e "console.log('real test output')"`; + const args = { command, waitForCompletion: true }; + const extras = createMockExtras(); + + const result = await runTerminalCommandImpl(args, extras); + + // Verify real command output + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].description).toBe("Terminal command output"); + expect(result[0].content).toContain("real test output"); + // Verify status field indicates successful completion + expect(result[0].status).toBe("Command completed"); + }); + + it("should stream output when onPartialOutput is provided", async () => { + // This test uses Node to create a command that outputs data incrementally + const command = `node -e " + console.log('first output'); + setTimeout(() => { + console.log('second output'); + console.error('error output'); + }, 50); + "`; + + const args = { command, waitForCompletion: true }; + const mockOutputFn = jest.fn(); + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); + + // Execute the command with streaming + const result = await runTerminalCommandImpl(args, extras); + + // Verify onPartialOutput was called with increasing content + expect(mockOutputFn).toHaveBeenCalled(); + + // Verify final result has all output + expect(result[0].content).toContain('first output'); + expect(result[0].content).toContain('second output'); + expect(result[0].content).toContain('error output'); + // Verify status field indicates successful completion + expect(result[0].status).toBe("Command completed"); + + // Verify that initial streaming updates have empty status for regular commands + const firstCall = mockOutputFn.mock.calls[0][0]; + if (firstCall && typeof firstCall === 'object') { + const contextItems = (firstCall as any).contextItems; + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { + // For commands with waitForCompletion=true, status should be empty while streaming + expect(contextItems[0].status).toBe(""); + } + } + }); + + it("should run commands in background when waitForCompletion is false", async () => { + // Create a self-identifying background process that writes its PID + // to a file we can access to kill it later + const pidFile = path.join(tempDir, 'test-pid.txt'); + + // This script creates a long-running process and writes its PID to our file + // Using a fixed duration timeout so we can be sure to clean it up + const command = `node -e " + const fs = require('fs'); + console.log('starting background process with PID: ' + process.pid); + fs.writeFileSync('${pidFile}', process.pid.toString()); + setTimeout(() => { + console.log('background process completed'); + }, 500); + "`; + + const args = { command, waitForCompletion: false }; + const mockOutputFn = jest.fn(); + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); + + const result = await runTerminalCommandImpl(args, extras); + + // Result should indicate background running in either content or status + expect(result[0].content || result[0].status).toContain("running in the background"); + // Verify status field indicates background running + expect(result[0].status).toBe("Command is running in the background..."); + + // Initial notification should indicate background running + expect(mockOutputFn).toHaveBeenCalled(); + // Check the first call contains background running message + const firstCallData = mockOutputFn.mock.calls[0][0]; + if (firstCallData && typeof firstCallData === 'object') { + const contextItems = (firstCallData as any).contextItems; + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { + expect(contextItems[0].content).toContain(""); + expect(contextItems[0].status).toMatch(/Command is running in the background.../); + } + } + + // Wait a bit to make sure the PID file is written + await new Promise(resolve => setTimeout(resolve, 100)); + + // Read the PID file to get the process ID so we can kill it later + if (fs.existsSync(pidFile)) { + testPid = Number(fs.readFileSync(pidFile, 'utf-8')); + } + + // Wait a bit longer for the process to complete and onPartialOutput to be called again + await new Promise(resolve => setTimeout(resolve, 400)); + + // Check for background process completion message in mockOutputFn calls + // Note: This is optional and depends on timing, so we don't want to strictly enforce it + let foundCompletionMessage = false; + + for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { + const call = mockOutputFn.mock.calls[i][0]; + if (call && typeof call === 'object') { + const contextItems = (call as any).contextItems; + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { + if (contextItems[0].status === "\nBackground command completed" || + (contextItems[0].status && contextItems[0].status.includes("Background command"))) { + foundCompletionMessage = true; + break; + } + } + } + } + + // If we found any completion message in the output, great! + // But we won't fail the test if we didn't, since it may be timing-dependent + if (mockOutputFn.mock.calls.length > 1) { + expect(foundCompletionMessage || true).toBeTruthy(); + } + }); + + it("should handle remote environments", async () => { + // We'll keep mocking for remote environments as we can't test those directly + const args = { command: "echo 'test'", waitForCompletion: true }; + const extras = createMockExtras({ remoteName: "ssh" }); + + const result = await runTerminalCommandImpl(args, extras); + + // In remote environments, it should use the IDE's runCommand + expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); + // Match the actual output message + expect(result[0].content).toContain("Terminal output not available"); + expect(result[0].content).toContain("SSH environments"); + // Verify status field indicates command failed in remote environments + expect(result[0].status).toBe("Command failed"); + }); + + it("should handle errors when executing invalid commands", async () => { + // Use a command that should fail on any platform + const args = { command: "non-existent-command-xyz", waitForCompletion: true }; + const extras = createMockExtras(); + + const result = await runTerminalCommandImpl(args, extras); + + expect(result[0].name).toBe("Terminal"); + expect(result[0].description).toBe("Terminal command output"); + + // The exact error message varies by platform, but should contain error information + const errorContent = result[0].content; + expect( + errorContent.includes("Command failed") || + errorContent.includes("not found") || + errorContent.includes("recognized") || + /error/i.test(errorContent) + ).toBe(true); + + // Verify status field indicates command failure + expect(result[0].status).toContain("Command failed with:"); + }); + + it("should handle error situations gracefully", async () => { + // Use Node.js script that writes to stderr for cross-platform testing + const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; + const args = { command, waitForCompletion: true }; + const extras = createMockExtras(); + + const result = await runTerminalCommandImpl(args, extras); + + // Verify we still get a result with a name and description + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].description).toBe("Terminal command output"); + + // The command should have executed and returned content + expect(result[0].content).toBeDefined(); + + // We should see the error message we wrote to stderr + expect(result[0].content).toContain("This is an error message"); + + // Verify status field indicates command failure - the exact message format can vary + // between different node versions and platforms + expect(result[0].status).toContain("Command failed"); + }); + + it("should set appropriate status when a command completes successfully", async () => { + // Use a simple command that will succeed + const command = `node -e "console.log('success test')"`; + const args = { command, waitForCompletion: true }; + const extras = createMockExtras(); + + const result = await runTerminalCommandImpl(args, extras); + + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].content).toContain("success test"); + // Verify status field for successful command + expect(result[0].status).toBe("Command completed"); + }); + + it("should include status info for background commands in non-streaming mode", async () => { + // Use a simple background command + const command = `node -e "setTimeout(() => console.log('done'), 300)"`; + const args = { command, waitForCompletion: false }; + // No streaming in this test (no onPartialOutput) + const extras = createMockExtras(); + + const result = await runTerminalCommandImpl(args, extras); + + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + // Verify both content and status fields for background commands + expect(result[0].content).toBe("Command is running in the background..."); + expect(result[0].status).toBe("Command is running in the background..."); + }); +}); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 9196cca2a..cfe7ced9e 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -3,42 +3,270 @@ import util from "node:util"; import { fileURLToPath } from "node:url"; import { ToolImpl } from "."; +import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates"; const asyncExec = util.promisify(childProcess.exec); export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { + // Default to waiting for completion if not specified + const waitForCompletion = args.waitForCompletion !== false; const ideInfo = await extras.ide.getIdeInfo(); + const toolCallId = extras.toolCallId || ""; if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { - try { - const output = await asyncExec(args.command, { - cwd: fileURLToPath((await extras.ide.getWorkspaceDirs())[0]), + // For streaming output + if (extras.onPartialOutput) { + return new Promise((resolve, reject) => { + try { + const getWorkspaceDirsPromise = extras.ide.getWorkspaceDirs(); + getWorkspaceDirsPromise + .then((workspaceDirs) => { + const cwd = fileURLToPath(workspaceDirs[0]); + let terminalOutput = ""; + + if (!waitForCompletion) { + const status = "Command is running in the background..."; + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: "", + status: status, + }, + ], + }); + } + } + + // Use spawn instead of exec to get streaming output + const childProc = childProcess.spawn(args.command, { + cwd, + shell: true, + }); + + childProc.stdout?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; + + const newOutput = data.toString(); + terminalOutput += newOutput; + + // Send partial output to UI + if (extras.onPartialOutput) { + const status = waitForCompletion ? "" : "Command is running in the background..."; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } + }); + + childProc.stderr?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; + + const newOutput = data.toString(); + terminalOutput += newOutput; + + // Send partial output to UI, status is not required + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + }, + ], + }); + } + }); + + // If we don't need to wait for completion, resolve immediately + if (!waitForCompletion) { + const status = "Command is running in the background..."; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ]); + } + + childProc.on("close", (code) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + + if (!waitForCompletion) { + // Already resolved, just update the UI with final output + if (extras.onPartialOutput) { + const status = (code === 0 || !code + ? "\nBackground command completed" + : `\nBackground command failed with exit code ${code}`) + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } + } else { + // Normal completion, resolve now + if (code === 0) { + const status = "Command completed"; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status + }, + ]); + } else { + const status = `Command failed with exit code ${code}`; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: + terminalOutput, + status: status, + }, + ]); + } + } + }); + + childProc.on("error", (error) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + + reject(error); + }); + }) + .catch((error) => { + reject(error); + }); + } catch (error: any) { + reject(error); + } }); - return [ - { - name: "Terminal", - description: "Terminal command output", - content: output.stdout ?? "", - }, - ]; - } catch (error: any) { - return [ - { - name: "Terminal", - description: "Terminal command output", - content: error.stderr || error.stdout || error.toString(), - }, - ]; + } else { + // Fallback to non-streaming for older clients + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + const cwd = fileURLToPath(workspaceDirs[0]); + + if (!waitForCompletion) { + // For non-streaming but also not waiting for completion, use spawn + // but don't attach any listeners other than error + try { + // Use spawn instead of exec but don't wait + const childProc = childProcess.spawn(args.command, { + cwd, + shell: true, + // Detach the process so it's not tied to the parent + detached: true, + // Redirect to /dev/null equivalent (works cross-platform) + stdio: 'ignore', + }); + + // Even for detached processes, add event handlers to clean up the background process map + childProc.on("close", () => { + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + } + }); + + childProc.on("error", () => { + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + } + }); + + // Unref the child to allow the Node.js process to exit + childProc.unref(); + const status = "Command is running in the background..."; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: status, + status: status, + }, + ]; + } catch (error: any) { + const status = `Command failed with: ${error.message || error.toString()}`; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: status, + status: status + }, + ]; + } + } else { + // Standard execution, waiting for completion + try { + const output = await asyncExec(args.command, { cwd }); + const status = "Command completed"; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + status: status, + }, + ]; + } catch (error: any) { + const status = `Command failed with: ${error.message || error.toString()}`; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: error.stderr ?? error.toString(), + status: status, + }, + ]; + } + } } } + // For remote environments, just run the command + // Note: waitForCompletion is not supported in remote environments yet await extras.ide.runCommand(args.command); return [ { name: "Terminal", description: "Terminal command output", content: - "[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]", + "Terminal output not available. This is only available in local development environments and not in SSH environments for example.", + status: "Command failed", }, ]; -}; +} diff --git a/core/tools/index.ts b/core/tools/index.ts index c9875c5eb..d89cf8744 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { createNewFileTool } from "./definitions/createNewFile"; +import { createRuleBlock } from "./definitions/createRuleBlock"; import { editFileTool } from "./definitions/editFile"; import { globSearchTool } from "./definitions/globSearch"; import { grepSearchTool } from "./definitions/grepSearch"; @@ -14,14 +15,13 @@ export const allTools = [ editFileTool, createNewFileTool, runTerminalCommandTool, - grepSearchTool, globSearchTool, searchWebTool, viewDiffTool, readCurrentlyOpenFileTool, - lsTool, + createRuleBlock, // replacing with ls tool for now // viewSubdirectoryTool, // viewRepoMapTool, diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index c59eb3320..ff7906e91 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -52,7 +52,6 @@ class FileSystemIde implements IDE { remoteConfigServerUrl: undefined, remoteConfigSyncPeriod: 60, userToken: "", - enableControlServerBeta: false, continueTestEnvironment: "none", pauseCodebaseIndexOnStart: false, }; diff --git a/core/util/history.ts b/core/util/history.ts index 622c2c9ce..ab332a11b 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -4,7 +4,11 @@ import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { NEW_SESSION_TITLE } from "./constants.js"; -import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +import { + getSessionFilePath, + getSessionsFolderPath, + getSessionsListPath, +} from "./paths.js"; function safeParseArray( value: string, errorMessage: string = "Error parsing array", @@ -67,6 +71,10 @@ class HistoryManager { ); } + clearAll() { + fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true }); + } + load(sessionId: string): Session { try { const sessionFile = getSessionFilePath(sessionId); diff --git a/core/util/processTerminalBackgroundStates.test.ts b/core/util/processTerminalBackgroundStates.test.ts new file mode 100644 index 000000000..bd128ad42 --- /dev/null +++ b/core/util/processTerminalBackgroundStates.test.ts @@ -0,0 +1,71 @@ +import { + markProcessAsBackgrounded, + isProcessBackgrounded, + removeBackgroundedProcess +} from './processTerminalBackgroundStates'; + +describe('processTerminalBackgroundStates', () => { + beforeEach(() => { + // Clear any backgrounded processes before each test + const backgroundedProcesses = Array.from( + Object.getOwnPropertySymbols(global) + ).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)'); + + if (backgroundedProcesses) { + // Reset the map by reimporting the module + jest.resetModules(); + } + }); + + test('should mark a process as backgrounded', () => { + const toolCallId = 'test-123'; + markProcessAsBackgrounded(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(true); + }); + + test('should correctly identify non-backgrounded processes', () => { + const toolCallId = 'test-123'; + const anotherToolCallId = 'test-456'; + + markProcessAsBackgrounded(toolCallId); + + expect(isProcessBackgrounded(toolCallId)).toBe(true); + expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); + }); + + test('should remove a process from backgrounded state', () => { + const toolCallId = 'test-123'; + + markProcessAsBackgrounded(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(true); + + removeBackgroundedProcess(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(false); + }); + + test('should handle removing non-existent processes', () => { + const toolCallId = 'test-123'; + + // Should not throw an error + removeBackgroundedProcess(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(false); + }); + + test('should handle multiple processes', () => { + const toolCallId1 = 'test-123'; + const toolCallId2 = 'test-456'; + const toolCallId3 = 'test-789'; + + markProcessAsBackgrounded(toolCallId1); + markProcessAsBackgrounded(toolCallId2); + + expect(isProcessBackgrounded(toolCallId1)).toBe(true); + expect(isProcessBackgrounded(toolCallId2)).toBe(true); + expect(isProcessBackgrounded(toolCallId3)).toBe(false); + + removeBackgroundedProcess(toolCallId1); + + expect(isProcessBackgrounded(toolCallId1)).toBe(false); + expect(isProcessBackgrounded(toolCallId2)).toBe(true); + }); +}); \ No newline at end of file diff --git a/core/util/processTerminalBackgroundStates.ts b/core/util/processTerminalBackgroundStates.ts new file mode 100644 index 000000000..822e810bb --- /dev/null +++ b/core/util/processTerminalBackgroundStates.ts @@ -0,0 +1,17 @@ +// Track which processes have been backgrounded +const processTerminalBackgroundStates = new Map(); + +// Function to mark a process as backgrounded +export function markProcessAsBackgrounded(toolCallId: string): void { + processTerminalBackgroundStates.set(toolCallId, true); +} + +// Function to check if a process is backgrounded +export function isProcessBackgrounded(toolCallId: string): boolean { + return processTerminalBackgroundStates.has(toolCallId); +} + +// Function to remove a process from the backgrounded processes map +export function removeBackgroundedProcess(toolCallId: string): void { + processTerminalBackgroundStates.delete(toolCallId); +} \ No newline at end of file diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index b89c7ac85..1191fa9f8 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -9,9 +9,10 @@ Agent offers the same functionality as Chat, while also including tools in the r ## The tool handshake -Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file. +Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file. The following handshake describes how Agent uses tools: + 1. In Agent mode, available tools are sent along with `user` chat requests 2. The model can choose to include a tool call in its response 3. The user gives permission. This step is skipped if the policy for that tool is set to `Automatic` @@ -32,7 +33,8 @@ Continue includes several built-in tools which provide the model access to IDE f - **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model - **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project - **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root -- **Search web** (`builtin_search_web`): Perform a web search to get top results +- **Search web** (`builtin_search_web`): Perform a web search to get top results - **View diff** (`builtin_view_diff`): View the current working git diff - **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map) -- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project \ No newline at end of file +- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project +- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index b21f78092..310c64df2 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -70,7 +70,7 @@ To add a single documentation site, we recommend using the **Add Documentation** In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site. -- `Title`: The name of the documentation site, used for identification in the UI +- `Title`: The name of the documentation site, used for identification in the UI. - `Start URL`: The URL where the indexing process should begin. Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page. @@ -154,9 +154,9 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo -### Github +### GitHub -The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file: +The GitHub API rate limits public requests to 60 per hour. If you want to reliably index GitHub repos, you can add a github token to your config file: @@ -223,7 +223,7 @@ Chromium crawling has been deprecated Further notes: - If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential. -- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways. +- For GitHub Repos this has no effect because only the GitHub Crawler will be used, and if the repo is private it can only be accessed with a priveleged GitHub token anyways. ## Managing your docs indexes @@ -237,6 +237,7 @@ You can view indexing statuses and manage your documentation sites from the `@do ![More Page @docs indexes section](/img/docs-indexes.png) You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page + ![Documentation indexing peek](/img/docs-indexing-peek.png) You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`. @@ -327,7 +328,7 @@ The following configuration example includes: - Examples of both public and private documentation sources - A custom embeddings provider - A reranker model available, with reranking parameters customized -- A Github token to enable Github crawling +- A GitHub token to enable GitHub crawling diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 59f816c15..94dec8a07 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -5,15 +5,55 @@ keywords: [rules, .continuerules, system, prompt, message] # Rules -Rules are used to provide instructions to **chat** models. They are inserted into the system message for all chat requests. Rules are _only_ used during Chat, they are not used for autocomplete or other roles. +Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -## Hub `rules` blocks +Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). -Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. +You can view the current rules by clicking the pen icon above the main toolbar: + +![rules input toolbar section](/img/notch-rules.png) + +To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)). + +## `rules` blocks + +Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. + +:::info Automatically create local rule blocks +When in Agent mode, you can simply prompt the agent to create a rule for you. + +For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation. +::: + +Rules blocks can be simple text, or have the following properties: + +- `name` (**required**): A display name/title for the rule +- `rule` (**required**): The text content of the rule + +Examples: + +```yaml title="config.yaml" +rules: + - uses: myprofile/my-mood-setter + with: + TONE: consise + - Always annotate Python functions with their parameter and return types + - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. +``` + +## Chat System Message + +Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output. + +This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4) + +Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models). ## `.continuerules` -You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. +You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. ### Simple Examples diff --git a/docs/docs/customize/model-providers/more/asksage.mdx b/docs/docs/customize/model-providers/more/asksage.mdx index 675cedc7f..b7d7ede26 100644 --- a/docs/docs/customize/model-providers/more/asksage.mdx +++ b/docs/docs/customize/model-providers/more/asksage.mdx @@ -4,7 +4,7 @@ import TabItem from "@theme/TabItem"; import Tabs from "@theme/Tabs"; :::info -To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) +To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs: [Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) ::: ## Configuration @@ -55,7 +55,7 @@ Currently, the setup for the models provided by Ask Sage is to support the follo More models, functionalities and documentation will be added in the future for Ask Sage Integration. -> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. +> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. ## Ask Sage Documentation diff --git a/docs/docs/customize/model-providers/more/siliconflow.mdx b/docs/docs/customize/model-providers/more/siliconflow.mdx index a496d3757..79ccd8e71 100644 --- a/docs/docs/customize/model-providers/more/siliconflow.mdx +++ b/docs/docs/customize/model-providers/more/siliconflow.mdx @@ -81,8 +81,8 @@ We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete ## Embeddings model -SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models. +SiliconFlow provide some embeddings models. [Click here](https://siliconflow.cn/models) to see a list of embeddings models. ## Reranking model -SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models. +SiliconFlow provide some reranking models. [Click here](https://siliconflow.cn/models) to see a list of reranking models. diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 1ecace184..040cdaa2e 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -10,6 +10,36 @@ import Tabs from "@theme/Tabs"; When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. -Generally speaking, models proficient in chat and edit can also be used for applying code. +## Recommended Apply models -Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). +We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys). + +However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku. + +:::info +Explore all apply models in [the Hub](https://hub.continue.dev/explore/models?roles=apply) +::: + +## Prompt templating + +You can customize the prompt template used for applying code changes by setting the `promptTemplates.apply` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the apply template: + +- `{{{original_code}}}` - The original code before changes +- `{{{new_code}}}` - The new code after changes + +Example: + +```yaml +models: + - name: My Custom Apply Template + provider: anthropic + model: claude-3-5-sonnet-latest + promptTemplates: + apply: | + Original: {{{original_code}}} + New: {{{new_code}}} + + Please generate the final code without any markers or explanations. +``` diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx index aca683782..781ce37d9 100644 --- a/docs/docs/customize/model-roles/chat.mdx +++ b/docs/docs/customize/model-roles/chat.mdx @@ -257,6 +257,14 @@ If your local machine can run an 8B parameter model, then we recommend running L model: llama3.1:8b ``` + + ```yaml title="config.yaml" + models: + - name: Llama 3.1 8B + provider: msty + model: llama3.1:8b + ``` + @@ -287,6 +295,19 @@ If your local machine can run an 8B parameter model, then we recommend running L } ``` + + ```json title="config.json" + { + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "msty", + "model": "llama3.1-8b" + } + ] + } + ``` + @@ -325,6 +346,14 @@ If your local machine can run a 16B parameter model, then we recommend running D model: deepseek-coder-v2:16b ``` + + ```yaml title="config.yaml" + models: + - name: DeepSeek Coder 2 16B + provider: msty + model: deepseek-coder-v2:16b + ``` + @@ -356,6 +385,19 @@ If your local machine can run a 16B parameter model, then we recommend running D } ``` + + ```json title="config.json" + { + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "msty", + "model": "deepseek-coder-v2:16b" + } + ] + } + ``` + diff --git a/docs/docs/customize/model-roles/edit.mdx b/docs/docs/customize/model-roles/edit.mdx index de817ed42..ca4572f26 100644 --- a/docs/docs/customize/model-roles/edit.mdx +++ b/docs/docs/customize/model-roles/edit.mdx @@ -29,8 +29,8 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use Set the `experimental.modelRoles.inlineEdit` property in `config.json`. ```json title="config.json" { - "models": { - "name": "Claude 3.5 Sonnet", + "models": { + "name": "Claude 3.5 Sonnet", "provider": "anthropic", "model": "claude-3-5-sonnet-latest", "apiKey": "" @@ -46,3 +46,37 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. + +## Prompt templating + +You can customize the prompt template used for editing code by setting the `promptTemplates.edit` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the edit template: + +- `{{{userInput}}}` - The user's edit request/instruction +- `{{{language}}}` - The programming language of the code +- `{{{codeToEdit}}}` - The code that's being edited +- `{{{prefix}}}` - Content before the edit area +- `{{{suffix}}}` - Content after the edit area +- `{{{supportsCompletions}}}` - Whether the model supports completions API +- `{{{supportsPrefill}}}` - Whether the model supports prefill capability + +Example: + +```yaml +models: + - name: My Custom Edit Template + provider: openai + model: gpt-4o + promptTemplates: + edit: | + `Here is the code before editing: + \`\`\`{{{language}}} + {{{codeToEdit}}} + \`\`\` + + Here is the edit requested: + "{{{userInput}}}" + + Here is the code after editing:` +``` diff --git a/docs/docs/customize/tutorials/custom-code-rag.mdx b/docs/docs/customize/tutorials/custom-code-rag.mdx index f5e43dc8e..145c38f10 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.mdx +++ b/docs/docs/customize/tutorials/custom-code-rag.mdx @@ -22,7 +22,7 @@ Most embeddings models can only handle a limited amount of text at once. To get If you use `voyage-code-3`, it has a maximum context length of 16,000 tokens, which is enough to fit most files. This means that in the beginning you can get away with a more naive strategy of truncating files that exceed the limit. In order of easiest to most comprehensive, 3 chunking strategies you can use are: 1. Truncate the file when it goes over the context length: in this case you will always have 1 chunk per file. -2. Split the file into chunks of a fixed length: starting at the top of the file, add lines you your current chunk until it reaches the limit, then start a new chunk. +2. Split the file into chunks of a fixed length: starting at the top of the file, add lines in your current chunk until it reaches the limit, then start a new chunk. 3. Use a recursive, abstract syntax tree (AST)-based strategy: this is the most exact, but most complex. In most cases you can achieve high quality results by using (1) or (2), but if you'd like to try this you can find a reference example in [our code chunker](https://github.com/continuedev/continue/blob/main/core/indexing/chunk/code.ts) or in [LlamaIndex](https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/code/). As usual in this guide, we recommend starting with the strategy that gives 80% of the benefit with 20% of the effort. @@ -51,8 +51,8 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-3` model. - vector: Vector(1536) = func.VectorField() + # 1024 is the default dimension for `voyage-code-3`: https://docs.voyageai.com/docs/embeddings#model-choices + vector: Vector(1024) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") table.add([ @@ -79,7 +79,7 @@ Regardless of which database or model you have chosen, your script should iterat In a perfect production version, you would want to build "automatic, incremental indexing", so that you whenever a file changes, that file and nothing else is automatically re-indexed. This has the benefits of perfectly up-to-date embeddings and lower cost. -That said, we highly recommend first building and testing the pipeline before attempting this. Unless your codebase is being entirely rewritten frequently, a full refresh of the index is likely to be sufficient and reasonably cheap. +That said, we highly recommend first building and testing the pipeline before attempting this. Unless your codebase is being entirely rewritten frequently, an incremental refresh of the index is likely to be sufficient and reasonably cheap. ::: At this point, you've written your indexing script and tested that you can make queries from your vector database. Now, you'll want a plan for when to run the indexing script. diff --git a/docs/docs/customize/tutorials/llama3.1.mdx b/docs/docs/customize/tutorials/llama3.1.mdx index 413214fb4..bb65be947 100644 --- a/docs/docs/customize/tutorials/llama3.1.mdx +++ b/docs/docs/customize/tutorials/llama3.1.mdx @@ -198,7 +198,7 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b - apiKey: + apiKey: ``` @@ -209,7 +209,7 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L "title": "Cerebras Llama 3.1 70B", "provider": "cerebras", "model": "llama3.1-70b", - "apiKey": "" + "apiKey": "" } ] } diff --git a/docs/docs/customize/tutorials/set-up-codestral.mdx b/docs/docs/customize/tutorials/set-up-codestral.mdx index 1ace12f2f..833da53bc 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.mdx +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -61,6 +61,3 @@ import TabItem from "@theme/TabItem"; 5. If you run into any issues or have any questions, please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) -### Ask for help on Discord - -Please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) if you are having problems using Codestral diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index b9c5bbd13..03b92c08a 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -15,7 +15,7 @@ Continue supports [many model providers](../../customize/model-providers), inclu ## Context -Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and Github issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. +Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and GitHub issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. Learn more about context providers [here](../../reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../reference.md#context). diff --git a/docs/docs/hub/source-control.md b/docs/docs/hub/source-control.md new file mode 100644 index 000000000..9230c487b --- /dev/null +++ b/docs/docs/hub/source-control.md @@ -0,0 +1,50 @@ +--- +title: Source Control +description: Source Control +keywords: [source, control, github, workflow, action, version, yaml] +sidebar_label: Source Control +--- + +# Source Control + +When managing your custom assistants within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a [GitHub Action](https://github.com/continuedev/continue-publish-action) that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on [Discord](https://discord.gg/vapESyrFmJ). + +## Quickstart + +This quickstart uses a template repository, but you can also follow these steps 2-4 from an existing repository. + +### 1. Create a new repository from the template + +As shown in the image below, start by creating a new repository from [the template](https://github.com/continuedev/continue-hub-template). Click "Use Template" and then "Create a new repository". + +![Use the template repository](/img/hub/template-repo.png) + +### 2. Obtain a deploy key + +Deploy keys allow the GitHub Action to authenticate with hub.continue.dev. [Obtain your deploy key here](https://hub.continue.dev/settings/api-keys) and then [create a secret](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository) named `CONTINUE_API_KEY` in your GitHub repository. + +### 3. Configure the GitHub Action + +:::tip +This step assumes you have already created an organization on hub.continue.dev. If not, learn more [here](./governance/creating-an-org.md). +::: + +In the repository you created, navigate to `.github/workflows/main.yaml` and update the lines below to match your organization: + +```yaml +env: + OWNER_SLUG: my-org-slug # <-- TODO +``` + +This is the only configuration necessary, but you can view the full list of options [here](https://github.com/continuedev/continue-publish-action/blob/main/README.md). + +### 4. Commit and push + +Add the [YAML for your assistants and blocks](../reference.md) to the appropriate directories: + +- `assistants/public` for public assistants +- `assistants/private` for private (visible only within your organization) assistants +- `blocks/public` for public blocks +- `blocks/private` for private blocks + +Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 4e418bc3d..88391dbda 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -49,6 +49,28 @@ models: provider: ollama ``` +### Local Blocks + +It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally). + +Place your YAML files in the following folders: + +Assistants: + +- `.continue/assistants` - for assistants + +Blocks: + +- `.continue/rules` - for rules +- `.continue/models` - for models +- `.continue/prompts` - for prompts +- `.continue/context` - for context providers +- `.continue/docs` - for docs +- `.continue/data` - for data +- `.continue/mcpServers` - for MCP Servers + +You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models) + ### Inputs Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: @@ -142,17 +164,16 @@ The `models` section defines the language models used in your configuration. Mod - `name` (**required**): A unique name to identify the model within your configuration. - `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). - `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). +- `apiBase`: Can be used to override the default API base that is specified per model - `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`. +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating). +- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: + - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - - `defaultCompletionOptions`: Default completion options for model settings. - - **Properties:** - - `contextLength`: Maximum context length of the model, typically in tokens. - `maxTokens`: Maximum number of tokens to generate in a completion. - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). @@ -162,11 +183,7 @@ The `models` section defines the language models used in your configuration. Mod - `n`: Number of completions to generate. - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models. - `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. - - `requestOptions`: HTTP request options specific to the model. - - **Properties:** - - `timeout`: Timeout for each request to the language model. - `verifySsl`: Whether to verify SSL certificates for requests. - `caBundlePath`: Path to a custom CA bundle for HTTP requests. @@ -179,7 +196,7 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. -#### Example: +#### Example ```yaml title="config.yaml" models: @@ -222,7 +239,8 @@ More information about usage/params for each context provider can be found [here **Properties:** -- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`) +- `name`: Optional name for the provider - `params`: Optional parameters to configure the context provider's behavior. **Example:** @@ -236,6 +254,10 @@ context: nFinal: 10 - provider: docs - provider: diff + - provider: http + name: Context Server 1 + params: + url: "https://api.example.com/server1" - provider: folder - provider: terminal ``` @@ -244,7 +266,13 @@ context: ### `rules` -List of rules that the LLM should follow. These are inserted into the system message for all chat requests. +List of rules that the LLM should follow. These are concatenated into the system message for all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests. See the [rules deep dive](./customize/deep-dives/rules.md) for details. + +Explicit rules can either be simple text or an object with the following properties: + +- `name` (**required**): A display name/title for the rule +- `rule` (**required**): The text content of the rule + Example @@ -252,9 +280,11 @@ Example rules: - uses: myprofile/my-mood-setter with: - MOOD: happy + TONE: concise - Always annotate Python functions with their parameter and return types - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. ``` --- diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 3065bdc28..71eac9d9b 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -4,8 +4,8 @@ description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- -import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below. @@ -35,13 +35,16 @@ In order to view debug logs, which contain extra information, click the dropdown 4. Select the `Console` tab 5. Read the console logs -#### LLM prompt logs +#### Prompt Logs (Continue Console) -If you're getting a response from the LLM that doesn't seem to make sense, you can +To view prompt logs/analytics, you can enable the Continue Console. -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 received +1. Open VS Code settings (cmd/ctrl + ,) +2. Search for the setting "Continue: Enable Console" and enable it +3. Reload the window +4. Open the Continue Console by using the command palette (cmd/ctrl + shift + P) and searching for "Continue: Focus on Continue Console View" + +![Continue Console](../static/img/continue-console.png) ### JetBrains diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 82df8edd2..c07f99c18 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -114,6 +114,7 @@ models: - name: My Voyage Reranker provider: voyage apiKey: + roles: - rerank - name: My Starcoder diff --git a/docs/package-lock.json b/docs/package-lock.json index f9c2ca21c..deb0071b8 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -8022,9 +8022,10 @@ } }, "node_modules/estree-util-value-to-estree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.2.1.tgz", - "integrity": "sha512-Vt2UOjyPbNQQgT5eJh+K5aATti0OjCIAGc9SgMdOFYbohuifsWclR74l0iZTJwePMgWYdX1hlVS+dedH9XV8kw==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.3.3.tgz", + "integrity": "sha512-Db+m1WSD4+mUO7UgMeKkAwdbfNWwIxLt48XF2oFU9emPfXkIu+k5/nlOj313v7wqtAPo0f9REhUvznFrPkG8CQ==", + "license": "MIT", "dependencies": { "@types/estree": "^1.0.0" }, diff --git a/docs/sidebars.js b/docs/sidebars.js index 20a47be93..1a634d163 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -171,6 +171,7 @@ const sidebars = { "hub/governance/pricing", ], }, + "hub/source-control", { type: "link", label: "Customize", diff --git a/docs/static/img/continue-console.png b/docs/static/img/continue-console.png new file mode 100644 index 000000000..f40b8cf6f Binary files /dev/null and b/docs/static/img/continue-console.png differ diff --git a/docs/static/img/hub/template-repo.png b/docs/static/img/hub/template-repo.png new file mode 100644 index 000000000..36dbf4aa8 Binary files /dev/null and b/docs/static/img/hub/template-repo.png differ diff --git a/docs/static/img/notch-rules.png b/docs/static/img/notch-rules.png new file mode 100644 index 000000000..02a175817 Binary files /dev/null and b/docs/static/img/notch-rules.png differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 7c00cb65c..ec6ce435b 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.12 +pluginVersion=1.0.13 # 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 031c6b2e9..6184aa347 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 @@ -157,7 +157,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { "remoteConfigServerUrl" to settings.remoteConfigServerUrl, "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, "userToken" to settings.userToken, - "enableControlServerBeta" to settings.enableContinueTeamsBeta ), null) { _ -> } } }) 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 f65404dcd..9908daa55 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 @@ -48,10 +48,7 @@ class ContinueAuthService { } init { - val settings = service() - if (settings.continueState.enableContinueTeamsBeta) { - setupRefreshTokenInterval() - } + setupRefreshTokenInterval() } fun startAuthFlow(project: Project, useOnboarding: Boolean) { @@ -74,6 +71,9 @@ class ContinueAuthService { setRefreshToken("") setAccountId("") setAccountLabel("") + + ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) + .handleUpdatedSessionInfo(null) } private fun updateRefreshToken(token: String) { 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 60d2d3b33..b226aa8f6 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 @@ -60,7 +60,6 @@ class MessageTypes { // core/protocol/passThrough.ts val PASS_THROUGH_TO_WEBVIEW = listOf( "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", @@ -69,7 +68,9 @@ class MessageTypes { "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", + "sessionUpdate", "didCloseFiles", + "toolCallPartialOutput", ) // Note: If updating these values, make a corresponding update in @@ -80,10 +81,12 @@ class MessageTypes { "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", "config/ideSettingsUpdate", + "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", @@ -126,6 +129,9 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "isItemTooBig", + "process/markAsBackgrounded", + "process/isBackgrounded", ) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 4378d273d..cbcee8e98 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -65,21 +65,6 @@ class CoreMessenger( // Forward to webview if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { - // TODO: Currently we aren't set up to receive a response back from the webview - // Can circumvent for getDefaultsModelTitle here for now - if (messageType == "getDefaultModelTitle") { - val continueSettingsService = service() - val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel - val message = - gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to defaultModelTitle - ) - ) - write(message) - } val continuePluginService = project.service() continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 41c2c4892..f76a41574 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -111,11 +111,6 @@ class IdeProtocolClient( "logoutOfControlPlane" -> { val authService = service() authService.signOut() - ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) - .handleUpdatedSessionInfo(null) - - // Tell the webview that session info changed - continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", null, null) { _ -> } respond(null) } @@ -497,21 +492,18 @@ class IdeProtocolClient( val config = result["config"] as Map<*, *> val selectedModels = config["selectedModelByRole"] as? Map<*, *> - val applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + + // If "apply" role model is not found, try "chat" role + if (applyCodeBlockModel == null) { + applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *> + } if (applyCodeBlockModel != null) { continuation.resume(applyCodeBlockModel) } else { - val models = - config["models"] as List> - val curSelectedModel = - models.find { it["title"] == params.curSelectedModelTitle } - - if (curSelectedModel == null) { - continuation.resumeWithException(IllegalStateException("Model '${params.curSelectedModelTitle}' not found in config.")) - } else { - continuation.resume(curSelectedModel) - } + // If neither "apply" nor "chat" models are available, return with exception + continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration.")) } } catch (e: Exception) { continuation.resumeWithException(e) 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 a23f2d716..41bcc2941 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 @@ -103,7 +103,6 @@ class IntelliJIDE( remoteConfigServerUrl = settings.continueState.remoteConfigServerUrl, remoteConfigSyncPeriod = settings.continueState.remoteConfigSyncPeriod, userToken = settings.continueState.userToken ?: "", - enableControlServerBeta = settings.continueState.enableContinueTeamsBeta, continueTestEnvironment = "production", pauseCodebaseIndexOnStart = false, // TODO: Needs to be implemented ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 5c587c54d..718755a99 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -11,7 +11,6 @@ data class SetGitHubAuthTokenParams( data class ApplyToFileParams( val text: String, val streamId: String, - val curSelectedModelTitle: String, val filepath: String?, val toolCallId: String? ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index f20096d81..3010cc33e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -30,7 +30,6 @@ class ContinueSettingsComponent : DumbAware { val remoteConfigSyncPeriod: JTextField = JTextField() val userToken: JTextField = JTextField() val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete") - val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta") val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering") val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") val showIDECompletionSideBySide: JCheckBox = JCheckBox("Show IDE completions side-by-side") @@ -59,8 +58,6 @@ class ContinueSettingsComponent : DumbAware { constraints.gridy++ panel.add(enableTabAutocomplete, constraints) constraints.gridy++ - panel.add(enableContinueTeamsBeta, constraints) - constraints.gridy++ panel.add(enableOSR, constraints) constraints.gridy++ panel.add(displayEditorTooltip, constraints) @@ -95,7 +92,6 @@ open class ContinueExtensionSettings : PersistentStateComponent await ApplySelectors.getCodeblockToolbarAction(view, action), + ); + applyButton.click(); + } +} diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index aafd1040a..b3fca5cbd 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -7,10 +7,17 @@ import { } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; +import { TestUtils } from "../TestUtils"; export class GlobalActions { + static defaultFolder = "e2e/test-continue"; + public static defaultNewFilename = "test.py"; + public static async openTestWorkspace() { - return VSBrowser.instance.openResources("e2e/test-continue"); + await VSBrowser.instance.openResources(GlobalActions.defaultFolder); + await new Workbench().executeCommand( + "Notifications: Clear All Notifications", + ); } public static async createAndOpenNewTextFile(): Promise<{ @@ -26,4 +33,47 @@ export class GlobalActions { return { editor }; } + + public static async createAndSaveNewFile( + filename = GlobalActions.defaultNewFilename, + ): Promise<{ + editor: TextEditor; + }> { + let { editor } = await GlobalActions.createAndOpenNewTextFile(); + + await new Workbench().executeCommand("File: Save As..."); + const inputBox = await InputBox.create(DEFAULT_TIMEOUT.MD); + + // Get current path and replace filename + const currentPath = await inputBox.getText(); + const pathParts = currentPath.split(/[\/\\]/); + pathParts[pathParts.length - 1] = filename; + const newPath = pathParts.join("/"); + + await inputBox.setText(newPath); + + await inputBox.confirm(); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + editor = (await new EditorView().openEditor(filename)) as TextEditor; + + return { editor }; + } + + public static async deleteFileFromFolder( + filename = GlobalActions.defaultNewFilename, + folder = GlobalActions.defaultFolder, + ): Promise { + const fs = require("fs"); + const path = require("path"); + + const folderPath = path.join(process.cwd(), folder); + const filePath = path.join(folderPath, filename); + + try { + await fs.promises.unlink(filePath); + } catch (error) { + console.warn(`Failed to delete file ${filePath}:`, error); + } + } } diff --git a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts index 358d883bd..cac1097c7 100644 --- a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts +++ b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts @@ -1,4 +1,4 @@ -import { TextEditor } from "vscode-extension-tester"; +import { Key, TextEditor, WebElement } from "vscode-extension-tester"; export class KeyboardShortcutsActions { /** @@ -10,4 +10,27 @@ export class KeyboardShortcutsActions { await editor.selectText(text); await editor.typeText(text); } + + /** + * Types each string in the array with a newline (Shift+Enter) between them. + * Optionally adds a final Enter key press to submit. + */ + public static async typeWithNewlines({ + input, + lines, + submit, + }: { + input: TextEditor | WebElement; + lines: string[]; + submit?: boolean; + }) { + for (let i = 0; i < lines.length - 1; i++) { + await input.sendKeys(lines[i]); + await input.sendKeys(Key.chord(Key.SHIFT, Key.ENTER)); + } + await input.sendKeys(lines[lines.length - 1]); + if (submit) { + await input.sendKeys(Key.ENTER); + } + } } diff --git a/extensions/vscode/e2e/selectors/Apply.selectors.ts b/extensions/vscode/e2e/selectors/Apply.selectors.ts new file mode 100644 index 000000000..4d14f7ff5 --- /dev/null +++ b/extensions/vscode/e2e/selectors/Apply.selectors.ts @@ -0,0 +1,15 @@ +import { WebView } from "vscode-extension-tester"; + +import { SelectorUtils } from "./SelectorUtils"; + +export class ApplySelectors { + static getCodeblockToolbarAction( + view: WebView, + action: "apply" | "accept" | "reject" | "create", + ) { + return SelectorUtils.getElementByDataTestId( + view, + `codeblock-toolbar-${action}`, + ); + } +} diff --git a/extensions/vscode/e2e/tests/Apply.test.skip.ts b/extensions/vscode/e2e/tests/Apply.test.skip.ts new file mode 100644 index 000000000..80e005d01 --- /dev/null +++ b/extensions/vscode/e2e/tests/Apply.test.skip.ts @@ -0,0 +1,100 @@ +import { TextEditor, VSBrowser, WebView } from "vscode-extension-tester"; + +import { ApplyActions } from "../actions/Apply.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +/** + * This file is currently `.skip`'d because the test is consistently failing in CI, + * bu consistenly passing locally. Screenshots from CI appear to indicate + * that our `GlobalActions.openTestWorkspace` fn isn't actually working, and therefore + * our apply button is instead rendering as "Create file" since the file doesn't exist + * in our workspace. + * + * The most recent failing screenshot is here: https://github.com/continuedev/continue/actions/runs/14481877233?pr=5167 + */ +describe("Apply Test", () => { + let view: WebView; + let editor: TextEditor; + let fileContent = "hello = 'world'"; + + before(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver); + await GlobalActions.openTestWorkspace(); + + ({ editor } = await GlobalActions.createAndSaveNewFile()); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.typeTextAt(1, 1, fileContent); + await GUIActions.toggleGui(); + + ({ view } = await GUIActions.switchToReactIframe()); + await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + }); + + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.clearText(); + + ({ view } = await GUIActions.switchToReactIframe()); + const tipTapEditor = await GUISelectors.getMessageInputFieldAtIndex( + view, + 0, + ); + await tipTapEditor.clear(); + }); + + after(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await GlobalActions.deleteFileFromFolder(); + }); + + it("Can reject and apply changes from sidebar", async () => { + const newFileContent = fileContent + "!"; + + const [messageInput] = await GUISelectors.getMessageInputFields(view); + + await KeyboardShortcutsActions.typeWithNewlines({ + submit: true, + input: messageInput, + lines: [ + "```py " + GlobalActions.defaultNewFilename, + newFileContent, + "```", + "_", // To avoid extra lines getting included in the block + ], + }); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "reject"); + await view.switchBack(); + + let editorText = await editor.getText(); + + await TestUtils.waitForSuccess(async () => editorText === fileContent); + + ({ view } = await GUIActions.switchToReactIframe()); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "accept"); + await view.switchBack(); + + // Note that the editor after accpeting contains additional text + // from the default output of the test LLM, so instead of checking + // for an exact text match on the new content we just do a `.includes()` + editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => + editorText.includes(newFileContent), + ); + }).timeout(DEFAULT_TIMEOUT.XL); +}); diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index e6444c80c..836c2c60e 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,9 +1,4 @@ -import { - EditorView, - InputBox, - TextEditor, - Workbench, -} from "vscode-extension-tester"; +import { EditorView, TextEditor } from "vscode-extension-tester"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts index 66b82aaf3..6d8812ff1 100644 --- a/extensions/vscode/e2e/tests/Edit.test.ts +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -1,9 +1,9 @@ import { expect } from "chai"; import { - WebView, - VSBrowser, - TextEditor, CodeLens, + TextEditor, + VSBrowser, + WebView, } from "vscode-extension-tester"; import { EditActions } from "../actions/Edit.actions"; diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index 0191d1d63..e9b79472f 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -1,21 +1,22 @@ +import { expect } from "chai"; import { - WebDriver, - VSBrowser, EditorView, InputBox, - TextEditor, - Workbench, - WebView, - WebElement, - until, Key, + TextEditor, + VSBrowser, + WebDriver, + WebElement, + WebView, + Workbench, + until, } from "vscode-extension-tester"; + +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; -import { GUIActions } from "../actions/GUI.actions"; -import { expect } from "chai"; import { TestUtils } from "../TestUtils"; -import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; describe("Keyboard Shortcuts", () => { let driver: WebDriver; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..4917b02cc 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.24", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.24", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -62,7 +62,7 @@ }, "devDependencies": { "@biomejs/biome": "1.6.4", - "@nestjs/common": "^8.4.7", + "@nestjs/common": "^11.0.16", "@openapitools/openapi-generator-cli": "^2.5.2", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", @@ -88,7 +88,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.5.12", + "vite": "^4.5.13", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -1433,43 +1433,29 @@ "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" }, - "node_modules/@nestjs/axios": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", - "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", - "dev": true, - "peerDependencies": { - "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", - "axios": "^1.3.1", - "rxjs": "^6.0.0 || ^7.0.0" - } - }, "node_modules/@nestjs/common": { - "version": "8.4.7", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-8.4.7.tgz", - "integrity": "sha512-m/YsbcBal+gA5CFrDpqXqsSfylo+DIQrkFY3qhVIltsYRfu8ct8J9pqsTO6OPf3mvqdOpFGrV5sBjoyAzOBvsw==", + "version": "11.0.16", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.16.tgz", + "integrity": "sha512-agvuQ8su4aZ+PVxAmY89odG1eR97HEQvxPmTMdDqyvDWzNerl7WQhUEd+j4/UyNWcF1or1UVcrtPj52x+eUSsA==", "dev": true, + "license": "MIT", "dependencies": { - "axios": "0.27.2", "iterare": "1.2.1", - "tslib": "2.4.0", - "uuid": "8.3.2" + "tslib": "2.8.1", + "uid": "2.0.2" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/nest" }, "peerDependencies": { - "cache-manager": "*", "class-transformer": "*", "class-validator": "*", - "reflect-metadata": "^0.1.12", + "file-type": "^20.4.1", + "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, "peerDependenciesMeta": { - "cache-manager": { - "optional": true - }, "class-transformer": { "optional": true }, @@ -1478,31 +1464,6 @@ } } }, - "node_modules/@nestjs/common/node_modules/axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "dev": true, - "dependencies": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "node_modules/@nestjs/common/node_modules/tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true - }, - "node_modules/@nestjs/common/node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "dev": true, - "bin": { - "uuid": "dist/bin/uuid" - } - }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1692,6 +1653,18 @@ "url": "https://opencollective.com/openapi_generator" } }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/axios": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-3.1.1.tgz", + "integrity": "sha512-ySoxrzqX80P1q6LKLKGcgyBd2utg4gbC+4FsJNpXYvILorMlxss/ECNogD9EXLCE4JS5exVFD5ez0nK5hXcNTQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0", + "axios": "^1.3.1", + "rxjs": "^6.0.0 || ^7.0.0" + } + }, "node_modules/@openapitools/openapi-generator-cli/node_modules/@nestjs/common": { "version": "10.4.6", "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.6.tgz", @@ -1963,6 +1936,53 @@ "resolved": "https://registry.npmjs.org/@tediousjs/connection-string/-/connection-string-0.5.0.tgz", "integrity": "sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ==" }, + "node_modules/@tokenizer/inflate": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", + "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "fflate": "^0.8.2", + "token-types": "^6.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/inflate/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -5941,6 +5961,14 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/figures": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", @@ -5977,6 +6005,26 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/file-type": { + "version": "20.4.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz", + "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/inflate": "^0.2.6", + "strtok3": "^10.2.0", + "token-types": "^6.0.0", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, "node_modules/file-uri-to-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", @@ -10090,6 +10138,21 @@ "node": "*" } }, + "node_modules/peek-readable": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-7.0.0.tgz", + "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -12046,6 +12109,25 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/strtok3": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", + "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/style-to-object": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.4.4.tgz", @@ -12677,6 +12759,25 @@ "node": ">=0.6" } }, + "node_modules/token-types": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", + "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/tough-cookie": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", @@ -12916,6 +13017,20 @@ "node": ">=8" } }, + "node_modules/uint8array-extras": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz", + "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/underscore": { "version": "1.13.7", "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", @@ -13322,9 +13437,9 @@ } }, "node_modules/vite": { - "version": "4.5.12", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz", - "integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==", + "version": "4.5.13", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz", + "integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 6ac6afd30..ade2b79fa 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.21", + "version": "1.1.24", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -92,11 +92,6 @@ "default": true, "markdownDescription": "Continue collects anonymous usage data, cleaned of PII, to help us improve the product for our users. Read more at [continue.dev › Telemetry](https://docs.continue.dev/telemetry)." }, - "continue.enableContinueForTeams": { - "type": "boolean", - "default": false, - "markdownDescription": "Enable Continue for teams beta features. To sign in, click the gear icon to go to the settings page, and click Sign In." - }, "continue.showInlineTip": { "type": "boolean", "default": true, @@ -588,6 +583,10 @@ { "fileMatch": ".continuerc.json", "url": "./continue_rc_schema.json" + }, + { + "fileMatch": "**/config.yaml", + "url": "./config-yaml-schema.json" } ] }, @@ -607,6 +606,7 @@ "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", "package-all": "node scripts/package-all.js", @@ -633,7 +633,7 @@ }, "devDependencies": { "@biomejs/biome": "1.6.4", - "@nestjs/common": "^8.4.7", + "@nestjs/common": "^11.0.16", "@openapitools/openapi-generator-cli": "^2.5.2", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", @@ -659,7 +659,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.5.12", + "vite": "^4.5.13", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index d8a9d4e68..9382e2b7a 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,4 +1,5 @@ const fs = require("fs"); +const { writeBuildTimestamp } = require("./utils"); const esbuild = require("esbuild"); @@ -49,6 +50,8 @@ const esbuildConfig = { }; (async () => { + // Create .buildTimestamp.js before starting the first build + writeBuildTimestamp(); // Bundles the extension into one file if (flags.includes("--watch")) { const ctx = await esbuild.context(esbuildConfig); @@ -74,7 +77,7 @@ const esbuildConfig = { }); console.log("Triggering VS Code Extension esbuild rebuild..."); - fs.utimesSync(inFile, new Date(), new Date()); + writeBuildTimestamp(); } else { await esbuild.build(esbuildConfig); } diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index aeab677ca..c16e627c3 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,11 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema } = require("./utils"); +const { + copyConfigSchema, + writeBuildTimestamp, + generateConfigYamlSchema, +} = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -63,6 +67,9 @@ const isMacTarget = target?.startsWith("darwin"); (async () => { console.log("[info] Packaging extension for target ", target); + // Generate and copy over config-yaml-schema.json + generateConfigYamlSchema(); + // Copy config schemas to intellij copyConfigSchema(); @@ -71,6 +78,9 @@ const isMacTarget = target?.startsWith("darwin"); process.chdir("extensions/vscode"); } + // Make sure we have an initial timestamp file + writeBuildTimestamp(); + // Install node_modules // execCmdSync("npm install"); console.log("[info] npm install in extensions/vscode completed"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index c4d392cfa..7023b6372 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -10,7 +10,20 @@ const { const continueDir = path.join(__dirname, "..", "..", ".."); +function generateConfigYamlSchema() { + process.chdir(path.join(continueDir, "packages", "config-yaml")); + execCmdSync("npm install"); + execCmdSync("npm run build"); + execCmdSync("npm run generate-schema"); + fs.copyFileSync( + path.join("schema", "config-yaml-schema.json"), + path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"), + ); + console.log("[info] Generated config.yaml schema"); +} + function copyConfigSchema() { + process.chdir(path.join(continueDir, "extensions", "vscode")); // Modify and copy for .continuerc.json const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { @@ -511,7 +524,22 @@ async function copyScripts() { console.log("[info] Copied script files"); } +// We can't simply touch one of our files to trigger a rebuild, because +// esbuild doesn't always use modifications times to detect changes - +// for example, if it finds a file changed within the last 3 seconds, +// it will fall back to full-contents-comparison for that file +// +// So to facilitate development workflows, we always include a timestamp string +// in the build +function writeBuildTimestamp() { + fs.writeFileSync( + "src/.buildTimestamp.ts", + `export default "${new Date().toISOString()}";\n`, + ); +} + module.exports = { + generateConfigYamlSchema, copyConfigSchema, installNodeModules, buildGui, @@ -526,4 +554,5 @@ module.exports = { downloadRipgrepBinary, copyTokenizers, copyScripts, + writeBuildTimestamp, }; diff --git a/extensions/vscode/scripts/write-build-timestamp.js b/extensions/vscode/scripts/write-build-timestamp.js new file mode 100644 index 000000000..a26f9b8d3 --- /dev/null +++ b/extensions/vscode/scripts/write-build-timestamp.js @@ -0,0 +1,3 @@ +const { writeBuildTimestamp } = require("./utils"); + +writeBuildTimestamp(); diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 3c8b66dcd..364140cb4 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -759,19 +759,11 @@ class VsCodeIde implements IDE { 60, ), userToken: settings.get("userToken", ""), - enableControlServerBeta: settings.get( - "enableContinueForTeams", - false, - ), continueTestEnvironment: "production", pauseCodebaseIndexOnStart: settings.get( "pauseCodebaseIndexOnStart", false, ), - // settings.get( - // "enableControlServerBeta", - // false, - // ), }; return ideSettings; } diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 1bd22c7f4..bfc344b06 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -2,6 +2,7 @@ import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; +import * as path from "path"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; @@ -32,6 +33,22 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); } + // Only set the YAML schema configuration if it hasn't been set before + if (!context.globalState.get("yamlSchemaConfigured")) { + vscode.workspace.getConfiguration("yaml").update( + "schemas", + { + [path.join( + context.extension.extensionUri.fsPath, + "config-yaml-schema.json", + )]: [".continue/**/*.yaml"], + }, + vscode.ConfigurationTarget.Global, + ); + // Mark that we've configured the YAML schema + context.globalState.update("yamlSchemaConfigured", true); + } + const api = new VsCodeContinueApi(vscodeExtension); const continuePublicApi = { registerCustomContextProvider: api.registerCustomContextProvider.bind(api), diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts new file mode 100644 index 000000000..3af716fc2 --- /dev/null +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -0,0 +1,187 @@ +import { ConfigHandler } from "core/config/ConfigHandler"; +import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; +import { getUriPathBasename } from "core/util/uri"; +import * as vscode from "vscode"; + +import { VerticalDiffManager } from "../diff/vertical/manager"; +import { VsCodeIde } from "../VsCodeIde"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; + +export interface ApplyToFileOptions { + streamId: string; + filepath?: string; + text: string; + toolCallId?: string; +} + +/** + * Handles applying text/code to files including diff generation and streaming + */ +export class ApplyManager { + constructor( + private readonly ide: VsCodeIde, + private readonly webviewProtocol: VsCodeWebviewProtocol, + private readonly verticalDiffManager: VerticalDiffManager, + private readonly configHandler: ConfigHandler, + ) {} + + async applyToFile({ + streamId, + filepath, + text, + toolCallId, + }: ApplyToFileOptions) { + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "streaming", + fileContent: text, + toolCallId, + }); + + if (filepath) { + await this.ensureFileOpen(filepath); + } + + const { activeTextEditor } = vscode.window; + if (!activeTextEditor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + + const hasExistingDocument = !!activeTextEditor.document.getText().trim(); + + if (hasExistingDocument) { + await this.handleExistingDocument( + activeTextEditor, + text, + streamId, + toolCallId, + ); + } else { + await this.handleEmptyDocument( + activeTextEditor, + text, + streamId, + toolCallId, + ); + } + } + + private async ensureFileOpen(filepath: string): Promise { + const fileExists = await this.ide.fileExists(filepath); + if (!fileExists) { + await this.ide.writeFile(filepath, ""); + await this.ide.openFile(filepath); + } + await this.ide.openFile(filepath); + } + + private async handleEmptyDocument( + editor: vscode.TextEditor, + text: string, + streamId: string, + toolCallId?: string, + ) { + await editor.edit((builder) => + builder.insert(new vscode.Position(0, 0), text), + ); + + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "closed", + numDiffs: 0, + fileContent: text, + toolCallId, + }); + } + + private async handleExistingDocument( + editor: vscode.TextEditor, + text: string, + streamId: string, + toolCallId?: string, + ) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + vscode.window.showErrorMessage("Config not loaded"); + return; + } + + const llm = + config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; + if (!llm) { + vscode.window.showErrorMessage( + `No model with roles "apply" or "chat" found in config.`, + ); + return; + } + + const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( + editor.document.getText(), + text, + getUriPathBasename(editor.document.uri.toString()), + llm, + ); + + if (isInstantApply) { + await this.verticalDiffManager.streamDiffLines( + diffLinesGenerator, + isInstantApply, + streamId, + toolCallId, + ); + } else { + await this.handleNonInstantDiff( + editor, + text, + llm, + streamId, + this.verticalDiffManager, + toolCallId, + ); + } + } + + /** + * Creates a prompt for applying code edits + */ + private getApplyPrompt(text: string): string { + return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`; + } + + private async handleNonInstantDiff( + editor: vscode.TextEditor, + text: string, + llm: any, + streamId: string, + verticalDiffManager: VerticalDiffManager, + toolCallId?: string, + ) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + vscode.window.showErrorMessage("Config not loaded"); + return; + } + + const prompt = this.getApplyPrompt(text); + const fullEditorRange = new vscode.Range( + 0, + 0, + editor.document.lineCount - 1, + editor.document.lineAt(editor.document.lineCount - 1).text.length, + ); + const rangeToApplyTo = editor.selection.isEmpty + ? fullEditorRange + : editor.selection; + + await verticalDiffManager.streamEdit({ + input: prompt, + llm, + streamId, + range: rangeToApplyTo, + newCode: text, + toolCallId, + rules: config.rules, + }); + } +} diff --git a/extensions/vscode/src/apply/index.ts b/extensions/vscode/src/apply/index.ts new file mode 100644 index 000000000..43b6ac276 --- /dev/null +++ b/extensions/vscode/src/apply/index.ts @@ -0,0 +1 @@ +export * from "./ApplyManager"; diff --git a/extensions/vscode/src/apply/utils.ts b/extensions/vscode/src/apply/utils.ts new file mode 100644 index 000000000..69ea37a3e --- /dev/null +++ b/extensions/vscode/src/apply/utils.ts @@ -0,0 +1,15 @@ +import { ILLM } from "core"; + +export const FAST_APPLY_MODELS: Array = ["Fast-Apply"]; + +/** + * Checks against model names, which can include proxy prefixes + * such as `continuedev/hub` + * @param llm + * @returns + */ +export function isFastApplyModel(llm: ILLM): boolean { + return FAST_APPLY_MODELS?.some((fastApplyModel) => + llm.model.toLowerCase().includes(fastApplyModel.toLowerCase()) + ); +} diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 9009d2b58..f44e5fed7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -12,7 +12,10 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; +import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; import { walkDirAsync } from "core/indexing/walkDir"; +import { isModelInstaller } from "core/llm"; +import { startLocalOllama } from "core/util/ollamaHelper"; import { getDevDataFilePath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import readLastLines from "read-last-lines"; @@ -29,7 +32,6 @@ import { } from "./autocomplete/statusBar"; import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; - import { VerticalDiffManager } from "./diff/vertical/manager"; import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; @@ -37,9 +39,6 @@ import { Battery } from "./util/battery"; 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"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -364,23 +363,23 @@ const getCommandsMap: ( throw new Error("Config not loaded"); } - const modelTitle = - config.selectedModelByRole.edit?.title ?? - (await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - )); + const llm = + config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No edit or chat model selected"); + } void sidebar.webviewProtocol.request("incrementFtc", undefined); - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, + await verticalDiffManager.streamEdit({ + input: + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + llm, onlyOneInsertion, - undefined, range, - ); + rules: config.rules, + }); } return { "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 4d4256a1f..6c94ab343 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { ChatMessage, DiffLine } from "core"; +import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; @@ -6,10 +6,11 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import * as URI from "uri-js"; import * as vscode from "vscode"; +import { isFastApplyModel } from "../../apply/utils"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; +import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; -import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -270,16 +271,27 @@ export class VerticalDiffManager { } } - async streamEdit( - input: string, - modelTitle: string | undefined, - streamId?: string, - onlyOneInsertion?: boolean, - quickEdit?: string, - range?: vscode.Range, - newCode?: string, - toolCallId?: string, - ): Promise { + async streamEdit({ + input, + llm, + streamId, + onlyOneInsertion, + quickEdit, + range, + newCode, + toolCallId, + rules, + }: { + input: string; + llm: ILLM; + streamId?: string; + onlyOneInsertion?: boolean; + quickEdit?: string; + range?: vscode.Range; + newCode?: string; + toolCallId?: string; + rules: RuleWithSource[]; + }): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); let editor = vscode.window.activeTextEditor; @@ -308,13 +320,13 @@ export class VerticalDiffManager { // Previous diff was a quickEdit // Check if user has highlighted a range let rangeBool = - startLine != endLine || - editor.selection.start.character != editor.selection.end.character; + startLine !== endLine || + editor.selection.start.character !== editor.selection.end.character; // Check if the range is different from the previous range let newRangeBool = - startLine != existingHandler.range.start.line || - endLine != existingHandler.range.end.line; + startLine !== existingHandler.range.start.line || + endLine !== existingHandler.range.end.line; if (!rangeBool || !newRangeBool) { // User did not highlight a new range -> use start/end from the previous quickEdit @@ -345,6 +357,7 @@ export class VerticalDiffManager { startLine, endLine, { + instant: isFastApplyModel(llm), input, onStatusUpdate: (status, numDiffs, fileContent) => streamId && @@ -374,7 +387,6 @@ export class VerticalDiffManager { ); } - const llm = await this.configHandler.llmFromTitle(modelTitle); const rangeContent = editor.document.getText(selectedRange); const prefix = pruneLinesFromTop( editor.document.getText( @@ -426,16 +438,17 @@ export class VerticalDiffManager { const streamedLines: string[] = []; async function* recordedStream() { - const stream = streamDiffLines( + const stream = streamDiffLines({ + highlighted: rangeContent, prefix, - rangeContent, suffix, llm, + rules, input, - getMarkdownLanguageTagForFile(fileUri), - !!onlyOneInsertion, + language: getMarkdownLanguageTagForFile(fileUri), + onlyOneInsertion: !!onlyOneInsertion, overridePrompt, - ); + }); for await (const line of stream) { if (line.type === "new" || line.type === "same") { diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index f1aa3f3e4..be2b12487 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -8,6 +8,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; +export { default as buildTimestamp } from "./.buildTimestamp"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { await setupCa(); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index c955f8d51..bcdb88edd 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -193,24 +193,11 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId && orgId !== "null") { - // In case org id is passed with profile id - // Make sure org is updated before profile is set - if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - profileId, - }); - } else { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - }); - } - } else if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedProfile", { - id: profileId, - }); - } + this.core.invoke("config/refreshProfiles", { + selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined), + selectProfileId: + profileId === "null" ? undefined : (profileId ?? undefined), + }); }); // Battery diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 9563eb8a9..d0ada4fc4 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,6 +1,4 @@ import { ConfigHandler } from "core/config/ConfigHandler"; -import { getModelByRole } from "core/config/util"; -import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { FromCoreProtocol, FromWebviewProtocol, @@ -15,10 +13,9 @@ import { WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; import { stripImages } from "core/util/messageContent"; -import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { ILLM } from "core"; +import { ApplyManager } from "../apply"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -30,14 +27,13 @@ import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & + ToWebviewFromCoreProtocol; + /** * A shared messenger class between Core and Webview * so we don't have to rewrite some of the handlers */ -type TODO = any; -type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & - ToWebviewFromCoreProtocol; - export class VsCodeMessenger { onWebview( messageType: T, @@ -129,115 +125,19 @@ export class VsCodeMessenger { }); this.onWebview("applyToFile", async ({ data }) => { - webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "streaming", - fileContent: data.text, - toolCallId: data.toolCallId, - }); + const [verticalDiffManager, configHandler] = await Promise.all([ + verticalDiffManagerPromise, + configHandlerPromise, + ]); - if (data.filepath) { - const fileExists = await this.ide.fileExists(data.filepath); - if (!fileExists) { - await this.ide.writeFile(data.filepath, ""); - await this.ide.openFile(data.filepath); - } - - await this.ide.openFile(data.filepath); - } - - // Get active text editor - const editor = vscode.window.activeTextEditor; - - if (!editor) { - vscode.window.showErrorMessage("No active editor to apply edits to"); - return; - } - - // If document is empty, insert at 0,0 and finish - if (!editor.document.getText().trim()) { - editor.edit((builder) => - builder.insert(new vscode.Position(0, 0), data.text), - ); - - void webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "closed", - numDiffs: 0, - fileContent: data.text, - toolCallId: data.toolCallId, - }); - - return; - } - - // Get LLM from config - const configHandler = await configHandlerPromise; - const { config } = await configHandler.loadConfig(); - - if (!config) { - vscode.window.showErrorMessage("Config not loaded"); - return; - } - - let llm: ILLM | null | undefined = config.selectedModelByRole.apply; - - if (!llm) { - llm = config.models.find( - (model) => model.title === data.curSelectedModelTitle, - ); - - if (!llm) { - vscode.window.showErrorMessage( - `Model ${data.curSelectedModelTitle} not found in config.`, - ); - return; - } - } - - const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm; - - // Generate the diff and pass through diff manager - const [instant, diffLines] = await applyCodeBlock( - editor.document.getText(), - data.text, - getUriPathBasename(editor.document.uri.toString()), - llm, - fastLlm, + const applyManager = new ApplyManager( + this.ide, + webviewProtocol, + verticalDiffManager, + configHandler, ); - const verticalDiffManager = await this.verticalDiffManagerPromise; - - if (instant) { - await verticalDiffManager.streamDiffLines( - diffLines, - instant, - data.streamId, - data.toolCallId, - ); - } else { - const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; - const fullEditorRange = new vscode.Range( - 0, - 0, - editor.document.lineCount - 1, - editor.document.lineAt(editor.document.lineCount - 1).text.length, - ); - const rangeToApplyTo = editor.selection.isEmpty - ? fullEditorRange - : editor.selection; - - await verticalDiffManager.streamEdit( - prompt, - llm.title, - data.streamId, - undefined, - undefined, - rangeToApplyTo, - data.text, - data.toolCallId, - ); - } + await applyManager.applyToFile(data); }); this.onWebview("showTutorial", async (msg) => { @@ -292,17 +192,30 @@ export class VsCodeMessenger { const { start, end } = msg.data.range.range; const verticalDiffManager = await verticalDiffManagerPromise; - const fileAfterEdit = await verticalDiffManager.streamEdit( - stripImages(prompt), - msg.data.selectedModelTitle, - "edit", - undefined, - undefined, - new vscode.Range( + const configHandler = await configHandlerPromise; + const { config } = await configHandler.loadConfig(); + + if (!config) { + throw new Error("Edit: Failed to load config"); + } + + const model = + config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No Edit or Chat model selected"); + } + + const fileAfterEdit = await verticalDiffManager.streamEdit({ + input: stripImages(prompt), + llm: model, + streamId: "edit", + range: new vscode.Range( new vscode.Position(start.line, start.character), new vscode.Position(end.line, end.character), ), - ); + rules: config.rules, + }); void this.webviewProtocol.request("setEditStatus", { status: "accepting", diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts new file mode 100644 index 000000000..dd46ad401 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts @@ -0,0 +1,34 @@ +import * as vscode from "vscode"; + +export class DownloadYamlExtensionCodeLensProvider + implements vscode.CodeLensProvider +{ + private yamlExtensionDownloaded(): boolean { + const yamlExtension = vscode.extensions.getExtension("redhat.vscode-yaml"); + return yamlExtension !== undefined; + } + + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + if (!document.uri.fsPath.includes(".continue")) { + return []; + } + if (this.yamlExtensionDownloaded()) { + return []; + } + + const codeLens: vscode.CodeLens = { + range: new vscode.Range(0, 0, 0, 0), + command: { + title: "Download YAML extension for Intellisense", + command: "workbench.extensions.installExtension", + arguments: ["redhat.vscode-yaml"], + }, + isResolved: true, + }; + + return [codeLens]; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/index.ts b/extensions/vscode/src/lang-server/codeLens/providers/index.ts index 00a309e62..03d89aa44 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/index.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/index.ts @@ -1,3 +1,4 @@ +export { DownloadYamlExtensionCodeLensProvider } from "./DownloadYamlExtensionCodeLensProvider"; export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider"; export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider"; export { VerticalDiffCodeLensProvider as VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index 9138fba8b..e17312fa0 100644 --- a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -19,6 +19,8 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined; +let downloadYamlExtensionCodeLensDisposable: vscode.Disposable | undefined = + undefined; /** * Registers the Quick Actions CodeLens provider if Quick Actions are enabled. @@ -96,6 +98,10 @@ export function registerAllCodeLensProviders( tutorialCodeLensDisposable.dispose(); } + if (downloadYamlExtensionCodeLensDisposable) { + downloadYamlExtensionCodeLensDisposable.dispose(); + } + const verticalDiffCodeLens = new providers.VerticalPerLineCodeLensProvider( editorToVerticalDiffCodeLens, ); @@ -110,6 +116,11 @@ export function registerAllCodeLensProviders( new providers.SuggestionsCodeLensProvider(), ); + downloadYamlExtensionCodeLensDisposable = registerCodeLensProvider( + "yaml", + new providers.DownloadYamlExtensionCodeLensProvider(), + ); + if (config) { registerQuickActionsProvider(config, context); diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index 074ec4d86..f982c5c55 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -34,7 +34,7 @@ export async function getContextProvidersString( provider.description.displayTitle === selectedProvider.label, ); - if (!provider) { + if (!provider || !config.selectedModelByRole.chat) { return []; } @@ -43,7 +43,7 @@ export async function getContextProvidersString( ide, embeddingsProvider: config.selectedModelByRole.embed, reranker: config.selectedModelByRole.rerank, - llm: config.models[0], + llm: config.selectedModelByRole.chat, fullInput: "", selectedCode: [], fetch: (url, init) => diff --git a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts b/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts deleted file mode 100644 index d46ed6d43..000000000 --- a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ContinueConfig } from "core"; -import { QuickPickItem, window } from "vscode"; - -export async function getModelQuickPickVal( - curModelTitle: string, - config: ContinueConfig, -) { - const modelItems: QuickPickItem[] = config.models.map((model) => { - const isCurModel = curModelTitle === model.title; - - return { - label: model.title - ? `${isCurModel ? "$(check)" : " "} ${model.title}` - : "Model title not set", - }; - }); - - const selectedItem = await window.showQuickPick(modelItems, { - title: "Models", - placeHolder: "Select a model", - }); - - if (!selectedItem) { - return undefined; - } - - const selectedModelTitle = config.models.find( - (model) => model.title && selectedItem.label.includes(model.title), - )?.title; - - return selectedModelTitle; -} diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index ec84eb81b..fa526b6e5 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { IDE } from "core"; +import { IDE, ILLM, RuleWithSource } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { DataLogger } from "core/data/log"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -8,10 +9,8 @@ import { VerticalDiffManager } from "../diff/vertical/manager"; import { FileSearch } from "../util/FileSearch"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { DataLogger } from "core/data/log"; import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick"; import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; -import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; // @ts-ignore - error finding typings // @ts-ignore @@ -23,7 +22,6 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; enum QuickEditInitialItemLabels { History = "History", ContextProviders = "Context providers", - Model = "Model", Submit = "Submit", } @@ -100,11 +98,6 @@ export class QuickEdit { */ private contextProviderStr?: string; - /** - * Stores the current model title for potential changes - */ - private _curModelTitle?: string; - constructor( private readonly verticalDiffManager: VerticalDiffManager, private readonly configHandler: ConfigHandler, @@ -224,7 +217,7 @@ export class QuickEdit { default: break; } - let model = await this.getCurModelTitle(); + let model = await this.getCurModel(); void DataLogger.getInstance().logDevData({ name: "quickEdit", @@ -233,7 +226,7 @@ export class QuickEdit { path, label, diffs: this.verticalDiffManager.logDiffs, - model, + model: model?.title, }, }); @@ -245,12 +238,15 @@ export class QuickEdit { prompt: string, path: string | undefined, ) => { - const modelTitle = await this.getCurModelTitle(); - if (!modelTitle) { + const model = await this.getCurModel(); + if (!model) { throw new Error("No model selected"); } - await this._streamEditWithInputAndContext(prompt, modelTitle); + const { config } = await this.configHandler.loadConfig(); + const rules = config?.rules ?? []; // no need to error - getCurModel above will handle + + await this._streamEditWithInputAndContext(prompt, model, rules); this.openAcceptRejectMenu(prompt, path); }; @@ -266,25 +262,13 @@ export class QuickEdit { /** * Gets the model title the user has chosen, or their default model */ - private async getCurModelTitle(): Promise { - if (this._curModelTitle) { - return this._curModelTitle; - } - + private async getCurModel(): Promise { const { config } = await this.configHandler.loadConfig(); if (!config) { - return undefined; + return null; } - return ( - config.selectedModelByRole.edit?.title ?? - (await this.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - false, - )) ?? - config.models[0]?.title - ); + return config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; } /** @@ -316,7 +300,8 @@ export class QuickEdit { private async _streamEditWithInputAndContext( prompt: string, - modelTitle: string, + model: ILLM, + rules: RuleWithSource[], ) { // Extracts all file references from the prompt string, // which are denoted by an '@' symbol followed by @@ -341,17 +326,16 @@ export class QuickEdit { void this.webviewProtocol.request("incrementFtc", undefined); - await this.verticalDiffManager.streamEdit( - prompt, - modelTitle, - undefined, - undefined, - this.previousInput, - this.range, - ); + await this.verticalDiffManager.streamEdit({ + input: prompt, + llm: model, + quickEdit: this.previousInput, + range: this.range, + rules, + }); } - private getInitialItems(modelTitle: string): vscode.QuickPickItem[] { + private getInitialItems(): vscode.QuickPickItem[] { return [ { label: QuickEditInitialItemLabels.History, @@ -361,10 +345,6 @@ export class QuickEdit { label: QuickEditInitialItemLabels.ContextProviders, detail: "$(add) Add context to your prompt", }, - { - label: QuickEditInitialItemLabels.Model, - detail: `$(chevron-down) ${modelTitle}`, - }, ]; } @@ -372,7 +352,7 @@ export class QuickEdit { label: QuickEditInitialItemLabels | undefined; value: string | undefined; }> { - const modelTitle = await this.getCurModelTitle(); + const modelTitle = await this.getCurModel(); if (!modelTitle) { this.ide.showToast("error", "Please configure a model to use Quick Edit"); @@ -381,7 +361,7 @@ export class QuickEdit { const quickPick = vscode.window.createQuickPick(); - const initialItems = this.getInitialItems(modelTitle); + const initialItems = this.getInitialItems(); quickPick.items = initialItems; quickPick.placeholder = "Enter a prompt to edit your code (@ to search files, ⏎ to submit)"; @@ -552,27 +532,6 @@ export class QuickEdit { break; - case QuickEditInitialItemLabels.Model: - const curModelTitle = await this.getCurModelTitle(); - - if (!curModelTitle) { - break; - } - - const selectedModelTitle = await getModelQuickPickVal( - curModelTitle, - config, - ); - - if (selectedModelTitle) { - this._curModelTitle = selectedModelTitle; - } - - // Recurse back to let the user write their prompt - this.initiateNewQuickPick(editor, params); - - break; - case QuickEditInitialItemLabels.Submit: if (selectedValue) { prompt = selectedValue; diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 03d9b2174..2e6acfb86 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -1,7 +1,7 @@ import crypto from "crypto"; import { ControlPlaneSessionInfo } from "core/control-plane/client"; -import { EXTENSION_NAME, getControlPlaneEnvSync } from "core/control-plane/env"; +import { getControlPlaneEnvSync } from "core/control-plane/env"; import fetch from "node-fetch"; import { v4 as uuidv4 } from "uuid"; import { @@ -16,7 +16,6 @@ import { ProgressLocation, Uri, window, - workspace, } from "vscode"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; @@ -25,13 +24,7 @@ import { UriEventHandler } from "./uriHandler"; const AUTH_NAME = "Continue"; -const enableControlServerBeta = workspace - .getConfiguration(EXTENSION_NAME) - .get("enableContinueForTeams", false); -const controlPlaneEnv = getControlPlaneEnvSync( - true ? "production" : "none", - enableControlServerBeta, -); +const controlPlaneEnv = getControlPlaneEnvSync(true ? "production" : "none"); const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; diff --git a/extensions/vscode/src/test/test-suites/main.test.ts b/extensions/vscode/src/test/test-suites/main.test.ts deleted file mode 100644 index 2cd1945fa..000000000 --- a/extensions/vscode/src/test/test-suites/main.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from "node:assert"; - -import { describe, test } from "mocha"; -import * as vscode from "vscode"; - -import { VsCodeExtension } from "../../extension/VsCodeExtension"; - -describe("Extension Test Suite", () => { - vscode.window.showInformationMessage("Start all tests."); - - // test("Make sure that nothing breaks after 10 seconds", async () => { - // await new Promise((resolve) => setTimeout(resolve, 10_000)); - // }); - - test("Get the default model from webview", async () => { - const continueExtensionApi = - vscode.extensions.getExtension("continue.continue"); - const extension: VsCodeExtension = continueExtensionApi?.exports.extension; - await new Promise((resolve) => setTimeout(resolve, 400)); - await vscode.commands.executeCommand("continue.focusContinueInput"); - await new Promise((resolve) => setTimeout(resolve, 400)); - const title = await ( - await extension.webviewProtocolPromise - ).request("getDefaultModelTitle", undefined); - assert.strictEqual(typeof title, "string"); - assert.strictEqual(title, "Test Model"); - }); -}); diff --git a/gui/package-lock.json b/gui/package-lock.json index 69c571f84..00986cfcf 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.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -93,7 +93,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engines": { @@ -109,7 +109,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -204,6 +204,28 @@ "node": ">=20.11.0" } }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -544,23 +566,9 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, - "node_modules/@continuedev/config-types": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", - "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", - "dependencies": { - "zod": "^3.23.8" - } - }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.71", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", - "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@emotion/is-prop-valid": { "version": "1.3.1", @@ -12248,9 +12256,9 @@ } }, "node_modules/vite": { - "version": "4.5.11", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz", - "integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==", + "version": "4.5.13", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz", + "integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==", "dev": true, "license": "MIT", "dependencies": { @@ -13773,6 +13781,7 @@ "version": "2.6.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz", "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", + "dev": true, "bin": { "yaml": "bin.mjs" }, @@ -13792,14 +13801,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/zod": { - "version": "3.24.2", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", - "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/gui/package.json b/gui/package.json index 2d4ed109b..50d2c6122 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -101,7 +101,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engine-strict": true, diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 18c68721f..15082d35b 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -5,7 +5,6 @@ import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProvide import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; import ConfigPage from "./pages/config"; -import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; @@ -34,10 +33,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: ROUTES.CONFIG_ERROR, - element: , - }, { path: ROUTES.CONFIG, element: , diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectAllButtons.tsx similarity index 90% rename from gui/src/components/StepContainer/AcceptRejectAllButtons.tsx rename to gui/src/components/AcceptRejectAllButtons.tsx index 8d2e59dd3..7a9c28062 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/AcceptRejectAllButtons.tsx @@ -1,10 +1,10 @@ -import { useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; -import { getMetaKeyLabel } from "../../util"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsSingleRangeEditOrInsertion } from "../../redux/slices/sessionSlice"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice"; +import { getMetaKeyLabel } from "../util"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx index 3d59ac239..9651ec235 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -1,18 +1,18 @@ -import FileIcon from "../FileIcon"; import { ChevronDownIcon, ChevronRightIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useState } from "react"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import styled from "styled-components"; import { CodeToEdit } from "core"; +import { getMarkdownLanguageTagForFile } from "core/util"; import { getLastNUriRelativePathParts, getUriPathBasename, } from "core/util/uri"; +import { useState } from "react"; +import styled from "styled-components"; +import FileIcon from "../FileIcon"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; export interface CodeToEditListItemProps { code: CodeToEdit; diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/FeedbackButtons.tsx similarity index 86% rename from gui/src/components/StepContainer/FeedbackButtons.tsx rename to gui/src/components/FeedbackButtons.tsx index 4ef09a833..6ad0992df 100644 --- a/gui/src/components/StepContainer/FeedbackButtons.tsx +++ b/gui/src/components/FeedbackButtons.tsx @@ -1,12 +1,12 @@ import { - HandThumbUpIcon, HandThumbDownIcon, + HandThumbUpIcon, } from "@heroicons/react/24/outline"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { ChatHistoryItem } from "core"; -import { useState, useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; +import { useContext, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; export interface FeedbackButtonsProps { item: ChatHistoryItem; diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 24003595a..839f7ed7c 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -4,9 +4,9 @@ import { useMemo } from "react"; import { themeIcons } from "seti-file-icons"; export interface FileIconProps { - filename: string; height: `${number}px`; width: `${number}px`; + filename: string; } export default function FileIcon({ filename, height, width }: FileIconProps) { diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index b2efd221c..d6e79651c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -1,11 +1,11 @@ import { useAppSelector } from "../redux/hooks"; -import { selectDefaultModel } from "../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../redux/slices/configSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; import { getLocalStorage } from "../util/localStorage"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; function Footer() { - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); if (defaultModel?.provider === "free-trial") { return ( diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 11a5a36df..8b7f3ba38 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,5 +1,6 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; +import { getUriPathBasename } from "core/util/uri"; import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; @@ -12,10 +13,6 @@ import { updateSession, } from "../../redux/thunks/session"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { - getLastNUriRelativePathParts, - getUriPathBasename, -} from "core/util/uri"; export function HistoryTableRow({ sessionMetadata, @@ -65,52 +62,48 @@ export function HistoryTableRow({ }; return ( - - setHovered(true)} - onMouseLeave={() => setHovered(false)} - > -
{ - if (sessionMetadata.sessionId !== currentSessionId) { - await dispatch( - loadSession({ - sessionId: sessionMetadata.sessionId, - saveCurrentSession: true, - }), - ); - } - navigate("/"); - }} - > -
- {editing ? ( -
- titleInput && titleInput.focus()} - value={sessionTitleEditValue} - onChange={(e) => setSessionTitleEditValue(e.target.value)} - onKeyUp={(e) => handleKeyUp(e)} - onBlur={() => setEditing(false)} - /> -
- ) : ( - - {sessionMetadata.title} - - )} + setHovered(true)} + onMouseLeave={() => setHovered(false)} + data-testid={`history-row-${index}`} + className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" + onClick={async () => { + if (sessionMetadata.sessionId !== currentSessionId) { + await dispatch( + loadSession({ + sessionId: sessionMetadata.sessionId, + saveCurrentSession: true, + }), + ); + } + navigate("/"); + }} + > +
+ {editing ? ( +
+ titleInput && titleInput.focus()} + value={sessionTitleEditValue} + onChange={(e) => setSessionTitleEditValue(e.target.value)} + onKeyUp={(e) => handleKeyUp(e)} + onBlur={() => setEditing(false)} + /> +
+ ) : ( + + {sessionMetadata.title} + + )} -
- - {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} - - {/* Uncomment to show the date */} - {/* +
+ + {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} + + {/* Uncomment to show the date */} + {/* {date.toLocaleString("en-US", { year: "2-digit", month: "2-digit", @@ -120,33 +113,31 @@ export function HistoryTableRow({ hour12: true, })} */} -
-
- - {hovered && !editing && ( -
- { - e.stopPropagation(); - setEditing(true); - }} - > - - - { - e.stopPropagation(); - await dispatch(deleteSession(sessionMetadata.sessionId)); - }} - > - - -
- )}
- +
+ + {hovered && !editing && ( +
+ { + e.stopPropagation(); + setEditing(true); + }} + > + + + { + e.stopPropagation(); + await dispatch(deleteSession(sessionMetadata.sessionId)); + }} + > + + +
+ )} ); } diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index e8d6ef2fd..e51dc45eb 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,12 +1,29 @@ import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; -import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; -import Shortcut from '../gui/Shortcut'; +import React, { + Fragment, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import Shortcut from "../gui/Shortcut"; -import { getFontSize, getMetaKeyLabel } from "../../util"; -import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; -import { useAppSelector } from "../../redux/hooks"; +import { useNavigate } from "react-router-dom"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + newSession, + setAllSessionMetadata, +} from "../../redux/slices/sessionSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { refreshSessionMetadata } from "../../redux/thunks/session"; +import { getFontSize, getPlatform } from "../../util"; +import { ROUTES } from "../../util/navigation"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import { HistoryTableRow } from "./HistoryTableRow"; const parseDate = (date: string): Date => { let dateObj = new Date(date); @@ -20,7 +37,10 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { + const dispatch = useAppDispatch(); + const navigate = useNavigate(); const searchInputRef = React.useRef(null); + const ideMessenger = useContext(IdeMessengerContext); const [searchTerm, setSearchTerm] = useState(""); @@ -50,6 +70,8 @@ export function History() { } }, [allSessionMetadata]); + const platform = useMemo(() => getPlatform(), []); + const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch .search(searchTerm, { @@ -73,11 +95,38 @@ export function History() { const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); const earlier = new Date(0); + const showClearSessionsDialog = () => { + dispatch( + setDialogMessage( + { + // optimistic update + dispatch(setAllSessionMetadata([])); + + // actual update + refresh + await ideMessenger.request("history/clear", undefined); + dispatch(refreshSessionMetadata({})); + + // start a new session + dispatch(newSession()); + navigate(ROUTES.HOME); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + return ( -
-
+
+
)}
+
+ {filteredAndSortedSessions.length === 0 && ( +
+ No past sessions found. To start a new session, either click the "+" + button or use the keyboard shortcut: meta L +
+ )} - {filteredAndSortedSessions.length === 0 && ( -
- No past sessions found. To start a new session, either click the "+" - button or use the keyboard shortcut: meta L -
- - )} - - - - {filteredAndSortedSessions.map((session, index) => { - const prevDate = - index > 0 - ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) - : earlier; - const date = parseDate(session.dateCreated); - return ( - - {index === 0 && date > yesterday && ( - - - - )} - {date < yesterday && - date > lastWeek && - prevDate > yesterday && ( +
Today
+ + {filteredAndSortedSessions.map((session, index) => { + const prevDate = + index > 0 + ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) + : earlier; + const date = parseDate(session.dateCreated); + return ( + + {index === 0 && date > yesterday && ( - + )} - {date < lastWeek && date > lastMonth && prevDate > lastWeek && ( - - - - )} - {date < lastMonth && prevDate > lastMonth && ( - - - - )} + {date < yesterday && + date > lastWeek && + prevDate > yesterday && ( +
+
+ + )} + {date < lastWeek && + date > lastMonth && + prevDate > lastWeek && ( +
+
+ + )} + {date < lastMonth && prevDate > lastMonth && ( +
+
+ + )} - - - ); - })} - -
This WeekToday
This Month
Older
This WeekThis MonthOlder
-
- - All session data is saved in ~/.continue/sessions - + + + ); + })} + + +
+
+ {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} + + Clear session history + +
); } diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 0f52d3d0b..0c5acda83 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo } from "react"; +import { useEffect } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { CustomScrollbarDiv, defaultBorderRadius } from "."; @@ -19,8 +19,10 @@ import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; import { fontSize, isMetaEquivalentKeyPressed } from "../util"; import { incrementFreeTrialCount } from "../util/freeTrial"; import { ROUTES } from "../util/navigation"; +import { FatalErrorIndicator } from "./config/FatalErrorNotice"; import TextDialog from "./dialogs"; import Footer from "./Footer"; +import { LumpProvider } from "./mainInput/Lump/LumpContext"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; @@ -44,13 +46,6 @@ const Layout = () => { const location = useLocation(); const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); - const { pathname } = useLocation(); - - const configError = useAppSelector((state) => state.config.configError); - - const hasFatalErrors = useMemo(() => { - return configError?.some((error) => error.fatal); - }, [configError]); const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); @@ -238,45 +233,36 @@ const Layout = () => { - -
- { - dispatch(setShowDialog(false)); + + +
{ - dispatch(setShowDialog(false)); - }} - message={dialogMessage} - /> + > + { + dispatch(setShowDialog(false)); + }} + onClose={() => { + dispatch(setShowDialog(false)); + }} + message={dialogMessage} + /> - - - - - {hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && ( -
navigate(ROUTES.CONFIG_ERROR)} - > - Error!{" "} - Could not load config -
Learn More
-
- )} -
- -
-
+ + + + +
+ +
+
+ diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index a4baa9a1e..aa8be2a29 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -37,7 +37,7 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { return ( onboardingCard.close()} testId="onboarding-card" > diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 389ed72dd..d739a8434 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -1,11 +1,12 @@ import { CubeIcon } from "@heroicons/react/24/outline"; import { FormEventHandler, useContext, useState } from "react"; -import { useDispatch } from "react-redux"; import { Button, Input, InputSubtext, lightGray } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { models } from "../../../pages/AddNewModel/configs/models"; import { providers } from "../../../pages/AddNewModel/configs/providers"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; +import { useAppDispatch } from "../../../redux/hooks"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; const { anthropic, mistral } = providers; @@ -25,7 +26,8 @@ interface BestExperienceConfigFormProps { function BestExperienceConfigForm({ onComplete, }: BestExperienceConfigFormProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); @@ -61,7 +63,14 @@ function BestExperienceConfigForm({ model: repoMapConfig, role: "repoMapFileSelection", }); - dispatch(setDefaultModel({ title: chatModelConfig.title, force: true })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: chatModelConfig.title, + }), + ); if (!!autocompleteApiKey) { await ideMessenger.request("addAutocompleteModel", { diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx index 6a7075fac..c98ca6794 100644 --- a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx @@ -1,9 +1,9 @@ import { CommandLineIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { StyledActionButton } from "../.."; -import OllamaCompletedStep from "./OllamaCompletedStep"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ToolTip } from "../../gui/Tooltip"; +import OllamaCompletedStep from "./OllamaCompletedStep"; interface OllamaModelDownloadProps { title: string; @@ -27,14 +27,18 @@ function OllamaModelDownload({ return (
-

{title}

+

{title}

{hasDownloaded ? ( ) : ( <> - +

{command}

- +
diff --git a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx index 3839ba6ad..51c782de9 100644 --- a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx @@ -39,7 +39,7 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) { return (

{downloadUrl}

- +
); case OllamaConnectionStatuses.Downloading: @@ -48,7 +48,7 @@ export function OllamaStatus({ isOllamaConnected }: OllamaStatusProps) {

Checking for connection to Ollama at http://localhost:11434

- +
); case OllamaConnectionStatuses.Connected: diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index 4c0deda74..69eed3ffb 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { useAuth } from "../../../context/Auth"; import { useAppSelector } from "../../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import Alert from "../../gui/Alert"; @@ -20,15 +21,24 @@ interface OnboardingCardProps { export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); + const auth = useAuth(); const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); } + function onGetStarted() { + auth.login(true).then((success) => { + if (success) { + onboardingCard.close(isDialog); + } + }); + } + return ( onboardingCard.close()} >
@@ -40,11 +50,10 @@ export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { ) : (
- 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")}> + 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{" "} + here diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index ab197b3d4..c5590e7d8 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -96,7 +96,7 @@ export default function MainTab({ ) : ( -
+
Or, remain local
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 81b0a7a6b..7e99f430d 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -6,15 +6,15 @@ import { LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import { Button } from "../.."; +import { Button, ButtonSubtext } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import AddModelButtonSubtext from "../../AddModelButtonSubtext"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; const OLLAMA_CHECK_INTERVAL_MS = 3000; @@ -23,13 +23,14 @@ interface OnboardingLocalTabProps { } function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const { submitOnboarding } = useSubmitOnboarding("Local", isDialog); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< string[] >([]); + const { selectedProfile } = useAuth(); const [isOllamaConnected, setIsOllamaConnected] = useState(false); @@ -100,10 +101,42 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { return () => clearInterval(intervalId); }, []); + const onClickSubmitOnboarding = () => { + submitOnboarding(); + + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: LOCAL_ONBOARDING_CHAT_TITLE, + }), + ); + }; + + const onClickSkip = () => { + submitOnboarding(); + + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } + }; + return (
-

Install Ollama

+

+ Install Ollama +

@@ -127,28 +160,17 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) {
- + + + Skip and configure manually + +
); diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index d40ed72b9..08a61e2e3 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -1,12 +1,12 @@ import { ChatHistoryItem } from "core"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; -import FeedbackButtons from "./FeedbackButtons"; import { renderChatMessage } from "core/util/messageContent"; -import { CopyIconButton } from "../gui/CopyIconButton"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; import { loadLastSession } from "../../redux/thunks/session"; +import AcceptRejectAllButtons from "../AcceptRejectAllButtons"; +import FeedbackButtons from "../FeedbackButtons"; +import { CopyIconButton } from "../gui/CopyIconButton"; export interface EditActionsProps { index: number; diff --git a/gui/src/components/StepContainer/Reasoning.tsx b/gui/src/components/StepContainer/Reasoning.tsx index d5537c82b..b2c7ec19e 100644 --- a/gui/src/components/StepContainer/Reasoning.tsx +++ b/gui/src/components/StepContainer/Reasoning.tsx @@ -10,7 +10,7 @@ import { vscQuickInputBackground, } from ".."; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; interface ReasoningProps { item: ChatHistoryItem; diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index f016b3474..dce39ea6f 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,12 +1,12 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; import { renderChatMessage } from "core/util/messageContent"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; +import FeedbackButtons from "../FeedbackButtons"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import EditActions from "./EditActions"; -import FeedbackButtons from "./FeedbackButtons"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; export interface ResponseActionsProps { isTruncated: boolean; diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 01560e595..aac4b877a 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -8,7 +8,7 @@ import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { deleteMessage } from "../../redux/slices/sessionSlice"; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; import Reasoning from "./Reasoning"; import ResponseActions from "./ResponseActions"; import ThinkingIndicator from "./ThinkingIndicator"; @@ -43,9 +43,6 @@ export default function StepContainer(props: StepContainerProps) { historyItemAfterThis?.message.role === "thinking"; const hideActions = hideActionSpace || (isStreaming && props.isLast); - // const isStepAheadOfCurCheckpoint = - // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; - useEffect(() => { if (!isStreaming) { const content = renderChatMessage(props.item.message).trim(); @@ -83,9 +80,7 @@ export default function StepContainer(props: StepContainerProps) { } return ( -
+
{uiConfig?.displayRawMarkdown ? (
 {
     };
   }, []);
 
-  const selectedModel = useAppSelector(selectDefaultModel);
+  const selectedModel = useAppSelector(selectSelectedChatModel);
   const isStreaming = useAppSelector((state) => state.session.isStreaming);
 
   const hasContent = Array.isArray(historyItem.message.content)
diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/StyledMarkdownPreview/FilenameLink.tsx
similarity index 100%
rename from gui/src/components/markdown/FilenameLink.tsx
rename to gui/src/components/StyledMarkdownPreview/FilenameLink.tsx
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx
similarity index 60%
rename from gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx
rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx
index 0da1c5c7f..7131e6ad9 100644
--- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx
+++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx
@@ -1,7 +1,6 @@
 import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
 import { ApplyState } from "core";
 import { useEffect, useState } from "react";
-import { lightGray, vscForeground } from "../..";
 import { getMetaKeyLabel } from "../../../util";
 import Spinner from "../../gui/Spinner";
 import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
@@ -14,7 +13,7 @@ interface ApplyActionsProps {
   onClickApply: () => void;
 }
 
-export default function ApplyActions(props: ApplyActionsProps) {
+export function ApplyActions(props: ApplyActionsProps) {
   const [hasRejected, setHasRejected] = useState(false);
   const [showApplied, setShowApplied] = useState(false);
   const isClosed = props.applyState?.status === "closed";
@@ -25,7 +24,7 @@ export default function ApplyActions(props: ApplyActionsProps) {
       setShowApplied(true);
       const timer = setTimeout(() => {
         setShowApplied(false);
-      }, 5_000);
+      }, 3_000);
       return () => clearTimeout(timer);
     }
   }, [isClosed, isSuccessful]);
@@ -37,12 +36,12 @@ export default function ApplyActions(props: ApplyActionsProps) {
 
   const applyButton = (text: string) => (
     
@@ -52,33 +51,36 @@ export default function ApplyActions(props: ApplyActionsProps) {
     case "streaming":
       return (
         
- - Applying changes + + Applying
); case "done": return ( -
- +
+ {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} - {` remaining`} - - - +
+ + + - - - + + + +
); case "closed": @@ -87,7 +89,7 @@ export default function ApplyActions(props: ApplyActionsProps) { return ( Applied - + ); } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton.tsx new file mode 100644 index 000000000..8b06ad03f --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton.tsx @@ -0,0 +1,25 @@ +import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; +import useCopy from "../../../hooks/useCopy"; + +interface CopyButtonProps { + text: string; +} + +export function CopyButton({ text }: CopyButtonProps) { + const { copyText, copied } = useCopy(text); + + return ( +
+
+ {copied ? ( + + ) : ( + + )} +
+
+ ); +} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CreateFileButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CreateFileButton.tsx new file mode 100644 index 000000000..280bb8452 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CreateFileButton.tsx @@ -0,0 +1,23 @@ +import { DocumentPlusIcon } from "@heroicons/react/24/outline"; +import { vscForeground } from "../.."; + +interface CreateFileButtonProps { + onClick: () => void; +} + +export function CreateFileButton({ onClick }: CreateFileButtonProps) { + return ( + <> + + + ); +} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx new file mode 100644 index 000000000..550d1fd28 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx @@ -0,0 +1,42 @@ +import { getLastNPathParts } from "core/util/uri"; +import FileIcon from "../../FileIcon"; +import { ToolTip } from "../../gui/Tooltip"; + +export interface FileInfoProps { + filepath: string; + onClick?: () => void; + range?: string; +} + +const TOOLTIP_ID = "file-info-tooltip"; + +export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { + return ( + <> +
+
+ +
+ + {getLastNPathParts(filepath, 1)} + {range && ` ${range}`} + +
+ + + ); +}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx similarity index 81% rename from gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx index c430c8d62..b730b30e5 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx @@ -5,7 +5,7 @@ export interface GeneratingCodeLoaderProps { codeBlockContent: string; } -export default function GeneratingCodeLoader({ +export function GeneratingCodeLoader({ showLineCount, codeBlockContent, }: GeneratingCodeLoaderProps) { @@ -16,7 +16,7 @@ export default function GeneratingCodeLoader({ : `${numLinesCodeBlock} lines generated`; return ( - + {showLineCount ? linesGeneratedText : "Generating"} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx new file mode 100644 index 000000000..b8784dd07 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx @@ -0,0 +1,21 @@ +import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; + +/** + * Button that inserts code at the current cursor position + */ +interface InsertButtonProps { + onInsert: () => void; +} + +export function InsertButton({ onInsert }: InsertButtonProps) { + return ( +
+
+ +
+
+ ); +} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx new file mode 100644 index 000000000..a50c953f4 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -0,0 +1,47 @@ +import { CommandLineIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { lightGray, vscForeground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +interface RunInTerminalButtonProps { + command: string; +} + +export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { + const ideMessenger = useContext(IdeMessengerContext); + + // Extract just the command line (the line after $ or the first line) + function extractCommand(cmd: string): string { + // If the command contains a $ prompt, extract the line after it + if (cmd.includes('$')) { + const match = cmd.match(/\$\s*([^\n]+)/); + return match ? match[1].trim() : ''; + } + + // Otherwise, just take the first line + return cmd.split('\n')[0].trim(); + } + + function runInTerminal() { + // Extract just the command line + const extractedCommand = extractCommand(command); + void ideMessenger.post("runCommand", { command: extractedCommand }); + } + + return ( +
+
+ <> + + Run + +
+
+ ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx similarity index 93% rename from gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 9ffed883c..6950ee415 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -1,7 +1,7 @@ import { ReactNode, useMemo } from "react"; import { Tooltip } from "react-tooltip"; -import { lightGray, vscForeground } from "../.."; import styled from "styled-components"; +import { lightGray, vscForeground } from "../.."; import { getFontSize } from "../../../util"; export const ToolbarButton = styled.button` @@ -24,12 +24,14 @@ interface ToolbarButtonWithTooltipProps { onClick: () => void; children: ReactNode; tooltipContent: string; + "data-testid"?: string; } export function ToolbarButtonWithTooltip({ onClick, children, tooltipContent, + "data-testid": testId, }: ToolbarButtonWithTooltipProps) { const tooltipId = useMemo( () => `tooltip-${Math.random().toString(36).slice(2, 11)}`, @@ -42,6 +44,7 @@ export function ToolbarButtonWithTooltip({ onClick={onClick} style={{ color: lightGray }} data-tooltip-id={tooltipId} + data-testid={testId} className="px-0.5" > {children} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx new file mode 100644 index 000000000..202d87972 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -0,0 +1,298 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import { useContext, useEffect, useMemo, useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useIdeMessengerRequest } from "../../../hooks"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { useAppSelector } from "../../../redux/hooks"; +import { + selectApplyStateByStreamId, + selectIsInEditMode, +} from "../../../redux/slices/sessionSlice"; +import { getFontSize } from "../../../util"; +import { isTerminalCodeBlock } from "../utils"; +import { ApplyActions } from "./ApplyActions"; +import { CopyButton } from "./CopyButton"; +import { CreateFileButton } from "./CreateFileButton"; +import { FileInfo } from "./FileInfo"; +import { GeneratingCodeLoader } from "./GeneratingCodeLoader"; +import { InsertButton } from "./InsertButton"; +import { RunInTerminalButton } from "./RunInTerminalButton"; + +const TopDiv = styled.div` + display: flex; + flex-direction: column; + outline: 1px solid ${vscCommandCenterInactiveBorder}; + outline-offset: -0.5px; + border-radius: ${defaultBorderRadius}; + margin-bottom: 8px !important; + margin-top: 8px !important; + background-color: ${vscEditorBackground}; + min-width: 0; +`; + +const ToolbarDiv = styled.div<{ isExpanded: boolean }>` + display: flex; + justify-content: space-between; + align-items: center; + font-size: ${getFontSize() - 2}px; + padding: 4px 6px; + margin: 0; + border-bottom: ${({ isExpanded }) => + isExpanded ? `1px solid ${vscCommandCenterInactiveBorder}` : "inherit"}; +`; + +export interface StepContainerPreToolbarProps { + codeBlockContent: string; + language: string | null; + relativeFilepath?: string; + isGeneratingCodeBlock: boolean; + codeBlockIndex: number; // To track which codeblock we are applying + codeBlockStreamId: string; + range?: string; + children: any; + expanded?: boolean; + disableManualApply?: boolean; +} + +export function StepContainerPreToolbar({ + codeBlockContent, + language, + relativeFilepath, + isGeneratingCodeBlock, + codeBlockIndex, + codeBlockStreamId, + range, + children, + expanded, + disableManualApply, +}: StepContainerPreToolbarProps) { + const ideMessenger = useContext(IdeMessengerContext); + const isInEditMode = useAppSelector(selectIsInEditMode); + const [isExpanded, setIsExpanded] = useState( + expanded ?? (isInEditMode ? false : true), + ); + + const [relativeFilepathUri, setRelativeFilepathUri] = useState( + null, + ); + + const fileExistsInput = useMemo( + () => (relativeFilepathUri ? { filepath: relativeFilepathUri } : null), + [relativeFilepathUri], + ); + + const { + result: fileExists, + refresh: refreshFileExists, + isLoading: isLoadingFileExists, + } = useIdeMessengerRequest("fileExists", fileExistsInput); + + const nextCodeBlockIndex = useAppSelector( + (state) => state.session.codeBlockApplyStates.curIndex, + ); + + const applyState = useAppSelector((state) => + selectApplyStateByStreamId(state, codeBlockStreamId), + ); + + /** + * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. + * However, if no `relativeFilepath` is defined, then this will + * be the URI of the currently open file at the time the user clicks "Apply". + */ + const [appliedFileUri, setAppliedFileUri] = useState( + undefined, + ); + + const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; + const hasFileExtension = + relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); + + // If we are creating a file, we already render that in the button + // so we don't want to dispaly it twice here + const displayFilepath = relativeFilepath ?? appliedFileUri; + + // TODO: This logic should be moved to a thunk + // Handle apply keyboard shortcut + useWebviewListener( + "applyCodeFromChat", + async () => onClickApply(), + [isNextCodeBlock, codeBlockContent], + !isNextCodeBlock, + ); + + useEffect(() => { + const getRelativeFilepathUri = async () => { + if (relativeFilepath) { + const resolvedUri = await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + setRelativeFilepathUri(resolvedUri); + } + }; + getRelativeFilepathUri(); + }, [relativeFilepath, ideMessenger.ide]); + + async function getFileUriToApplyTo() { + // If we've already resolved a file URI (from clicking apply), use that + if (appliedFileUri) { + return appliedFileUri; + } + + // If we have the `relativeFilepathUri`, use that + if (relativeFilepathUri) { + return relativeFilepathUri; + } + + // If no filepath was provided, get the current file + const currentFile = await ideMessenger.ide.getCurrentFile(); + if (currentFile) { + return currentFile.path; + } + + return undefined; + } + + async function onClickApply() { + const fileUri = await getFileUriToApplyTo(); + if (!fileUri) { + ideMessenger.ide.showToast( + "error", + "Could not resolve filepath to apply changes", + ); + return; + } + + // applyToFile will create the file if it doesn't exist + ideMessenger.post("applyToFile", { + streamId: codeBlockStreamId, + filepath: fileUri, + text: codeBlockContent, + }); + + setAppliedFileUri(fileUri); + refreshFileExists(); + } + + function onClickInsertAtCursor() { + ideMessenger.post("insertAtCursor", { text: codeBlockContent }); + } + + async function handleDiffAction(action: "accept" | "reject") { + const filepath = await getFileUriToApplyTo(); + if (!filepath) { + ideMessenger.ide.showToast( + "error", + `Could not resolve filepath to ${action} changes`, + ); + return; + } + + ideMessenger.post(`${action}Diff`, { + filepath, + streamId: codeBlockStreamId, + }); + + setAppliedFileUri(undefined); + } + + function onClickFilename() { + if (appliedFileUri) { + ideMessenger.post("showFile", { + filepath: appliedFileUri, + }); + } + + if (relativeFilepath) { + ideMessenger.post("showFile", { + filepath: relativeFilepath, + }); + } + } + + const renderActionButtons = () => { + if (isTerminalCodeBlock(language, codeBlockContent)) { + return ; + } + + if (isLoadingFileExists) { + return null; + } + + if (fileExists || !relativeFilepath) { + return ( + handleDiffAction("accept")} + onClickReject={() => handleDiffAction("reject")} + /> + ); + } + + return ; + }; + + // We wait until there is an extension in the filepath to avoid rendering + // an incomplete filepath + if (relativeFilepath && !hasFileExtension) { + return children; + } + + return ( + + +
+ setIsExpanded(!isExpanded)} + className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ + isExpanded ? "rotate-0" : "-rotate-90" + }`} + /> + {displayFilepath ? ( + + ) : ( + + {language} + + )} +
+ +
+ {isGeneratingCodeBlock ? ( + + ) : ( + <> +
+ + +
+ + {renderActionButtons()} + + )} +
+
+ + {isExpanded && ( +
{children}
+ )} +
+ ); +} diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx similarity index 100% rename from gui/src/components/markdown/SymbolLink.tsx rename to gui/src/components/StyledMarkdownPreview/SymbolLink.tsx diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx similarity index 100% rename from gui/src/components/markdown/SyntaxHighlightedPre.tsx rename to gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx similarity index 94% rename from gui/src/components/markdown/StyledMarkdownPreview.tsx rename to gui/src/components/StyledMarkdownPreview/index.tsx index 6af2f68d5..1cab75874 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -22,8 +22,7 @@ import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; -import StepContainerPreToolbar from "./StepContainerPreToolbar"; +import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import { isSymbolNotRif, matchCodeToSymbolOrFile } from "./utils"; @@ -301,6 +300,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const preChildProps = preProps?.children?.[0]?.props ?? {}; const { className, range } = preChildProps; + const relativeFilePath = preChildProps["data-relativefilepath"]; const codeBlockContent = preChildProps["data-codeblockcontent"]; @@ -310,22 +310,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - if (!relativeFilePath) { - return ( - - - - ); - } - const isGeneratingCodeBlock = preChildProps["data-islastcodeblock"] && isLastItemRef.current && - !isStreamingRef.current; + isStreamingRef.current; if (codeblockState.current[codeBlockIndex] === undefined) { codeblockState.current[codeBlockIndex] = { @@ -337,7 +325,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( isGeneratingCodeBlock; } - // We use a custom toolbar for codeblocks in the step container return ( { + const configError = useAppSelector((store) => store.config.configError); + + const navigate = useNavigate(); + + const hasFatalErrors = useMemo(() => { + return configError?.some((error) => error.fatal); + }, [configError]); + + const { setSelectedSection } = useLump(); + + const showLumpErrorSection = () => { + navigate(ROUTES.HOME); + setSelectedSection("error"); + }; + + if (!hasFatalErrors) { + return null; + } + return ( +
+ Error!{" "} + Could not load config +
Learn More
+
+ ); +}; diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 1cf0567ee..c49b47721 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -1,3 +1,4 @@ +import { XMarkIcon } from "@heroicons/react/24/outline"; import React, { isValidElement, useEffect } from "react"; import ReactMarkdown from "react-markdown"; import styled from "styled-components"; @@ -10,9 +11,6 @@ import { vscBackground, vscForeground, } from ".."; -import { useDispatch } from "react-redux"; -import { setShowDialog } from "../../redux/slices/uiSlice"; -import { XMarkIcon } from "@heroicons/react/24/outline"; interface TextDialogProps { showDialog: boolean; @@ -26,7 +24,8 @@ const ScreenCover = styled.div` width: 100%; height: 100%; background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa; - z-index: 1000; + z-index: 100000; + flex-direction: column; `; const DialogContainer = styled.div` @@ -34,23 +33,16 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); -`; - -const Dialog = styled.div` color: ${vscForeground}; background-color: ${vscBackground}; border-radius: ${defaultBorderRadius}; display: flex; flex-direction: column; border: 1px solid ${lightGray}; - margin: auto; word-wrap: break-word; - // overflow: hidden; `; const TextDialog = (props: TextDialogProps) => { - const dispatch = useDispatch(); - useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") { @@ -71,22 +63,20 @@ const TextDialog = (props: TextDialogProps) => { return ( ); diff --git a/gui/src/components/gui/Tooltip.tsx b/gui/src/components/gui/Tooltip.tsx index cf934f750..1eae5b77b 100644 --- a/gui/src/components/gui/Tooltip.tsx +++ b/gui/src/components/gui/Tooltip.tsx @@ -1,9 +1,10 @@ +import { CSSProperties } from "react"; import ReactDOM from "react-dom"; -import { Tooltip } from "react-tooltip"; +import { ITooltip, Tooltip } from "react-tooltip"; import { vscBackground, vscForeground, vscInputBorder } from ".."; import { fontSize } from "../../util"; -const TooltipStyles = { +const TooltipStyles: CSSProperties = { fontSize: fontSize(-2), backgroundColor: vscBackground, outline: `0.5px solid ${vscInputBorder}`, @@ -14,7 +15,7 @@ const TooltipStyles = { textAlign: "center", }; -export function ToolTip(props: any) { +export function ToolTip(props: ITooltip) { const combinedStyles = { ...TooltipStyles, ...props.style, diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index beeb37070..9d5a10bec 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -5,6 +5,7 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; +import { RangeInFile } from "core"; import { forwardRef, useContext, @@ -24,6 +25,8 @@ import { vscQuickInputBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -138,11 +141,29 @@ interface AtMentionDropdownProps { onClose: () => void; } +const formatFileSize = (fileSize: number) => { + const KB = 1000; + const MB = 1000_000; + const GB = 1000_000_000; + + if (fileSize > GB) { + return `${(fileSize / GB).toFixed(1)} GB`; + } else if (fileSize > MB) { + return `${(fileSize / MB).toFixed(1)} MB`; + } else if (fileSize > KB) { + return `${(fileSize / KB).toFixed(1)} KB`; + } + + return `${fileSize} byte${fileSize > 1 ? "s" : ""}`; +}; + const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); + const selectedModelTitle = useAppSelector(selectSelectedChatModel); + const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -157,6 +178,88 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const [allItems, setAllItems] = useState([]); + async function isItemTooBig( + name: string, + query: string, + ): Promise<[boolean, number]> { + const selectedCode: RangeInFile[] = []; + // Get context item from core + const contextResult = await ideMessenger.request( + "context/getContextItems", + { + name, + query, + fullInput: "", + selectedCode, + selectedModelTitle: selectedModelTitle?.title ?? "", + }, + ); + + if (contextResult.status === "error") { + return [false, -1]; + } + + const item = contextResult.content[0]; + + // Check if the context item exceeds the context length of the selected model + const result = await ideMessenger.request("isItemTooBig", { + item, + selectedModelTitle: selectedModelTitle?.title, + }); + + if (result.status === "error") { + return [false, -1]; + } + + const size = new Blob([item.content]).size; + + return [result.content, size]; + } + + function handleItemTooBig( + fileExceeds: boolean, + fileSize: number, + item: ComboBoxItem, + ) { + if (fileExceeds) { + props.editor + .chain() + .focus() + .command(({ tr, state }) => { + const text = state.doc.textBetween( + 0, + state.selection.from, + "\n", + "\n", + ); // Get the text before the cursor + const lastAtIndex = text.lastIndexOf("@"); + + if (lastAtIndex !== -1) { + // Delete text after the last "@" + tr.delete(lastAtIndex + 1, state.selection.from); + return true; + } + return false; + }) + .run(); + + // Trigger warning message + ideMessenger.ide.showToast( + "warning", + fileSize > 0 ? "File exceeds context length" : "Can't load the file", + { + modal: true, + detail: + fileSize > 0 + ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model` + : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, + }, + ); + } else { + props.command({ ...item, itemType: item.type }); + } + } + useEffect(() => { const items = [...props.items]; if (subMenuTitle === "Type to search docs") { @@ -243,7 +346,13 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { } if (item) { - props.command({ ...item, itemType: item.type }); + if (item.type === "file" && item.query) { + isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) => + handleItemTooBig(fileExceeds, fileSize, item), + ); + } else { + props.command({ ...item, itemType: item.type }); + } } }; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 20e40d9a9..08c5a910f 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -14,7 +14,7 @@ import { import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { selectHasCodeToEdit, selectIsInEditMode, @@ -92,7 +92,7 @@ interface InputToolbarProps { function InputToolbar(props: InputToolbarProps) { const dispatch = useAppDispatch(); const fileInputRef = useRef(null); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); @@ -148,6 +148,9 @@ function InputToolbar(props: InputToolbarProps) { for (const file of files) { props.onImageFileSelected?.(file); } + if (fileInputRef.current) { + fileInputRef.current.value = ""; + } }} /> @@ -158,7 +161,7 @@ function InputToolbar(props: InputToolbarProps) { fileInputRef.current?.click(); }} /> - + Attach an image @@ -171,7 +174,7 @@ function InputToolbar(props: InputToolbarProps) { className="h-3 w-3 hover:brightness-125" /> - + Add context (files, docs, urls, etc.) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 405182086..f7464e793 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -4,11 +4,13 @@ import { ChevronLeftIcon, CubeIcon, EllipsisHorizontalIcon, + ExclamationTriangleIcon, PencilIcon, Squares2X2Icon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; -import { vscBadgeBackground, vscBadgeForeground } from "../.."; +import { vscBadgeForeground } from "../.."; +import { useAppSelector } from "../../../redux/hooks"; import { fontSize } from "../../../util"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; @@ -36,9 +38,14 @@ const sections: Section[] = [ { id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon }, { id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon }, { id: "mcp", tooltip: "MCP", icon: Squares2X2Icon }, + { id: "error", tooltip: "Errors", icon: ExclamationTriangleIcon }, ]; -function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { +function BlockSettingsToolbarIcon( + props: BlockSettingsToolbarIcon & { sectionId?: string }, +) { + const isErrorSection = props.sectionId === "error"; + return (
store.config.configError); + const handleEllipsisClick = () => { if (isToolbarExpanded) { setSelectedSection(null); @@ -95,8 +109,14 @@ export function BlockSettingsTopToolbar() { toggleToolbar(); }; + const visibleSections = sections.filter( + (section) => + section.id !== "error" || + (section.id === "error" && configError && configError?.length > 0), + ); + return ( -
+
- {sections.map((section) => ( + {visibleSections.map((section) => (
-
+
diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx index 53cd82cfb..6cdcac4b0 100644 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -4,7 +4,10 @@ import { useContext } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -type SectionKey = Exclude; +type SectionKey = Exclude< + keyof ConfigYaml, + "name" | "version" | "schema" | "metadata" +>; interface EditBlockButtonProps { blockType: T; diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx index 92c5dbd6c..e2a7c17f8 100644 --- a/gui/src/components/mainInput/Lump/LumpContext.tsx +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -37,6 +37,8 @@ export function LumpProvider({ children }: LumpProviderProps) { const [isToolbarExpanded, setIsToolbarExpanded] = useState(true); const isStreaming = useAppSelector((state) => state.session.isStreaming); + const configError = useAppSelector((store) => store.config.configError); + // Handle keyboard escape const handleKeyDown = useCallback( (event: KeyboardEvent) => { @@ -71,6 +73,13 @@ export function LumpProvider({ children }: LumpProviderProps) { } }, [selectedSection]); + // Don't allow selection error section if there are no errors + useEffect(() => { + if (selectedSection === "error" && !configError) { + setSelectedSection(null); + } + }, [selectedSection, configError]); + // Reset when streaming starts useEffect(() => { if (isStreaming && selectedSection) { diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index de432f1d1..32222af65 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -4,7 +4,7 @@ import { vscCommandCenterInactiveBorder, vscInputBackground, } from "../.."; -import { LumpProvider, useLump } from "./LumpContext"; +import { useLump } from "./LumpContext"; import { LumpToolbar } from "./LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; @@ -29,21 +29,10 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>` overflow-y: auto; `; -/** - * Main component that displays the toolbar and selected content section - */ -export function Lump() { - return ( - - - - ); -} - /** * Internal component that consumes the LumpContext */ -function LumpContent() { +export function Lump() { const { isLumpVisible, selectedSection } = useLump(); return ( diff --git a/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx new file mode 100644 index 000000000..d4d01141c --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx @@ -0,0 +1,40 @@ +import { + ExclamationCircleIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../../../redux/hooks"; + +export function ErrorSection() { + const configError = useAppSelector((state) => state.config.configError); + + const sortedErrors = configError + ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) + : []; + + return ( +
+
    + {sortedErrors.map((error, index) => ( +
  • + {error.fatal ? ( + + ) : ( + + )} +

    + {error.fatal ? "Fatal Error:" : "Warning:"}{" "} + {error.message} +

    +
  • + ))} +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index 6885870df..a79d05a56 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -1,3 +1,4 @@ +import { BlockType } from "@continuedev/config-yaml"; import { ArrowTopRightOnSquareIcon, PlusIcon, @@ -7,12 +8,7 @@ import { GhostButton } from "../../.."; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch } from "../../../../redux/hooks"; -import { - setDialogMessage, - setShowDialog, -} from "../../../../redux/slices/uiSlice"; import { fontSize } from "../../../../util"; -import AddDocsDialog from "../../../dialogs/AddDocsDialog"; export function ExploreBlocksButton(props: { blockType: string }) { const { selectedProfile } = useAuth(); @@ -30,16 +26,19 @@ export function ExploreBlocksButton(props: { blockType: string }) { const handleClick = () => { if (isLocal) { - switch (props.blockType) { - case "docs": - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - break; - default: - ideMessenger.request("config/openProfile", { - profileId: selectedProfile.id, - }); - } + ideMessenger.request("config/addLocalWorkspaceBlock", { + blockType: props.blockType as BlockType, + }); + // switch (props.blockType) { + // case "docs": + // dispatch(setShowDialog(true)); + // dispatch(setDialogMessage()); + // break; + // default: + // ideMessenger.request("config/openProfile", { + // profileId: selectedProfile.id, + // }); + // } } else { ideMessenger.request("controlPlane/openUrl", { path: `new?type=block&blockType=${props.blockType}`, @@ -60,7 +59,7 @@ export function ExploreBlocksButton(props: { blockType: string }) { }} >
- + {text}
diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx index 05e9352f0..b128db0a2 100644 --- a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -1,54 +1,31 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ModelDescription } from "core"; -import { useContext } from "react"; import { useAuth } from "../../../../context/Auth"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, - updateConfig, -} from "../../../../redux/slices/configSlice"; +import { updateSelectedModelByRole } from "../../../../redux/thunks"; import { isJetBrains } from "../../../../util"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; export function ModelsSection() { const { selectedProfile } = useAuth(); const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); const jetbrains = isJetBrains(); - const selectedChatModel = useAppSelector(selectDefaultModel); function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { - if (!selectedProfile) { - return; - } - // Optimistic update - dispatch( - updateConfig({ - ...config, - selectedModelByRole: { - ...config.selectedModelByRole, - [role]: model, - }, - }), - ); - ideMessenger.post("config/updateSelectedModel", { - profileId: selectedProfile.id, - role, - title: model?.title ?? null, - }); - } - - // TODO use handleRoleUpdate for chat - function handleChatModelSelection(model: ModelDescription | null) { if (!model) { return; } - dispatch(setDefaultModel({ title: model.title })); + + dispatch( + updateSelectedModelByRole({ + role, + selectedProfile, + modelTitle: model.title, + }), + ); } return ( @@ -58,16 +35,8 @@ export function ModelsSection() { displayName="Chat" description="Used in the chat interface" models={config.modelsByRole.chat} - selectedModel={ - selectedChatModel - ? { - title: selectedChatModel.title, - provider: selectedChatModel.provider, - model: selectedChatModel.model, - } - : null - } - onSelect={(model) => handleChatModelSelection(model)} + selectedModel={config.selectedModelByRole.chat} + onSelect={(model) => handleRoleUpdate("chat", model)} /> void; - title: string; + rule: RuleWithSource; } -const RuleCard: React.FC = ({ index, rule, onClick, title }) => { +const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const handleOpen = async () => { + if (rule.slug) { + ideMessenger.request("controlPlane/openUrl", { + path: `${rule.slug}/new-version`, + orgSlug: undefined, + }); + } else if (rule.ruleFile) { + ideMessenger.post("openFile", { + path: rule.ruleFile, + }); + } else if (rule.source === "default") { + ideMessenger.post("openUrl", DEFAULT_CHAT_SYSTEM_MESSAGE_URL); + } else { + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + } + }; + + const title = useMemo(() => { + if (rule.name) { + return rule.name; + } else { + if (rule.source === ".continuerules") { + return "Project rules"; + } else if (rule.source === "default") { + return "Default chat system message"; + } else if (rule.source === "json-systemMessage") { + return "JSON systemMessage)"; + } else if (rule.source === "model-chat-options") { + return "Base System Chat Message"; + } else { + return "Assistant rule"; + } + } + }, [rule]); function onClickExpand() { dispatch(setShowDialog(true)); dispatch( setDialogMessage( -
+

{title}

-
-            {/** TODO: Render the rule in a more readable way */}
-            {JSON.stringify(rule)}
-          
+
{rule.rule}
, ), ); } - const renderRuleContent = () => { - if (typeof rule === "string") { - return
{rule}
; - } - - if (rule.rule) { - return ( -
-
{rule.rule}
- {rule.if &&
if: {rule.if}
} -
- ); - } - - return
{JSON.stringify(rule)}
; - }; - + const smallFont = useFontSize(-2); + const tinyFont = useFontSize(-3); return (
-
-
-
-
- {title} -
-
- {renderRuleContent()} -
-
-
+
+
+ + {title} + +
{" "} - - - + {rule.source === "default" ? ( + + + + ) : ( + + + + )}
+ + + {rule.rule} + + {rule.if ? ( +
+ Applies if + + {rule.if.replace(/\${{|}}/g, "")} + +
+ ) : null}
); }; export function RulesSection() { - const ideMessenger = useContext(IdeMessengerContext); const { selectedProfile } = useAuth(); - const { hideLump } = useLump(); - const rules = useSelector( - (state: RootState) => state.config.config.rules ?? [], - ); + const config = useAppSelector((store) => store.config.config); + const mode = useAppSelector((store) => store.session.mode); + const sortedRules: RuleWithSource[] = useMemo(() => { + const rules = [...config.rules.map((rule) => ({ ...rule }))]; - const mergedRules = useMemo(() => { - const parsed = selectedProfile?.rawYaml - ? parseConfigYaml(selectedProfile?.rawYaml ?? "") - : undefined; - return rules.map((rule, index) => ({ - unrolledRule: rule, - ruleFromYaml: parsed?.rules?.[index], - })); - }, [rules]); + // Use profile rawYaml to infer slugs + if (selectedProfile?.rawYaml) { + try { + const parsed = parseConfigYaml(selectedProfile.rawYaml); + const parsedRules = parsed?.rules ?? []; + let index = 0; + for (const rule of rules) { + if (rule.source === "rules-block") { + let slug: string | undefined = undefined; + const yamlRule = parsedRules[index]; + if (yamlRule) { + if (typeof yamlRule !== "string" && "uses" in yamlRule) { + slug = yamlRule.uses; + } else { + slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; + } + } + if (slug) { + rule.slug = slug; + } - const openUrl = (path: string) => { - ideMessenger.request("controlPlane/openUrl", { - path, - orgSlug: undefined, - }); - hideLump(); - }; + index++; + } + } + } catch (e) { + console.error( + "Rules notch section: failed to parse selected profile", + e, + ); + } + } + // Add a displayed rule for the base system chat message when in chat mode + if (mode === "chat") { + const baseMessage = + config.selectedModelByRole.chat?.baseChatSystemMessage; + if (baseMessage) { + rules.unshift({ + rule: baseMessage, + source: "model-chat-options", + }); + } else { + rules.unshift({ + rule: DEFAULT_CHAT_SYSTEM_MESSAGE, + source: "default", + }); + } + } + + return rules; + }, [config, selectedProfile, mode]); return ( -
-
- {mergedRules.map((rule, index) => { - if (!rule.ruleFromYaml) { - return ( - { - ideMessenger.post("config/openProfile", { - profileId: undefined, - }); - hideLump(); - }} - title="Locally Defined Rule" - /> - ); - } - - if (typeof rule.ruleFromYaml === "string") { - const slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; - - return ( - openUrl(`${slug}/new-version`)} - title="Inline Rule" - /> - ); - } - - if ("uses" in rule.ruleFromYaml) { - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); - } - - // TODO: Handle rules as object with 'if' - return null; - })} -
+
+ {sortedRules.map((rule, index) => ( + + ))}
); diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 0465e1f74..85f72078f 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,6 +1,7 @@ import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; import DocsSection from "./docs/DocsSection"; +import { ErrorSection } from "./ErrorSection"; import { MCPSection } from "./MCPSection"; import { ModelsSection } from "./ModelsSection"; import { PromptsSection } from "./PromptsSection"; @@ -28,6 +29,8 @@ export function SelectedSection() { return ; case "mcp": return ; + case "error": + return ; default: return null; } diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 3e52cfe8f..f5d172dc2 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; @@ -46,7 +46,7 @@ export function TipTapEditor(props: TipTapEditorProps) { const isOSREnabled = useIsOSREnabled(); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const isInEditMode = useAppSelector(selectIsInEditMode); const historyLength = useAppSelector((store) => store.session.history.length); diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index 16e959ebb..b7f3d724c 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -122,25 +122,22 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { const [hidden, setHidden] = useState(calculatedInitiallyHidden); const [isExpanded, setIsExpanded] = useState(false); - // Track if user has manually toggled visibility - const [userToggled, setUserToggled] = useState(false); - const contentRef = useRef(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); useEffect(() => { - // Only update hidden state from props if user hasn't manually toggled - // or if initiallyHidden isn't explicitly set to false - if (!userToggled || props.initiallyHidden !== false) { + // Only update hidden state from props if initiallyHidden isn't explicitly set to false + if (props.initiallyHidden !== false) { setHidden(calculatedInitiallyHidden); } - }, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]); + }, [calculatedInitiallyHidden, props.initiallyHidden]); + useEffect(() => { const resizeObserver = new ResizeObserver(() => { - setContentDims({ - width: contentRef.current?.scrollWidth ?? 0, - height: contentRef.current?.scrollHeight ?? 0, - }); + setContentDims(prevValue => ({ + width: contentRef.current?.scrollWidth ?? prevValue.width, + height: contentRef.current?.scrollHeight ?? prevValue.height, + })); }); if (contentRef.current) { @@ -166,7 +163,6 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { fontSize: getFontSize() - 3, }} onClick={() => { - setUserToggled(true); setHidden(!hidden); }} > diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx index c414d7f1c..8055e7fa9 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -6,7 +6,7 @@ import { useContext, useMemo } from "react"; import { vscBadgeBackground } from "../../../.."; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import FileIcon from "../../../../FileIcon"; -import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../../StyledMarkdownPreview"; import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; import { NodeViewWrapper } from "../../components/NodeViewWrapper"; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 6e7808ba7..400f08019 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -123,8 +123,6 @@ export function useMainEditorWebviewListeners({ } } - debugger; - editor .chain() .insertContentAt(index, { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index e50769ac8..9c56819e3 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -21,7 +21,7 @@ import { useInputHistory } from "../../../../hooks/useInputHistory"; import useUpdatingRef from "../../../../hooks/useUpdatingRef"; import { useAppSelector } from "../../../../redux/hooks"; import { selectUseActiveFile } from "../../../../redux/selectors"; -import { selectDefaultModel } from "../../../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { addCodeToEdit, selectHasCodeToEdit, @@ -83,7 +83,7 @@ export function createEditorConfig(options: { const posthog = usePostHog(); const { getSubmenuContextItems } = useSubmenuContextProviders(); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const useActiveFile = useAppSelector(selectUseActiveFile); const historyLength = useAppSelector((store) => store.session.history.length); diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index eb63e0ee9..bb153f62a 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -42,7 +42,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const isRangeInFile = name.includes(" (") && name.endsWith(")"); if (isRangeInFile) { - const rif = ctxItemToRifWithContents(contextItem); + const rif = ctxItemToRifWithContents(contextItem, true); ideMessenger.ide.showLines( rif.filepath, rif.range.start.line, diff --git a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index a89ba2e6a..40e3c8d2b 100644 --- a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscBackground } from "../.."; import { getFontSize } from "../../../util"; -import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../StyledMarkdownPreview"; const SpoilerButton = styled.div` background-color: ${vscBackground}; diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx deleted file mode 100644 index 85ece0990..000000000 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { - ArrowLeftEndOnRectangleIcon, - CommandLineIcon, - PlayIcon, -} from "@heroicons/react/24/outline"; -import { useContext, useRef, useState } from "react"; -import { v4 as uuidv4 } from "uuid"; -import { - defaultBorderRadius, - vscCommandCenterInactiveBorder, - vscEditorBackground, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - selectUIConfig, -} from "../../redux/slices/configSlice"; -import { isJetBrains } from "../../util"; -import { CopyIconButton } from "../gui/CopyIconButton"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { getTerminalCommand, isTerminalCodeBlock } from "./utils"; - -interface StepContainerPreActionButtonsProps { - language: string | null; - codeBlockContent: string; - codeBlockIndex: number; - children: any; -} - -export default function StepContainerPreActionButtons({ - language, - codeBlockContent, - codeBlockIndex, - children, -}: StepContainerPreActionButtonsProps) { - const [hovering, setHovering] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const uiConfig = useAppSelector(selectUIConfig); - const streamIdRef = useRef(null); - const nextCodeBlockIndex = useAppSelector( - (state) => state.session.codeBlockApplyStates.curIndex, - ); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isBottomToolbarPosition = - uiConfig?.codeBlockToolbarPosition == "bottom"; - - const toolTipPlacement = isBottomToolbarPosition ? "top" : "bottom"; - - const shouldRunTerminalCmd = - !isJetBrains() && isTerminalCodeBlock(language, codeBlockContent); - const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; - - if (streamIdRef.current === null) { - streamIdRef.current = uuidv4(); - } - - const defaultModel = useAppSelector(selectDefaultModel); - - function onClickApply() { - if (!defaultModel || !streamIdRef.current) { - return; - } - ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, - text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, - }); - } - - async function onClickRunTerminal(): Promise { - if (shouldRunTerminalCmd) { - return ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent)); - } - } - - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - - return ( -
setHovering(true)} - onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background relative my-2.5" - style={{ - border: `1px solid ${vscCommandCenterInactiveBorder}`, - borderRadius: defaultBorderRadius, - }} - > -
{children}
- {hovering && !isStreaming && ( -
- {shouldRunTerminalCmd && ( - - - - )} - - - - - ideMessenger.post("insertAtCursor", { text: codeBlockContent }) - } - tooltipPlacement={toolTipPlacement} - > - - - -
- )} -
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx deleted file mode 100644 index 195615380..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; -import useCopy from "../../../hooks/useCopy"; -import { lightGray, vscForeground } from "../.."; - -interface CopyButtonProps { - text: string; -} - -export default function CopyButton({ text }: CopyButtonProps) { - const { copyText, copied } = useCopy(text); - - return ( -
-
- {copied ? ( - <> - - Copied - - ) : ( - <> - - Copy - - )} -
-
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx deleted file mode 100644 index ee46ccee8..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { getLastNPathParts } from "core/util/uri"; -import { useContext } from "react"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import FileIcon from "../../FileIcon"; - -export interface FileInfoProps { - relativeFilepath: string; - range?: string; -} - -const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { - const ideMessenger = useContext(IdeMessengerContext); - - async function onClickFileName() { - const fileUri = await inferResolvedUriFromRelativePath( - relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("showFile", { - filepath: fileUri, - }); - } - - return ( -
-
- -
- - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} - -
- ); -}; - -export default FileInfo; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx deleted file mode 100644 index 35bc54349..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { CommandLineIcon } from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { lightGray, vscForeground } from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; - -interface RunInTerminalButtonProps { - command: string; -} - -export default function RunInTerminalButton({ - command, -}: RunInTerminalButtonProps) { - const ideMessenger = useContext(IdeMessengerContext); - - function runInTerminal() { - void ideMessenger.post("runCommand", { command }); - } - - return ( -
-
- <> - - Run - -
-
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx deleted file mode 100644 index f09ed1a9f..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ /dev/null @@ -1,224 +0,0 @@ -import { ChevronDownIcon } from "@heroicons/react/24/outline"; -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { debounce } from "lodash"; -import { useContext, useEffect, useRef, useState } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - vscCommandCenterInactiveBorder, - vscEditorBackground, -} from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { useAppSelector } from "../../../redux/hooks"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; -import { - selectApplyStateByStreamId, - selectIsInEditMode, -} from "../../../redux/slices/sessionSlice"; -import { getFontSize } from "../../../util"; -import { childrenToText, isTerminalCodeBlock } from "../utils"; -import ApplyActions from "./ApplyActions"; -import CopyButton from "./CopyButton"; -import FileInfo from "./FileInfo"; -import GeneratingCodeLoader from "./GeneratingCodeLoader"; -import RunInTerminalButton from "./RunInTerminalButton"; - -const TopDiv = styled.div` - display: flex; - flex-direction: column; - outline: 1px solid ${vscCommandCenterInactiveBorder}; - outline-offset: -0.5px; - border-radius: ${defaultBorderRadius}; - margin-bottom: 8px !important; - background-color: ${vscEditorBackground}; - min-width: 0; -`; - -const ToolbarDiv = styled.div<{ isExpanded: boolean }>` - display: flex; - justify-content: space-between; - align-items: center; - font-size: ${getFontSize() - 2}px; - padding: 4px 6px; - margin: 0; - border-bottom: ${({ isExpanded }) => - isExpanded ? `1px solid ${vscCommandCenterInactiveBorder}` : "inherit"}; -`; - -export interface StepContainerPreToolbarProps { - codeBlockContent: string; - language: string | null; - relativeFilepath: string; - isGeneratingCodeBlock: boolean; - codeBlockIndex: number; // To track which codeblock we are applying - codeBlockStreamId: string; - range?: string; - children: any; - expanded?: boolean; - disableManualApply?: boolean; -} - -export default function StepContainerPreToolbar( - props: StepContainerPreToolbarProps, -) { - const ideMessenger = useContext(IdeMessengerContext); - const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); - const isInEditMode = useAppSelector(selectIsInEditMode); - const [isExpanded, setIsExpanded] = useState( - props.expanded ?? (isInEditMode ? false : true), - ); - const [codeBlockContent, setCodeBlockContent] = useState(""); - - const nextCodeBlockIndex = useAppSelector( - (state) => state.session.codeBlockApplyStates.curIndex, - ); - - const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, props.codeBlockStreamId), - ); - - const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; - const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); - - const defaultModel = useAppSelector(selectDefaultModel); - - async function onClickApply() { - if (!defaultModel) { - return; - } - - let fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - - ideMessenger.post("applyToFile", { - streamId: props.codeBlockStreamId, - filepath: fileUri, - text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, - }); - } - - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - - useEffect(() => { - if (codeBlockContent === "") { - setCodeBlockContent(childrenToText(props.children.props.children)); - } else { - const debouncedEffect = debounce(() => { - setCodeBlockContent(childrenToText(props.children.props.children)); - }, 100); - - debouncedEffect(); - - return () => { - debouncedEffect.cancel(); - }; - } - }, [props.children, codeBlockContent]); - - // useEffect(() => { - // const hasCompletedGenerating = - // wasGeneratingRef.current && !isGeneratingCodeBlock; - - // wasGeneratingRef.current = isGeneratingCodeBlock; - // if (hasCompletedGenerating) { - // if (props.autoApply) { - // onClickApply(); - // } - // } - // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); - - async function onClickAcceptApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("acceptDiff", { - filepath: fileUri, - streamId: props.codeBlockStreamId, - }); - } - - async function onClickRejectApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("rejectDiff", { - filepath: fileUri, - streamId: props.codeBlockStreamId, - }); - } - - function onClickExpand() { - setIsExpanded(!isExpanded); - } - - // We want until there is an extension in the filepath to avoid rendering - // an incomplete filepath - if (!hasFileExtension) { - return props.children; - } - - return ( - - -
- - -
- -
- {props.isGeneratingCodeBlock ? ( - - ) : ( - <> - - {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - )} - - )} -
-
- - {isExpanded && ( -
- {props.children} -
- )} -
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/index.ts b/gui/src/components/markdown/StepContainerPreToolbar/index.ts deleted file mode 100644 index 6e974689a..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./StepContainerPreToolbar"; diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx index 0e14adfad..92395f545 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -12,7 +12,7 @@ import { useEffect, useMemo } from "react"; import styled from "styled-components"; import { lightGray } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { cycleMode, selectCurrentMode, @@ -40,7 +40,7 @@ const ShortcutText = styled.span` function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector(selectCurrentMode); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); const jetbrains = useMemo(() => { diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 4c2e31387..8191af54b 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -6,18 +6,15 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray } from ".."; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; -import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, -} from "../../redux/slices/configSlice"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; @@ -122,9 +119,11 @@ function ModelOption({ } function ModelSelect() { - const dispatch = useDispatch(); - const defaultModel = useAppSelector(selectDefaultModel); - const allModels = useAppSelector((state) => state.config.config.models); + const dispatch = useAppDispatch(); + const selectedChatModel = useAppSelector(selectSelectedChatModel); + const allChatModels = useAppSelector( + (state) => state.config.config.modelsByRole.chat, + ); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -142,7 +141,7 @@ function ModelSelect() { useEffect(() => { setOptions( - allModels + allChatModels .filter((m) => !m.roles || m.roles.includes("chat")) .map((model) => { return { @@ -152,19 +151,30 @@ function ModelSelect() { }; }), ); - }, [allModels]); + }, [allChatModels]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { + if (!selectedProfile) { + return; + } + const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === defaultModel?.title, + (option) => option.value === selectedChatModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; const newModelTitle = options[nextIndex].value; - dispatch(setDefaultModel({ title: newModelTitle })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: newModelTitle, + }), + ); } }; @@ -172,7 +182,7 @@ function ModelSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [options, defaultModel]); + }, [options, selectedChatModel]); function onClickAddModel(e: MouseEvent) { e.stopPropagation(); @@ -195,11 +205,16 @@ function ModelSelect() { } return ( - // Hiad sfasdfasdf asdfasdf { - if (val === defaultModel?.title) return; - dispatch(setDefaultModel({ title: val })); + if (val === selectedChatModel?.title) return; + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: val, + }), + ); }} >
@@ -208,8 +223,8 @@ function ModelSelect() { ref={buttonRef} className="h-[18px] gap-1 border-none text-gray-400" > - - {modelSelectTitle(defaultModel) || "Select model"} + + {modelSelectTitle(selectedChatModel) || "Select model"} ))}
diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index e0d88dc12..f58a4194a 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,5 +1,5 @@ import { - ArrowPathRoundedSquareIcon, + ArrowPathIcon, ArrowTopRightOnSquareIcon, BuildingOfficeIcon, ChevronDownIcon, @@ -53,6 +53,7 @@ const AssistantSelectOption = ({ const tinyFont = useFontSize(-4); const navigate = useNavigate(); + const { setSelectedSection } = useLump(); const hasFatalErrors = useMemo(() => { return !!profile.errors?.find((error) => error.fatal); @@ -78,7 +79,8 @@ const AssistantSelectOption = ({ function handleClickError() { if (profile.id === "local") { - navigate(ROUTES.CONFIG_ERROR); + navigate(ROUTES.HOME); + setSelectedSection("error"); } else { ideMessenger.post("config/openProfile", { profileId: profile.id }); } @@ -99,10 +101,10 @@ const AssistantSelectOption = ({ fontSize: tinyFont, }} > -
-
+
+
- +
Create your first assistant @@ -278,7 +280,7 @@ export default function AssistantSelect() {
{selectedProfile.title} @@ -291,6 +293,20 @@ export default function AssistantSelect() { +
+ Assistants +
{ + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); + }} + > + +
+
+
@@ -314,8 +330,9 @@ export default function AssistantSelect() { }} /> -
+
login(false)} @@ -330,24 +347,6 @@ export default function AssistantSelect() { New Assistant
-
{ - e.stopPropagation(); - refreshProfiles(); - buttonRef.current?.click(); - }} - > - - - Refresh - -
) : ( diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 329a1ee38..831df7f6a 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -29,7 +29,6 @@ interface AuthContextType { selectedProfile: ProfileDescription | null; profiles: ProfileDescription[] | null; refreshProfiles: () => void; - controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; } @@ -86,6 +85,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ setOrganizations(orgs.filter((org) => org.id === "personal")), ); dispatch(setSelectedOrgId("personal")); + setSession(undefined); }} onCancel={() => { dispatch(setDialogMessage(undefined)); @@ -110,25 +110,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }, []); useWebviewListener( - "didChangeControlPlaneSessionInfo", + "sessionUpdate", async (data) => { setSession(data.sessionInfo); }, [], ); - const [controlServerBetaEnabled, setControlServerBetaEnabled] = - useState(false); - - // Hacky, remove once continue for teams is deprecated - useWebviewListener( - "configUpdate", - async (msg) => { - setControlServerBetaEnabled(msg.usingContinueForTeams); - }, - [], - ); - const refreshProfiles = useCallback(async () => { try { await ideMessenger.request("config/refreshProfiles", undefined); @@ -149,7 +137,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ profiles: currentOrg?.profiles ?? [], refreshProfiles, organizations: orgs, - controlServerBetaEnabled, }} > {children} diff --git a/gui/src/forms/AddModelForm.tsx b/gui/src/forms/AddModelForm.tsx index e96349f1b..94a26adbc 100644 --- a/gui/src/forms/AddModelForm.tsx +++ b/gui/src/forms/AddModelForm.tsx @@ -1,20 +1,21 @@ import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; import { FormProvider, useForm } from "react-hook-form"; -import { useDispatch } from "react-redux"; import { Button, Input, InputSubtext, StyledActionButton } from "../components"; import AddModelButtonSubtext from "../components/AddModelButtonSubtext"; import Alert from "../components/gui/Alert"; import ModelSelectionListbox from "../components/modelSelection/ModelSelectionListbox"; +import { useAuth } from "../context/Auth"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs"; +import { DisplayInfo } from "../pages/AddNewModel/configs/models"; import { ProviderInfo, providers, } from "../pages/AddNewModel/configs/providers"; +import { useAppDispatch } from "../redux/hooks"; +import { updateSelectedModelByRole } from "../redux/thunks"; import { FREE_TRIAL_LIMIT_REQUESTS, hasPassedFTL } from "../util/freeTrial"; -import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs"; -import { setDefaultModel } from "../redux/slices/configSlice"; -import { DisplayInfo } from "../pages/AddNewModel/configs/models"; interface QuickModelSetupProps { onDone: () => void; @@ -33,13 +34,14 @@ function AddModelForm({ const [selectedProvider, setSelectedProvider] = useState( providers["openai"]!, ); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const [selectedModel, setSelectedModel] = useState( selectedProvider.packages[0], ); const formMethods = useForm(); - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const popularProviderTitles = [ @@ -115,7 +117,13 @@ function AddModelForm({ profileId: "local", }); - dispatch(setDefaultModel({ title: model.title, force: true })); + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: model.title, + }), + ); onDone(); } diff --git a/gui/src/hooks/index.ts b/gui/src/hooks/index.ts new file mode 100644 index 000000000..8688c91e5 --- /dev/null +++ b/gui/src/hooks/index.ts @@ -0,0 +1 @@ +export * from "./useIdeMessengerRequest"; diff --git a/gui/src/hooks/useIdeMessengerRequest.ts b/gui/src/hooks/useIdeMessengerRequest.ts new file mode 100644 index 000000000..f03a17571 --- /dev/null +++ b/gui/src/hooks/useIdeMessengerRequest.ts @@ -0,0 +1,44 @@ +import type { FromWebviewProtocol } from "core/protocol"; +import type { SuccessWebviewSingleMessage } from "core/protocol/util"; +import { useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; + +/** + * Generic hook for making IDE messenger requests with automatic error handling and refresh capability + */ +export function useIdeMessengerRequest( + messageType: T, + data: FromWebviewProtocol[T][0] | null, +) { + const ideMessenger = useContext(IdeMessengerContext); + const [result, setResult] = useState< + SuccessWebviewSingleMessage["content"] | null + >(null); + const [isLoading, setIsLoading] = useState(false); + + async function makeRequest() { + if (!data) { + setResult(null); + return; + } + + setIsLoading(true); + try { + const response = await ideMessenger.request(messageType, data); + if (response.status === "success") { + setResult(response.content); + } else { + console.error(`Error in ${messageType} request:`, response.error); + setResult(null); + } + } finally { + setIsLoading(false); + } + } + + useEffect(() => { + makeRequest(); + }, [data, messageType]); + + return { result, isLoading, refresh: makeRequest }; +} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5b3e665ad..e9d9223a8 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,7 +11,7 @@ import { } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { - selectDefaultModel, + selectSelectedChatModel, setConfigResult, } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; @@ -35,7 +35,7 @@ function useSetup() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const selectedProfileId = useAppSelector( (store) => store.profiles.selectedProfileId, ); @@ -50,6 +50,7 @@ function useSetup() { organizations, selectedOrgId, } = result; + if (isInitial && hasDoneInitialConfigLoad.current) { return; } @@ -253,26 +254,12 @@ function useSetup() { dispatch(updateIndexingStatus(data)); }); - useWebviewListener( - "getDefaultModelTitle", - async () => { - return defaultModel?.title; - }, - [defaultModel], - ); - const activeToolStreamId = useAppSelector( (store) => store.session.activeToolStreamId, ); useWebviewListener( "updateApplyState", async (state) => { - // dispatch( - // updateCurCheckpoint({ - // filepath: state.filepath, - // content: state.fileContent, - // }), - // ); dispatch(updateApplyState(state)); if ( activeToolStreamId && diff --git a/gui/src/pages/config-error/index.tsx b/gui/src/pages/config-error/index.tsx deleted file mode 100644 index 7bd3a3050..000000000 --- a/gui/src/pages/config-error/index.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { - ArrowLeftIcon, - ExclamationCircleIcon, - ExclamationTriangleIcon, -} from "@heroicons/react/24/outline"; -import { useNavigate } from "react-router-dom"; -import { vscBackground } from "../../components"; -import { useAppSelector } from "../../redux/hooks"; -import { ROUTES } from "../../util/navigation"; - -export default function ConfigErrorPage() { - const navigate = useNavigate(); - const configError = useAppSelector((state) => state.config.configError); - - const sortedErrors = configError - ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) - : []; - - return ( -
-
navigate(ROUTES.HOME)} - className="sticky top-0 m-0 flex cursor-pointer items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" - style={{ - backgroundColor: vscBackground, - }} - > - - Chat -
- -
-
-

Config Errors

-

- Please resolve the following errors in your assistant configuration. -

-
- {sortedErrors.length > 0 ? ( -
    - {sortedErrors.map((error, index) => ( -
  • - {error.fatal ? ( - - ) : ( - - )} -

    - - {error.fatal ? "Fatal Error:" : "Warning:"} - {" "} - {error.message} -

    -
  • - ))} -
- ) : ( -

- No configuration errors found. -

- )} -
-
-
-
- ); -} diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 5c3d2e44f..b293de719 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,6 +1,5 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; -import { useState } from "react"; import { SecondaryButton } from "../../components"; import { Popover, @@ -14,7 +13,6 @@ import { useAppSelector } from "../../redux/hooks"; import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { - const [open, setOpen] = useState(false); const { session, logout, login, organizations } = useAuth(); const selectedOrg = useAppSelector(selectCurrentOrg); diff --git a/gui/src/pages/config/KeyboardShortcuts.tsx b/gui/src/pages/config/KeyboardShortcuts.tsx index 4ac0919c5..4456bf45c 100644 --- a/gui/src/pages/config/KeyboardShortcuts.tsx +++ b/gui/src/pages/config/KeyboardShortcuts.tsx @@ -1,192 +1,130 @@ import { useMemo } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscForeground, -} from "../../components"; -import { ToolTip } from "../../components/gui/Tooltip"; -import { getPlatform, isJetBrains } from "../../util"; - -const StyledKeyDiv = styled.div` - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 2px; - color: ${vscForeground}; - - width: 16px; - height: 16px; - - display: flex; - justify-content: center; - align-items: center; -`; - -const keyToName: { [key: string]: string } = { - "⌘": "Cmd", - "⌃": "Ctrl", - "⇧": "Shift", - "⏎": "Enter", - "⌫": "Backspace", - "⌥": "Option", - "⎇": "Alt", -}; - -function KeyDiv({ text }: { text: string }) { - return ( - <> - - {text} - - - - {keyToName[text]} - - - ); -} +import Shortcut from "../../components/gui/Shortcut"; +import { isJetBrains } from "../../util"; interface KeyboardShortcutProps { - mac: string; - windows: string; + shortcut: string; description: string; + isEven: boolean; } function KeyboardShortcut(props: KeyboardShortcutProps) { - const shortcut = getPlatform() === "mac" ? props.mac : props.windows; return ( -
- {props.description}: -
- {shortcut.split(" ").map((key, i) => { - return ; - })} +
+
+ {props.description}: +
+
+ {props.shortcut}
); } -const vscodeShortcuts: KeyboardShortcutProps[] = [ +// Shortcut strings will be rendered correctly based on the platform by the Shortcut component +const vscodeShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ L", - windows: "⌃ L", + shortcut: "cmd L", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ L", - windows: "⌃ ⇧ L", + shortcut: "cmd shift L", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ R", - windows: "⌃ ⇧ R", + shortcut: "cmd shift R", description: "Debug Terminal", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⌘ N", - windows: "Alt ⌃ N", + shortcut: "alt cmd N", description: "Reject Top Change in Diff", }, { - mac: "⌥ ⌘ Y", - windows: "Alt ⌃ Y", + shortcut: "alt cmd Y", description: "Accept Top Change in Diff", }, { - mac: "⌘ K ⌘ A", - windows: "⌃ K ⌃ A", + shortcut: "cmd K cmd A", description: "Toggle Autocomplete Enabled", }, { - mac: "⌘ K ⌘ M", - windows: "⌃ K ⌃ M", + shortcut: "cmd K cmd M", description: "Toggle Full Screen", }, ]; -const jetbrainsShortcuts: KeyboardShortcutProps[] = [ +const jetbrainsShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ J", - windows: "⌃ J", + shortcut: "cmd J", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ J", - windows: "⌃ ⇧ J", + shortcut: "cmd shift J", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⇧ J", - windows: "Alt ⇧ J", + shortcut: "alt shift J", description: "Quick Input", }, { - mac: "⌥ ⌘ J", - windows: "Alt ⌃ J", + shortcut: "alt cmd J", description: "Toggle Sidebar", }, ]; @@ -197,16 +135,16 @@ function KeyboardShortcuts() { }, []); return ( -
-

Keyboard shortcuts

-
+
+

Keyboard shortcuts

+
{shortcuts.map((shortcut, i) => { return ( ); })} @@ -216,3 +154,4 @@ function KeyboardShortcuts() { } export default KeyboardShortcuts; + diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index cdc0d16d1..e3464a6f2 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -1,5 +1,12 @@ -import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline"; -import { type ModelDescription } from "core"; +import { + CheckIcon, + ChevronUpDownIcon, + Cog6ToothIcon, + CubeIcon, +} from "@heroicons/react/24/outline"; +import { ModelDescription } from "core"; +import { LLMConfigurationStatuses } from "core/llm/constants"; +import { MouseEvent, useContext, useState } from "react"; import { defaultBorderRadius } from "../../components"; import { ToolTip } from "../../components/gui/Tooltip"; import InfoHover from "../../components/InfoHover"; @@ -10,6 +17,7 @@ import { ListboxOptions, Transition, } from "../../components/ui"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { fontSize } from "../../util"; interface ModelRoleSelectorProps { @@ -27,10 +35,33 @@ const ModelRoleSelector = ({ displayName, description, }: ModelRoleSelectorProps) => { + const ideMessenger = useContext(IdeMessengerContext); + const [hoveredIdx, setHoveredIdx] = useState(null); + + const noConfiguredModels = models.every( + (model) => model.configurationStatus !== LLMConfigurationStatuses.VALID, + ); + function handleSelect(title: string | null) { onSelect(models.find((m) => m.title === title) ?? null); } + function onClickGear(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + ideMessenger.post("config/openProfile", { profileId: undefined }); + } + + function handleOptionClick( + showMissingApiKeyMsg: boolean, + e: MouseEvent, + ) { + if (showMissingApiKeyMsg) { + e.preventDefault(); + e.stopPropagation(); + } + } + return ( <>
@@ -52,8 +83,14 @@ const ModelRoleSelector = ({ disabled={models.length === 0} className={`bg-vsc-editor-background hover:bg-list-active hover:text-list-active-foreground w-full justify-between`} > - {models.length === 0 ? ( - {`No ${displayName} models${["Chat", "Apply", "Edit"].includes(displayName) ? ". Using chat model" : ""}`} + {models.length === 0 || noConfiguredModels ? ( + + {`No ${models.length === 0 ? "" : "valid "}${displayName} models${ + ["Chat", "Apply", "Edit"].includes(displayName) + ? ". Using Chat model" + : "" + }`} + ) : ( {selectedModel?.title ?? `Select ${displayName} model`} @@ -71,19 +108,55 @@ const ModelRoleSelector = ({ style={{ borderRadius: defaultBorderRadius }} className="min-w-40" > - {models.map((option, idx) => ( - - { + const showMissingApiKeyMsg = + option.configurationStatus === + LLMConfigurationStatuses.MISSING_API_KEY; + + return ( + setHoveredIdx(idx)} + onMouseLeave={() => setHoveredIdx(null)} + onClick={(e: any) => + handleOptionClick(showMissingApiKeyMsg, e) + } + className={""} > - {option.title} - - {option.title === selectedModel?.title && ( - - ))} +
+
+
+ + + {option.title} + {showMissingApiKeyMsg && ( + + (Missing API key) + + )} + +
+
+ {hoveredIdx === idx && ( + + )} + {option.title === selectedModel?.title && ( + + )} +
+
+
+ + ); + })}
diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 152d701ae..6c7d7c325 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -8,7 +8,6 @@ import { Input } from "../../components"; import NumberInput from "../../components/gui/NumberInput"; import { Select } from "../../components/gui/Select"; import ToggleSwitch from "../../components/gui/Switch"; -import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { updateConfig } from "../../redux/slices/configSlice"; @@ -17,7 +16,6 @@ import { getFontSize } from "../../util"; export function UserSettingsForm() { /////// User settings section ////// const dispatch = useAppDispatch(); - const { controlServerBetaEnabled } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); @@ -118,7 +116,7 @@ export function UserSettingsForm() {
) : null} */} - {!controlServerBetaEnabled || hubEnabled ? ( + {hubEnabled ? (

User settings

diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 682671cbb..11017177b 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -13,6 +13,7 @@ import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; import styled from "styled-components"; import { Button, lightGray, vscBackground } from "../../components"; +import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons"; import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; @@ -24,19 +25,19 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { submitEdit } from "../../redux/slices/editModeState"; import { newSession, selectIsInEditMode, selectIsSingleRangeEditOrInsertion, + updateToolCallOutput } from "../../redux/slices/sessionSlice"; import { setDialogEntryOn, @@ -54,7 +55,6 @@ import { } from "../../util/freeTrial"; import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; -import ConfigErrorIndicator from "./ConfigError"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; @@ -105,7 +105,7 @@ export function Chat() { const showSessionTabs = useAppSelector( (store) => store.config.config.ui?.showSessionTabs, ); - const defaultModel = useAppSelector(selectDefaultModel); + const selectedChatModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); @@ -165,7 +165,7 @@ export function Chat() { "Cannot submit message while awaiting tool confirmation", ); } - if (defaultModel?.provider === "free-trial") { + if (selectedChatModel?.provider === "free-trial") { const newCount = incrementFreeTrialCount(); if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { @@ -224,7 +224,7 @@ export function Chat() { }, [ history, - defaultModel, + selectedChatModel, streamResponse, isSingleRangeEditOrInsertion, codeToEdit, @@ -233,7 +233,7 @@ export function Chat() { ); async function handleSingleRangeEditOrInsertion(editorState: JSONContent) { - if (!defaultModel) { + if (!selectedChatModel) { console.error("No selected chat model"); return; } @@ -248,7 +248,7 @@ export function Chat() { defaultContextProviders: [], availableSlashCommands: [], dispatch, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); const prompt = [ @@ -259,7 +259,6 @@ export function Chat() { ideMessenger.post("edit/sendPrompt", { prompt, range: codeToEdit[0] as RangeInFileWithContents, - selectedModelTitle: defaultModel.title, }); dispatch(submitEdit(prompt)); @@ -274,6 +273,21 @@ export function Chat() { [mainTextInputRef], ); + // Handle partial tool call output for streaming updates + useWebviewListener( + "toolCallPartialOutput", + async (data) => { + // Update tool call output in Redux store + dispatch( + updateToolCallOutput({ + toolCallId: data.toolCallId, + contextItems: data.contextItems, + }), + ); + }, + [dispatch], + ); + const isLastUserInput = useCallback( (index: number): boolean => { return !history @@ -437,7 +451,6 @@ export function Chat() {
)}
-
{hasPendingApplies && isSingleRangeEditOrInsertion && ( diff --git a/gui/src/pages/gui/ConfigError.tsx b/gui/src/pages/gui/ConfigError.tsx deleted file mode 100644 index 8bab2c3c9..000000000 --- a/gui/src/pages/gui/ConfigError.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useLocation, useNavigate } from "react-router-dom"; -import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; -import { ROUTES } from "../../util/navigation"; -import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; -import { useAppSelector } from "../../redux/hooks"; - -const ConfigErrorIndicator = () => { - const configError = useAppSelector((store) => store.config.configError); - - const navigate = useNavigate(); - const { pathname } = useLocation(); - - function onClickError() { - navigate(pathname === ROUTES.CONFIG_ERROR ? "/" : ROUTES.CONFIG_ERROR); - } - - if (!configError?.length) { - return null; - } - - // TODO: add a tooltip - return ( - - - - ); -}; - -export default ConfigErrorIndicator; diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 389528cd0..35fe3dc91 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -9,7 +9,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { isLocalProfile } from "../../util"; import { providers } from "../AddNewModel/configs/providers"; @@ -20,7 +20,7 @@ interface StreamErrorProps { const StreamErrorDialog = ({ error }: StreamErrorProps) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const hubEnabled = useAppSelector(selectUseHub); const selectedProfile = useAppSelector(selectSelectedProfile); const { session, refreshProfiles } = useAuth(); diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 45396dc23..7e50b7305 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,5 +1,5 @@ import { getMarkdownLanguageTagForFile } from "core/util"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface CreateFileToolCallProps { relativeFilepath: string; @@ -11,9 +11,9 @@ export function CreateFile(props: CreateFileToolCallProps) { return props.relativeFilepath ? ( ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 80927e6e7..304dcb4c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,7 +1,7 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; import { useAppSelector } from "../../../redux/hooks"; type EditToolCallProps = { @@ -29,9 +29,9 @@ export function EditFile(props: EditToolCallProps) { return ( <> diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 55ed79e2a..d9906794e 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -34,6 +34,7 @@ function FunctionSpecificToolCallDiv({ ); default: diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 35fc0e54f..7356d01f5 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,16 +1,106 @@ +import { AnyAction, ThunkDispatch } from "@reduxjs/toolkit"; import { ToolCallState } from "core"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import { Fragment } from "react"; +import { useDispatch } from "react-redux"; +import styled from "styled-components"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; +import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground"; +import { useAppDispatch } from "../../../redux/hooks"; interface RunTerminalCommandToolCallProps { command: string; toolCallState: ToolCallState; + toolCallId: string | undefined; } +const CommandStatus = styled.div` + font-size: 12px; + color: #666; + margin-top: 8px; + padding-left: 8px; + padding-right: 8px; + padding-bottom: 8px; + display: flex; + align-items: center; +`; + +const StatusIcon = styled.span<{ status: 'running' | 'completed' | 'failed' | 'background' }>` + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + background-color: ${props => + props.status === 'running' ? '#4caf50' : + props.status === 'completed' ? '#4caf50' : + props.status === 'background' ? '#2196f3' : + '#f44336'}; + ${props => props.status === 'running' ? 'animation: pulse 1.5s infinite;' : ''} +`; + +// Removed unused styled components + +const BackgroundLink = styled.a` + font-size: 12px; + color: #0077cc; + margin-left: 12px; + cursor: pointer; + text-decoration: none; + + &:hover { + text-decoration: underline; + } +`; + export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { + const dispatch = useAppDispatch(); + + // Find the terminal output from context items if available + const terminalItem = props.toolCallState.output?.find( + item => item.name === "Terminal" + ); + + const terminalContent = terminalItem?.content || ""; + const statusMessage = terminalItem?.status || ""; + const isRunning = props.toolCallState.status === "calling"; + const hasOutput = terminalContent.length > 0; + + // Determine status type + let statusType: 'running' | 'completed' | 'failed' | 'background' = 'completed'; + if (isRunning) { + statusType = 'running'; + } else if (statusMessage?.includes('failed')) { + statusType = 'failed'; + } else if (statusMessage?.includes('background')) { + statusType = 'background'; + } + return ( - + + + + {(statusMessage || isRunning) && ( + + + {isRunning ? "Running" : statusMessage} + {isRunning && props.toolCallId && ( + { + // Dispatch the action to move the command to the background + dispatch(moveTerminalProcessToBackground({ + toolCallId: props.toolCallId as string + })); + }} + > + Move to background + + )} + + )} + ); } diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx index 2289be544..dcf0cdc47 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx @@ -7,7 +7,8 @@ interface ToolOutputProps { } function ToolOutput(props: ToolOutputProps) { - if (props.contextItems.length === 0) { + // Terminal has dedicated UI to show the output + if (props.contextItems.some((ci) => ci.name === "Terminal")) { return null; } diff --git a/gui/src/pages/history/history.test.tsx b/gui/src/pages/history/history.test.tsx index f739220cb..9a9d2772c 100644 --- a/gui/src/pages/history/history.test.tsx +++ b/gui/src/pages/history/history.test.tsx @@ -15,8 +15,6 @@ vi.mock("react-router-dom", async () => { describe("history Page test", () => { it("History text is existed after render", () => { renderWithProviders(); - expect( - screen.getByText("All session data is saved in ~/.continue/sessions"), - ).toBeInTheDocument(); + expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); }); diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index f59da5509..a8be3d92f 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -8,7 +8,10 @@ export default function HistoryPage() { const navigate = useNavigate(); return ( -
+
navigate("/")} diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 3092f01c5..0c78a27e0 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -6,7 +6,6 @@ import { DEFAULT_MAX_TOKENS } from "core/llm/constants"; export type ConfigState = { configError: ConfigValidationError[] | undefined; config: BrowserSerializedContinueConfig; - defaultModelTitle?: string; }; const EMPTY_CONFIG: BrowserSerializedContinueConfig = { @@ -21,7 +20,6 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { }, ], contextProviders: [], - models: [], tools: [], mcpServerStatuses: [], usePlatform: true, @@ -43,11 +41,11 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { rerank: null, embed: null, }, + rules: [], }; const initialState: ConfigState = { configError: undefined, - defaultModelTitle: undefined, config: EMPTY_CONFIG, }; @@ -62,7 +60,11 @@ export const configSlice = createSlice({ }: PayloadAction>, ) => { const { config, errors } = result; - state.configError = errors; + if (!errors || errors.length === 0) { + state.configError = undefined; + } else { + state.configError = errors; + } // If an error is found in config on save, // We must invalidate the GUI config too, @@ -70,12 +72,8 @@ export const configSlice = createSlice({ // Don't invalidate the loaded config if (!config) { state.config = EMPTY_CONFIG; - state.defaultModelTitle = undefined; } else { state.config = config; - state.defaultModelTitle = - config.models.find((model) => model.title === state.defaultModelTitle) - ?.title || config.models[0]?.title; } }, updateConfig: ( @@ -84,63 +82,29 @@ export const configSlice = createSlice({ ) => { state.config = config; }, - setDefaultModel: ( - state, - { payload }: PayloadAction<{ title: string; force?: boolean }>, - ) => { - const model = state.config.models.find( - (model) => model.title === payload.title, - ); - if (!model && !payload.force) return; - return { - ...state, - defaultModelTitle: payload.title, - }; - }, - cycleDefaultModel: (state, { payload }: PayloadAction<"next" | "prev">) => { - const currentIndex = state.config.models.findIndex( - (model) => model.title === state.defaultModelTitle, - ); - const nextIndex = - (currentIndex + - (payload === "next" ? 1 : -1) + - state.config.models.length) % - state.config.models.length; - return { - ...state, - defaultModelTitle: state.config.models[nextIndex].title, - }; - }, }, selectors: { - selectDefaultModel: (state) => { - return state.config.models.find( - (model) => model.title === state.defaultModelTitle, - ); - }, - selectDefaultModelContextLength: (state): number => { + selectSelectedChatModelContextLength: (state): number => { return ( - configSlice.getSelectors().selectDefaultModel(state)?.contextLength || + state.config.selectedModelByRole.chat?.contextLength || DEFAULT_MAX_TOKENS ); }, + selectSelectedChatModel: (state) => { + return state.config.selectedModelByRole.chat; + }, selectUIConfig: (state) => { return state.config?.ui ?? null; }, }, }); -export const { - setDefaultModel, - cycleDefaultModel, - updateConfig, - setConfigResult, -} = configSlice.actions; +export const { updateConfig, setConfigResult } = configSlice.actions; export const { - selectDefaultModel, - selectDefaultModelContextLength, + selectSelectedChatModelContextLength, selectUIConfig, + selectSelectedChatModel, } = configSlice.selectors; export default configSlice.reducer; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 0906fdd45..7c065a9ae 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -637,6 +637,23 @@ export const sessionSlice = createSlice({ toolCallState.output = action.payload; }, + updateToolCallOutput: ( + state, + action: PayloadAction<{ toolCallId: string; contextItems: ContextItem[] }>, + ) => { + // Find the tool call with the given ID and update its output + const { toolCallId, contextItems } = action.payload; + + // Find the history item containing the tool call + const historyItem = state.history.find( + (item) => + item.toolCallState?.toolCallId === toolCallId + ); + + if (historyItem && historyItem.toolCallState) { + historyItem.toolCallState.output = contextItems; + } + }, cancelToolCall: (state) => { const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -773,6 +790,7 @@ export const { acceptToolCall, setToolGenerated, setToolCallOutput, + updateToolCallOutput, setMode, setAllSessionMetadata, addSessionMetadata, diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 0ea07b190..7cc964cd6 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -52,6 +52,7 @@ export const uiSlice = createSlice({ [BuiltInToolNames.SearchWeb]: "allowedWithoutPermission", [BuiltInToolNames.ViewDiff]: "allowedWithoutPermission", [BuiltInToolNames.LSTool]: "allowedWithoutPermission", + [BuiltInToolNames.CreateRuleBlock]: "allowedWithPermission", }, toolGroupSettings: { BUILT_IN_GROUP_NAME: "include", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index bf15e7ae8..cb875f805 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -5,7 +5,7 @@ import { EditToolArgs } from "core/tools/definitions/editFile"; import { resolveRelativePathInDir } from "core/util/ideUtils"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { acceptToolCall, cancelToolCall, @@ -30,8 +30,9 @@ export const callTool = createAsyncThunk( return; } - const defaultModel = selectDefaultModel(state); - if (!defaultModel) { + const selectedChatModel = selectSelectedChatModel(state); + + if (!selectedChatModel) { throw new Error("No model selected"); } @@ -54,7 +55,6 @@ export const callTool = createAsyncThunk( args, extra.ideMessenger, state.session.activeToolStreamId[0], - defaultModel.title, toolCallState.toolCallId, ); } catch (e) { @@ -77,7 +77,7 @@ export const callTool = createAsyncThunk( } else { const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); if (result.status === "error") { errorMessage = result.error; @@ -125,7 +125,6 @@ async function customGuiEditImpl( args: EditToolArgs, ideMessenger: IIdeMessenger, streamId: string, - modelTitle: string, toolCallId: string, ) { const firstUriMatch = await resolveRelativePathInDir( @@ -138,7 +137,6 @@ async function customGuiEditImpl( const apply = await ideMessenger.request("applyToFile", { streamId, text: args.new_contents, - curSelectedModelTitle: modelTitle, toolCallId, filepath: firstUriMatch, }); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 450471164..2ba244d3f 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -9,7 +9,7 @@ import { } from "core"; import * as URI from "uri-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; export const gatherContext = createAsyncThunk< @@ -37,11 +37,12 @@ export const gatherContext = createAsyncThunk< { dispatch, extra, getState }, ) => { const state = getState(); - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); + const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; - if (!defaultModel) { + if (!selectedChatModel) { console.error( "gatherContext thunk: Cannot gather context, no model selected", ); @@ -57,12 +58,12 @@ export const gatherContext = createAsyncThunk< defaultContextProviders, availableSlashCommands: state.config.config.slashCommands, dispatch, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); // Automatically use currently open file if (!modifiers.noContext) { - const usingFreeTrial = defaultModel.provider === "free-trial"; + const usingFreeTrial = selectedChatModel.provider === "free-trial"; const currentFileResponse = await extra.ideMessenger.request( "context/getContextItems", @@ -71,7 +72,7 @@ export const gatherContext = createAsyncThunk< query: "non-mention-usage", fullInput: "", selectedCode: [], - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }, ); if (currentFileResponse.status === "success") { diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index 59b556f8d..ad987fafa 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -5,3 +5,4 @@ export { streamNormalInput } from "./streamNormalInput"; export { streamResponseThunk } from "./streamResponse"; export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; export { streamThunkWrapper } from "./streamThunkWrapper"; +export { updateSelectedModelByRole } from "./updateSelectedModelByRole"; diff --git a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts new file mode 100644 index 000000000..1b592f549 --- /dev/null +++ b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts @@ -0,0 +1,68 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { abortStream, acceptToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +/** + * This thunk is used to move a terminal command to the background + * when the user clicks the "Continue" button in the UI + * + * It marks the command as visually complete without stopping + * the already running process + */ +export const moveTerminalProcessToBackground = createAsyncThunk< + void, + { toolCallId: string }, + ThunkApiType +>("chat/moveTerminalProcessToBackground", async ({ toolCallId }, { dispatch, getState, extra }) => { + // Find the current tool call + const state = getState(); + const toolCalls = state.session.history.filter( + (item) => item.toolCallState?.toolCallId === toolCallId + ); + + if (toolCalls.length === 0) { + console.error("Could not find tool call with ID:", toolCallId); + return; + } + + const toolCall = toolCalls[0].toolCallState; + if (!toolCall) { + console.error("Tool call state is missing"); + return; + } + + const status = "Command moved to background. Further output will be ignored." + + const contextItems: ContextItem[] = [ + { + name: "Terminal", + description: "Terminal command output", + content: "\n" + status, + status: status, + } + ]; + + // Abort any existing stream for this tool call + dispatch(abortStream()); + + // Update the tool call output + dispatch(updateToolCallOutput({ + toolCallId, + contextItems + })); + + // Mark the process as backgrounded so we ignore future events + await extra.ideMessenger.request("process/markAsBackgrounded", { toolCallId }); + + // Mark the tool call as "done" in the UI + // This will set isRunning to false in RunTerminalCommand.tsx + dispatch(acceptToolCall()); + + // Trigger an LLM response about the command being moved to background + dispatch(streamResponseAfterToolCall({ + toolCallId, + toolOutput: contextItems + })); +}); \ No newline at end of file diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index b5ef0ac9a..7572b1fe4 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -3,7 +3,7 @@ import { ChatMessage, Session, SessionMetadata } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { deleteSessionMetadata, newSession, @@ -167,8 +167,9 @@ export const saveCurrentSession = createAsyncThunk< // Now save previous session and update chat title if relevant let title = state.session.title; if (title === NEW_SESSION_TITLE) { - const defaultModel = selectDefaultModel(state); - if (!state.config.config?.disableSessionTitles && defaultModel) { + const selectedChatModel = selectSelectedChatModel(state); + + if (!state.config.config?.disableSessionTitles && selectedChatModel) { let assistantResponse = state.session.history ?.filter((h) => h.message.role === "assistant")[0] ?.message?.content?.toString(); @@ -179,7 +180,7 @@ export const saveCurrentSession = createAsyncThunk< "chatDescriber/describe", { text: assistantResponse, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }, ); if (result.status === "success" && result.content) { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index afc80fbe4..c8b10dc37 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -3,13 +3,13 @@ import { ChatMessage } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { ToCoreProtocol } from "core/protocol"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, selectUseTools, setToolGenerated, - streamUpdate + streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { callTool } from "./callTool"; @@ -29,15 +29,16 @@ export const streamNormalInput = createAsyncThunk< ) => { // Gather state const state = getState(); - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); + const toolSettings = state.ui.toolSettings; const toolGroupSettings = state.ui.toolGroupSettings; const streamAborter = state.session.streamAborter; const useTools = selectUseTools(state); - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("Default model not defined"); } - const includeTools = useTools && modelSupportsTools(defaultModel); + const includeTools = useTools && modelSupportsTools(selectedChatModel); // Send request const gen = extra.ideMessenger.llmStreamChat( @@ -51,7 +52,7 @@ export const streamNormalInput = createAsyncThunk< ), } : {}, - title: defaultModel.title, + title: selectedChatModel.title, messages, legacySlashCommandData, }, @@ -81,8 +82,8 @@ export const streamNormalInput = createAsyncThunk< data: { prompt: next.value.prompt, completion: next.value.completion, - modelProvider: defaultModel.provider, - modelTitle: defaultModel.title, + modelProvider: selectedChatModel.provider, + modelTitle: selectedChatModel.title, sessionId: state.session.id, }, }); @@ -93,8 +94,8 @@ export const streamNormalInput = createAsyncThunk< // data: { // prompt: next.value.prompt, // completion: next.value.completion, - // modelProvider: defaultModel.provider, - // modelTitle: defaultModel.title, + // modelProvider: selectedChatModel.provider, + // modelTitle: selectedChatModel.title, // }, // }); // } diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 9b802ffbb..63b5e6189 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -4,7 +4,7 @@ import { InputModifiers } from "core"; import { constructMessages } from "core/llm/constructMessages"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { submitEditorAndInitAtIndex, updateHistoryItemAtIndex, @@ -34,11 +34,10 @@ export const streamResponseThunk = createAsyncThunk< await dispatch( streamThunkWrapper(async () => { const state = getState(); - const defaultModel = selectDefaultModel(state); - const slashCommands = state.config.config.slashCommands || []; + const selectedChatModel = selectSelectedChatModel(state); const inputIndex = index ?? state.session.history.length; // Either given index or concat to end - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("No chat model selected"); } @@ -86,7 +85,12 @@ export const streamResponseThunk = createAsyncThunk< // Construct messages from updated history const updatedHistory = getState().session.history; - const messages = constructMessages([...updatedHistory]); + const messages = constructMessages( + [...updatedHistory], + selectedChatModel?.baseChatSystemMessage, + state.config.config.rules, + selectedChatModel.model, + ); posthog.capture("step run", { step_name: "User Input", diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 99554a628..5a0083886 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -2,7 +2,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, ContextItem } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { addContextItemsAtIndex, setActive, @@ -27,9 +27,9 @@ export const streamResponseAfterToolCall = createAsyncThunk< streamThunkWrapper(async () => { const state = getState(); const initialHistory = state.session.history; - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("No model selected"); } @@ -59,7 +59,13 @@ export const streamResponseAfterToolCall = createAsyncThunk< dispatch(setActive()); const updatedHistory = getState().session.history; - const messages = constructMessages([...updatedHistory]); + const messages = constructMessages( + [...updatedHistory], + selectedChatModel?.baseChatSystemMessage, + state.config.config.rules, + selectedChatModel.model, + ); + unwrapResult(await dispatch(streamNormalInput({ messages }))); }), ); diff --git a/gui/src/redux/thunks/updateSelectedModelByRole.ts b/gui/src/redux/thunks/updateSelectedModelByRole.ts new file mode 100644 index 000000000..8ad4f3df5 --- /dev/null +++ b/gui/src/redux/thunks/updateSelectedModelByRole.ts @@ -0,0 +1,58 @@ +import { ModelRole } from "@continuedev/config-yaml"; +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { updateConfig } from "../slices/configSlice"; +import { ThunkApiType } from "../store"; + +export const updateSelectedModelByRole = createAsyncThunk< + void, + { + role: ModelRole; + modelTitle: string; + selectedProfile: ProfileDescription | null; + }, + ThunkApiType +>( + "config/updateSelectedModel", + async ( + { role, modelTitle, selectedProfile }, + { dispatch, extra, getState }, + ) => { + if (!selectedProfile) { + return; + } + + const state = getState(); + + const { + config: { config }, + } = state; + + const model = state.config.config.modelsByRole[role]?.find( + (m) => m.title === modelTitle, + ); + + if (!model) { + console.error( + `Model with title "${modelTitle}" not found for role "${role}"`, + ); + return; + } + + dispatch( + updateConfig({ + ...config, + selectedModelByRole: { + ...config.selectedModelByRole, + [role]: model, + }, + }), + ); + + extra.ideMessenger.post("config/updateSelectedModel", { + role, + profileId: selectedProfile.id, + title: modelTitle, + }); + }, +); diff --git a/gui/src/util/navigation.ts b/gui/src/util/navigation.ts index 8a7693b32..0f145b6cd 100644 --- a/gui/src/util/navigation.ts +++ b/gui/src/util/navigation.ts @@ -1,7 +1,6 @@ // TODO: Move all the routes here export const ROUTES = { HOME: "/", - CONFIG_ERROR: "/config-error", CONFIG: "/config", // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`, }; diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index fe2b8c0e4..f376aa2bc 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -43,6 +43,7 @@ module.exports = { "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)", "list-active-foreground": "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))", + badge: "var(--vscode-badge-background, #1bbe84)", }, }, }, diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 87f2e654b..44147f676 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -25,7 +25,7 @@ nltk==3.6.3 spacy==3.1.2 # Deep Learning -torch==1.9.1 +torch==2.6.0 keras==2.6.0 # Image processing diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index 44c55402e..d2920d6af 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -7,9 +7,7 @@ class Calculator { this.result += number; return this; } - subtract(number) { - this.result -= number; return this; } diff --git a/manual-testing-sandbox/test.kt b/manual-testing-sandbox/test.kt index 683993e81..bb13ae9ee 100644 --- a/manual-testing-sandbox/test.kt +++ b/manual-testing-sandbox/test.kt @@ -30,3 +30,4 @@ class Test { return this } } + diff --git a/package-lock.json b/package-lock.json index cdfb21273..06f811afa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,6 +6,7 @@ "": { "devDependencies": { "@typescript-eslint/parser": "^7.8.0", + "concurrently": "^9.1.2", "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", @@ -360,7 +361,6 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -370,7 +370,6 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, - "peer": true, "dependencies": { "color-convert": "^2.0.1" }, @@ -587,7 +586,6 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, - "peer": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -599,12 +597,26 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, - "peer": true, "dependencies": { "color-name": "~1.1.4" }, @@ -616,8 +628,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "peer": true + "dev": true }, "node_modules/concat-map": { "version": "0.0.1", @@ -625,6 +636,48 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true }, + "node_modules/concurrently": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.1.2.tgz", + "integrity": "sha512-H9MWcoPsYddwbOGM6difjVwVZHl63nwMEwDJG/L7VGtuaJhb12h2caPG2tVPWs7emuYix252iGfqOyrz1GczTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2", + "lodash": "^4.17.21", + "rxjs": "^7.8.1", + "shell-quote": "^1.8.1", + "supports-color": "^8.1.1", + "tree-kill": "^1.2.2", + "yargs": "^17.7.2" + }, + "bin": { + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/bin/concurrently.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -775,6 +828,13 @@ "node": ">=6.0.0" } }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, "node_modules/es-abstract": { "version": "1.23.3", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", @@ -908,6 +968,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -1399,6 +1469,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", @@ -1579,7 +1659,6 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -1826,6 +1905,16 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -2071,6 +2160,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -2515,6 +2611,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve": { "version": "1.22.8", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", @@ -2592,6 +2698,16 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-array-concat": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", @@ -2694,6 +2810,19 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.2.tgz", + "integrity": "sha512-AzqKpGKjrj7EM6rKVQEPpB288oCfnrEIuyoT9cyF4nmGa7V8Zk6f7RRqYisX8X9m+Q7bd632aZW4ky7EhbQztA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", @@ -2721,6 +2850,21 @@ "node": ">=8" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/string.prototype.trim": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", @@ -2775,7 +2919,6 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, - "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -2810,7 +2953,6 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, - "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -2849,6 +2991,16 @@ "node": ">=8.0" } }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, "node_modules/ts-api-utils": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", @@ -2873,6 +3025,13 @@ "strip-bom": "^3.0.0" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -3071,6 +3230,24 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -3078,6 +3255,45 @@ "dev": true, "peer": true }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index dd376f1ec..01270032f 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,17 @@ { "scripts": { - "tsc:watch": "npx concurrently -n gui,vscode,core,binary -c cyan,magenta,yellow,green \"npm run tsc:watch:gui\" \"npm run tsc:watch:vscode\" \"npm run tsc:watch:core\" \"npm run tsc:watch:binary\"", + "tsc:watch": "concurrently -n gui,vscode,core,binary -c cyan,magenta,yellow,green \"npm run tsc:watch:gui\" \"npm run tsc:watch:vscode\" \"npm run tsc:watch:core\" \"npm run tsc:watch:binary\"", "tsc:watch:gui": "tsc --project gui/tsconfig.json --watch --noEmit --pretty", "tsc:watch:vscode": "tsc --project extensions/vscode/tsconfig.json --watch --noEmit --pretty", "tsc:watch:core": "tsc --project core/tsconfig.json --watch --noEmit --pretty", "tsc:watch:binary": "tsc --project binary/tsconfig.json --watch --noEmit --pretty" }, "devDependencies": { - "typescript": "^5.6.3", "@typescript-eslint/parser": "^7.8.0", + "concurrently": "^9.1.2", "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", - "prettier-plugin-tailwindcss": "^0.6.8" + "prettier-plugin-tailwindcss": "^0.6.8", + "typescript": "^5.6.3" } } diff --git a/packages/config-types/package-lock.json b/packages/config-types/package-lock.json index 6e6f16916..6449198ab 100644 --- a/packages/config-types/package-lock.json +++ b/packages/config-types/package-lock.json @@ -1,20 +1,31 @@ { "name": "@continuedev/config-types", - "version": "1.0.13", + "version": "1.0.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-types", - "version": "1.0.13", + "version": "1.0.14", "license": "Apache-2.0", "dependencies": { - "zod": "^3.23.8" + "zod": "^3.24.2" }, "devDependencies": { + "@types/node": "^20.11.19", "typescript": "^5.5.2" } }, + "node_modules/@types/node": { + "version": "20.17.30", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.30.tgz", + "integrity": "sha512-7zf4YyHA+jvBNfVrk2Gtvs6x7E8V+YDW05bNfG2XkWDJfYRXrTiP/DsB2zSYTaHX0bGIujTBQdMVAhb+j7mwpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, "node_modules/typescript": { "version": "5.5.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.2.tgz", @@ -28,10 +39,18 @@ "node": ">=14.17" } }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, "node_modules/zod": { - "version": "3.23.8", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", - "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "version": "3.24.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", + "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", + "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/packages/config-types/package.json b/packages/config-types/package.json index 5c420223f..2cccfe1ab 100644 --- a/packages/config-types/package.json +++ b/packages/config-types/package.json @@ -12,9 +12,10 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { + "@types/node": "^20.11.19", "typescript": "^5.5.2" }, "dependencies": { "zod": "^3.24.2" } -} +} \ No newline at end of file diff --git a/packages/config-yaml/.gitignore b/packages/config-yaml/.gitignore new file mode 100644 index 000000000..b73759d7b --- /dev/null +++ b/packages/config-yaml/.gitignore @@ -0,0 +1 @@ +schema/ \ No newline at end of file diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index bd174fa96..bef305fe9 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.87", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.87", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -22,7 +22,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@ampproject/remapping": { @@ -1049,6 +1050,7 @@ "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", "dev": true, + "license": "MIT", "dependencies": { "expect": "^29.0.0", "pretty-format": "^29.0.0" @@ -3822,6 +3824,16 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zod-to-json-schema": { + "version": "3.24.5", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.5.tgz", + "integrity": "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.24.1" + } } } } diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 0f6e6b82c..f538969ea 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.87", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -10,7 +10,8 @@ }, "scripts": { "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", - "build": "tsc" + "build": "tsc", + "generate-schema": "tsc && node dist/scripts/generateJsonSchema.js" }, "author": "Continue Dev, Inc.", "license": "Apache-2.0", @@ -25,6 +26,7 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } } diff --git a/packages/config-yaml/test/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts similarity index 75% rename from packages/config-yaml/test/index.test.ts rename to packages/config-yaml/src/__tests__/index.test.ts index 71b073f42..0c8f120d7 100644 --- a/packages/config-yaml/test/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -1,18 +1,19 @@ import * as fs from "fs"; -import { decodeSecretLocation, resolveSecretLocationInProxy } from "../dist"; import { + decodeSecretLocation, FQSN, FullSlug, PlatformClient, PlatformSecretStore, Registry, resolveFQSN, + resolveSecretLocationInProxy, SecretLocation, SecretResult, SecretStore, SecretType, unrollAssistant, -} from "../src"; +} from "../index.js"; // Test e2e flows from raw yaml -> unroll -> client render -> resolve secrets on proxy describe("E2E Scenarios", () => { @@ -92,12 +93,28 @@ describe("E2E Scenarios", () => { getContent: async function (fullSlug: FullSlug): Promise { return fs .readFileSync( - `./test/packages/${fullSlug.ownerSlug}/${fullSlug.packageSlug}.yaml`, + `./src/__tests__/packages/${fullSlug.ownerSlug}/${fullSlug.packageSlug}.yaml`, ) .toString(); }, }; + it("should unroll assistant with a single block that doesn't exist", async () => { + const unrolledConfig = await unrollAssistant( + "test-org/assistant-with-non-existing-block", + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + }, + ); + + expect(unrolledConfig.rules?.[0]).toBeNull(); + }); + it("should correctly unroll assistant", async () => { const unrolledConfig = await unrollAssistant( "test-org/assistant", @@ -133,10 +150,10 @@ describe("E2E Scenarios", () => { ); expect(unrolledConfig.rules?.length).toBe(2); - expect(unrolledConfig.docs?.[0].startUrl).toBe( + expect(unrolledConfig.docs?.[0]?.startUrl).toBe( "https://docs.python.org/release/3.13.1", ); - expect(unrolledConfig.docs?.[0].rootUrl).toBe( + expect(unrolledConfig.docs?.[0]?.rootUrl).toBe( "https://docs.python.org/release/3.13.1", ); @@ -176,5 +193,40 @@ describe("E2E Scenarios", () => { expect(geminiSecretValue2).toBe("gemini-api-key"); }); + it("should correctly unroll assistant with injected blocks", async () => { + const unrolledConfig = await unrollAssistant( + "test-org/assistant", + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + // Add an injected block + injectBlocks: [ + { + ownerSlug: "test-org", + packageSlug: "docs", + versionSlug: "latest", + }, + ], + }, + ); + + // The original docs array should have one item + expect(unrolledConfig.docs?.length).toBe(2); // Now 2 with the injected block + + // Check the original doc is still there + expect(unrolledConfig.docs?.[0]?.startUrl).toBe( + "https://docs.python.org/release/3.13.1", + ); + + // Check the injected doc block was added + expect(unrolledConfig.docs?.[1]?.startUrl).toBe( + "https://docs.python.org/release/3.13.1", + ); + }); + it.skip("should prioritize org over user / package secrets", () => {}); }); diff --git a/packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml b/packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml new file mode 100644 index 000000000..4f01b32b8 --- /dev/null +++ b/packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml @@ -0,0 +1,6 @@ +name: Assistant with non-existing block +version: 0.0.1 +schema: v1 + +rules: + - uses: test-org/non-existing-package diff --git a/packages/config-yaml/test/packages/test-org/assistant.yaml b/packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml similarity index 100% rename from packages/config-yaml/test/packages/test-org/assistant.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml diff --git a/packages/config-yaml/test/packages/test-org/claude35sonnet.yaml b/packages/config-yaml/src/__tests__/packages/test-org/claude35sonnet.yaml similarity index 100% rename from packages/config-yaml/test/packages/test-org/claude35sonnet.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/claude35sonnet.yaml diff --git a/packages/config-yaml/test/packages/test-org/docs.yaml b/packages/config-yaml/src/__tests__/packages/test-org/docs.yaml similarity index 100% rename from packages/config-yaml/test/packages/test-org/docs.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/docs.yaml diff --git a/packages/config-yaml/test/packages/test-org/gemini.yaml b/packages/config-yaml/src/__tests__/packages/test-org/gemini.yaml similarity index 100% rename from packages/config-yaml/test/packages/test-org/gemini.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/gemini.yaml diff --git a/packages/config-yaml/test/packages/test-org/rules.yaml b/packages/config-yaml/src/__tests__/packages/test-org/rules.yaml similarity index 100% rename from packages/config-yaml/test/packages/test-org/rules.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/rules.yaml diff --git a/packages/config-yaml/src/converter.ts b/packages/config-yaml/src/converter.ts index 13f54cb8c..84786c880 100644 --- a/packages/config-yaml/src/converter.ts +++ b/packages/config-yaml/src/converter.ts @@ -70,13 +70,13 @@ function convertCustomCommand( function convertMcp(mcp: any): NonNullable[number] { const { transport } = mcp; - const { command, args, env } = transport; + const { command, args, env, server_name } = transport; return { command, args, env, - name: "MCP Server", + name: server_name || "MCP Server", }; } diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index 585fc24ee..ffc62f0fc 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -120,16 +120,17 @@ export function useProxyForUnrenderedSecrets( if (config.models) { for (let i = 0; i < config.models.length; i++) { const apiKeyLocation = getUnrenderedSecretLocation( - config.models[i].apiKey, + config.models[i]?.apiKey, ); if (apiKeyLocation) { config.models[i] = { ...config.models[i], + name: config.models[i]?.name ?? "", provider: "continue-proxy", model: getContinueProxyModelName( packageSlug, - config.models[i].provider, - config.models[i].model, + config.models[i]?.provider ?? "", + config.models[i]?.model ?? "", ), apiKeyLocation: encodeSecretLocation(apiKeyLocation), orgScopeId, diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 3d56b0251..e0e440bb0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -20,6 +20,7 @@ import { Rule, } from "../schemas/index.js"; import { useProxyForUnrenderedSecrets } from "./clientRender.js"; +import { getBlockType } from "./getBlockType.js"; export function parseConfigYaml(configYaml: string): ConfigYaml { try { @@ -178,11 +179,18 @@ async function extractRenderedSecretsMap( return map; } -export interface DoNotRenderSecretsUnrollAssistantOptions { +export interface BaseUnrollAssistantOptions { + renderSecrets: boolean; + injectBlocks?: FullSlug[]; +} + +export interface DoNotRenderSecretsUnrollAssistantOptions + extends BaseUnrollAssistantOptions { renderSecrets: false; } -export interface RenderSecretsUnrollAssistantOptions { +export interface RenderSecretsUnrollAssistantOptions + extends BaseUnrollAssistantOptions { renderSecrets: true; orgScopeId: string | null; currentUserSlug: string; @@ -239,7 +247,11 @@ export async function unrollAssistantFromContent( let parsedYaml = parseConfigYaml(rawYaml); // Unroll blocks and convert their secrets to FQSNs - const unrolledAssistant = await unrollBlocks(parsedYaml, registry); + const unrolledAssistant = await unrollBlocks( + parsedYaml, + registry, + options.injectBlocks, + ); // Back to a string so we can fill in template variables const rawUnrolledYaml = YAML.stringify(unrolledAssistant); @@ -277,6 +289,7 @@ export async function unrollAssistantFromContent( export async function unrollBlocks( assistant: ConfigYaml, registry: Registry, + injectBlocks: FullSlug[] | undefined, ): Promise { const unrolledAssistant: AssistantUnrolled = { name: assistant.name, @@ -285,7 +298,7 @@ export async function unrollBlocks( const sections: (keyof Omit< ConfigYaml, - "name" | "version" | "rules" | "schema" + "name" | "version" | "rules" | "schema" | "metadata" >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; // For each section, replace "uses/with" blocks with the real thing @@ -296,16 +309,23 @@ export async function unrollBlocks( for (const unrolledBlock of assistant[section]) { // "uses/with" block if ("uses" in unrolledBlock) { - const blockConfigYaml = await resolveBlock( - decodeFullSlug(unrolledBlock.uses), - unrolledBlock.with, - registry, - ); - const block = blockConfigYaml[section]?.[0]; - if (block) { - sectionBlocks.push( - mergeOverrides(block, unrolledBlock.override ?? {}), + try { + const blockConfigYaml = await resolveBlock( + decodeFullSlug(unrolledBlock.uses), + unrolledBlock.with, + registry, ); + const block = blockConfigYaml[section]?.[0]; + if (block) { + sectionBlocks.push( + mergeOverrides(block, unrolledBlock.override ?? {}), + ); + } + } catch (err) { + console.error( + `Failed to unroll block ${unrolledBlock.uses}: ${(err as Error).message}`, + ); + sectionBlocks.push(null); } } else { // Normal block @@ -317,21 +337,28 @@ export async function unrollBlocks( } } - // Rules are a bit different because they can be strings, so hanlde separately + // Rules are a bit different because they can be strings, so handle separately if (assistant.rules) { - const rules: Rule[] = []; + const rules: (Rule | null)[] = []; for (const rule of assistant.rules) { if (typeof rule === "string" || !("uses" in rule)) { rules.push(rule); } else if ("uses" in rule) { - const blockConfigYaml = await resolveBlock( - decodeFullSlug(rule.uses), - rule.with, - registry, - ); - const block = blockConfigYaml.rules?.[0]; - if (block) { - rules.push(block); + try { + const blockConfigYaml = await resolveBlock( + decodeFullSlug(rule.uses), + rule.with, + registry, + ); + const block = blockConfigYaml.rules?.[0]; + if (block) { + rules.push(block); + } + } catch (err) { + console.error( + `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, + ); + rules.push(null); } } } @@ -339,6 +366,33 @@ export async function unrollBlocks( unrolledAssistant.rules = rules; } + // Add injected blocks + for (const injectBlock of injectBlocks ?? []) { + try { + const blockConfigYaml = await registry.getContent(injectBlock); + const parsedBlock = parseConfigYaml(blockConfigYaml); + const blockType = getBlockType(parsedBlock); + const resolvedBlock = await resolveBlock( + injectBlock, + undefined, + registry, + ); + + if (blockType) { + if (!unrolledAssistant[blockType]) { + unrolledAssistant[blockType] = []; + } + unrolledAssistant[blockType]?.push( + ...(resolvedBlock[blockType] as any), + ); + } + } catch (err) { + console.error( + `Failed to unroll block ${injectBlock}: ${(err as Error).message}`, + ); + } + } + return unrolledAssistant; } diff --git a/packages/config-yaml/src/schemas/commonSlugs.ts b/packages/config-yaml/src/schemas/commonSlugs.ts new file mode 100644 index 000000000..3ba10bbd5 --- /dev/null +++ b/packages/config-yaml/src/schemas/commonSlugs.ts @@ -0,0 +1,30 @@ +export const commonModelSlugs = [ + "anthropic/claude-3-7-sonnet", + "togetherai/llama-4-maverick-instruct-17bx128e", + "google/gemini-2.5-pro", + "mistral/codestral", + "voyageai/voyage-code-3", + "relace/instant-apply", + "xai/grok-2", + "openai/gpt-4o", + "togetherai/llama-4-scout-instruct-17bx16e", + "anthropic/claude-3-5-sonnet", + "google/gemini-2.0-flash", + "voyageai/rerank-2", + "ollama/deepseek-r1", + "morphllm/morph-v0", + "anthropic/claude-3-5-haiku", + "lmstudio/deepseek-r1", + "openai/o3-mini", + "voyageai/voyage-code-2", + "ollama/qwen2.5-coder-1.5b", + "openai/gpt-4o-mini", + "openai/o1", + "mistral/mistral-embed", + "ollama/nomic-embed-text-latest", + "lmstudio/deepseek-r1-8b", + "mistral/mistral-large", + "lmstudio/qwen2.5-coder-1.5b", + "ollama/deepseek-r1-8b", + "openai/text-embedding-3-large", +]; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index ae12c99a7..1de41838c 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,8 +1,10 @@ import * as z from "zod"; +import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; import { modelSchema, partialModelSchema } from "./models.js"; export const contextSchema = z.object({ + name: z.string().optional(), provider: z.string(), params: z.any().optional(), }); @@ -15,12 +17,16 @@ const mcpServerSchema = z.object({ env: z.record(z.string()).optional(), }); +export type MCPServer = z.infer; + const promptSchema = z.object({ name: z.string(), description: z.string().optional(), prompt: z.string(), }); +export type Prompt = z.infer; + const docSchema = z.object({ name: z.string(), startUrl: z.string(), @@ -28,6 +34,8 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +export type DocsConfig = z.infer; + const ruleObjectSchema = z.object({ name: z.string(), rule: z.string(), @@ -38,29 +46,50 @@ const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; -export const blockItemWrapperSchema = (schema: T) => +const defaultUsesSchema = z.string(); + +export const blockItemWrapperSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.object({ - uses: z.string(), + uses: usesSchema, with: z.record(z.string()).optional(), override: schema.partial().optional(), }); -export const blockOrSchema = (schema: T) => - z.union([schema, blockItemWrapperSchema(schema)]); +export const blockOrSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.union([schema, blockItemWrapperSchema(schema, usesSchema)]); + +export const commonMetadataSchema = z.object({ + tags: z.string().optional(), + sourceCodeUrl: z.string().optional(), + description: z.string().optional(), + author: z.string().optional(), + license: z.string().optional(), + iconUrl: z.string().optional(), +}); export const baseConfigYamlSchema = z.object({ name: z.string(), version: z.string(), schema: z.string().optional(), + metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(), }); +const modelsUsesSchema = z + .string() + .or(z.enum(commonModelSlugs as [string, ...string[]])); + export const configYamlSchema = baseConfigYamlSchema.extend({ models: z .array( z.union([ modelSchema, z.object({ - uses: z.string(), + uses: modelsUsesSchema, with: z.record(z.string()).optional(), override: partialModelSchema.optional(), }), @@ -75,7 +104,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ z.union([ ruleSchema, z.object({ - uses: z.string(), + uses: defaultUsesSchema, with: z.record(z.string()).optional(), }), ]), @@ -88,6 +117,18 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ export type ConfigYaml = z.infer; export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ + models: z.array(modelSchema.nullable()).optional(), + context: z.array(contextSchema.nullable()).optional(), + data: z.array(dataSchema.nullable()).optional(), + mcpServers: z.array(mcpServerSchema.nullable()).optional(), + rules: z.array(ruleSchema.nullable()).optional(), + prompts: z.array(promptSchema.nullable()).optional(), + docs: z.array(docSchema.nullable()).optional(), +}); + +export type AssistantUnrolled = z.infer; + +export const assistantUnrolledSchemaNonNullable = baseConfigYamlSchema.extend({ models: z.array(modelSchema).optional(), context: z.array(contextSchema).optional(), data: z.array(dataSchema).optional(), @@ -97,7 +138,20 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ docs: z.array(docSchema).optional(), }); -export type AssistantUnrolled = z.infer; +export type AssistantUnrolledNonNullable = z.infer< + typeof assistantUnrolledSchemaNonNullable +>; + +export const isAssistantUnrolledNonNullable = ( + a: AssistantUnrolled, +): a is AssistantUnrolledNonNullable => + (!a.models || a.models.every((m) => m !== null)) && + (!a.context || a.context.every((c) => c !== null)) && + (!a.data || a.data.every((d) => d !== null)) && + (!a.mcpServers || a.mcpServers.every((s) => s !== null)) && + (!a.rules || a.rules.every((r) => r !== null)) && + (!a.prompts || a.prompts.every((p) => p !== null)) && + (!a.docs || a.docs.every((d) => d !== null)); export const blockSchema = baseConfigYamlSchema.and( z.union([ diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 5730c74f9..e57e22bf6 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -58,6 +58,11 @@ export const embedOptionsSchema = z.object({ }); export type EmbedOptions = z.infer; +export const chatOptionsSchema = z.object({ + baseSystemMessage: z.string().optional(), +}); +export type ChatOptions = z.infer; + /** Prompt templates use Handlebars syntax */ const promptTemplatesSchema = z.object({ apply: z.string().optional(), @@ -75,7 +80,9 @@ const baseModelFields = { defaultCompletionOptions: completionOptionsSchema.optional(), requestOptions: requestOptionsSchema.optional(), embedOptions: embedOptionsSchema.optional(), + chatOptions: chatOptionsSchema.optional(), promptTemplates: promptTemplatesSchema.optional(), + useLegacyCompletionsEndpoint: z.boolean().optional(), env: z .record(z.string(), z.union([z.string(), z.boolean(), z.number()])) .optional(), diff --git a/packages/config-yaml/src/scripts/generateJsonSchema.ts b/packages/config-yaml/src/scripts/generateJsonSchema.ts new file mode 100644 index 000000000..308dcf951 --- /dev/null +++ b/packages/config-yaml/src/scripts/generateJsonSchema.ts @@ -0,0 +1,28 @@ +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +import { configYamlSchema } from '../schemas/index.js'; + +// Get the directory name of the current module +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +// Convert Zod schema to JSON schema +const jsonSchema = zodToJsonSchema(configYamlSchema, { + $refStrategy: 'none', + name: 'ConfigYaml', +}); + +// Output directory and file path +const outDir = path.resolve(__dirname, '../../schema'); +const outFile = path.join(outDir, 'config-yaml-schema.json'); + +// Ensure output directory exists +if (!fs.existsSync(outDir)) { + fs.mkdirSync(outDir, { recursive: true }); +} + +// Write the JSON schema to file +fs.writeFileSync(outFile, JSON.stringify(jsonSchema, null, 2)); + +console.log(`JSON schema has been written to ${outFile}`); \ No newline at end of file diff --git a/packages/continue-sdk/README.md b/packages/continue-sdk/README.md new file mode 100644 index 000000000..66b6532f1 --- /dev/null +++ b/packages/continue-sdk/README.md @@ -0,0 +1,23 @@ +# @continuedev/sdk + +> **⚠️ EXPERIMENTAL: This package is in early development and subject to frequent breaking changes without notice.** + +This SDK provides programmatic access to Continue's APIs and functionality. + +## Status + +This package is currently in early development and is considered **experimental**. It is not recommended for production use. The API surface, functionality, and implementation are subject to change at any time without prior notice or deprecation period. + + +## Development + +```bash +# Install dependencies +npm install + +# Generate API clients +npm run generate-client:ALL + +# Start Swagger UI for API exploration +npm run swagger-ui +``` \ No newline at end of file diff --git a/packages/continue-sdk/clients/python/.github/workflows/python.yml b/packages/continue-sdk/clients/python/.github/workflows/python.yml new file mode 100644 index 000000000..60073bfad --- /dev/null +++ b/packages/continue-sdk/clients/python/.github/workflows/python.yml @@ -0,0 +1,31 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: openapi_client Python package + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install -r test-requirements.txt + - name: Test with pytest + run: | + pytest --cov=openapi_client diff --git a/packages/continue-sdk/clients/python/.gitignore b/packages/continue-sdk/clients/python/.gitignore new file mode 100644 index 000000000..43995bd42 --- /dev/null +++ b/packages/continue-sdk/clients/python/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/packages/continue-sdk/clients/python/.gitlab-ci.yml b/packages/continue-sdk/clients/python/.gitlab-ci.yml new file mode 100644 index 000000000..156d5a581 --- /dev/null +++ b/packages/continue-sdk/clients/python/.gitlab-ci.yml @@ -0,0 +1,31 @@ +# NOTE: This file is auto generated by OpenAPI Generator. +# URL: https://openapi-generator.tech +# +# ref: https://docs.gitlab.com/ee/ci/README.html +# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml + +stages: + - test + +.pytest: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov=openapi_client + +pytest-3.8: + extends: .pytest + image: python:3.8-alpine +pytest-3.9: + extends: .pytest + image: python:3.9-alpine +pytest-3.10: + extends: .pytest + image: python:3.10-alpine +pytest-3.11: + extends: .pytest + image: python:3.11-alpine +pytest-3.12: + extends: .pytest + image: python:3.12-alpine diff --git a/packages/continue-sdk/clients/python/.openapi-generator-ignore b/packages/continue-sdk/clients/python/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/packages/continue-sdk/clients/python/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/packages/continue-sdk/clients/python/.openapi-generator/FILES b/packages/continue-sdk/clients/python/.openapi-generator/FILES new file mode 100644 index 000000000..c5f2b42f3 --- /dev/null +++ b/packages/continue-sdk/clients/python/.openapi-generator/FILES @@ -0,0 +1,38 @@ +.github/workflows/python.yml +.gitignore +.gitlab-ci.yml +.openapi-generator-ignore +.travis.yml +README.md +docs/DefaultApi.md +docs/ListAssistants200ResponseInner.md +docs/ListAssistants200ResponseInnerConfigResult.md +docs/ListAssistants401Response.md +docs/ListAssistants404Response.md +git_push.sh +openapi_client/__init__.py +openapi_client/api/__init__.py +openapi_client/api/default_api.py +openapi_client/api_client.py +openapi_client/api_response.py +openapi_client/configuration.py +openapi_client/exceptions.py +openapi_client/models/__init__.py +openapi_client/models/list_assistants200_response_inner.py +openapi_client/models/list_assistants200_response_inner_config_result.py +openapi_client/models/list_assistants401_response.py +openapi_client/models/list_assistants404_response.py +openapi_client/py.typed +openapi_client/rest.py +pyproject.toml +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +test/test_default_api.py +test/test_list_assistants200_response_inner.py +test/test_list_assistants200_response_inner_config_result.py +test/test_list_assistants401_response.py +test/test_list_assistants404_response.py +tox.ini diff --git a/packages/continue-sdk/clients/python/.openapi-generator/VERSION b/packages/continue-sdk/clients/python/.openapi-generator/VERSION new file mode 100644 index 000000000..5f84a81db --- /dev/null +++ b/packages/continue-sdk/clients/python/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.12.0 diff --git a/packages/continue-sdk/clients/python/.travis.yml b/packages/continue-sdk/clients/python/.travis.yml new file mode 100644 index 000000000..ae1aaf0be --- /dev/null +++ b/packages/continue-sdk/clients/python/.travis.yml @@ -0,0 +1,17 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" + # uncomment the following if needed + #- "3.12-dev" # 3.12 development branch + #- "nightly" # nightly build +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov=openapi_client diff --git a/packages/continue-sdk/clients/python/README.md b/packages/continue-sdk/clients/python/README.md new file mode 100644 index 000000000..75f45e7bb --- /dev/null +++ b/packages/continue-sdk/clients/python/README.md @@ -0,0 +1,127 @@ +# openapi-client +API for Continue IDE to fetch assistants and other related information. +These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Generator version: 7.12.0 +- Build package: org.openapitools.codegen.languages.PythonClientCodegen +For more information, please visit [https://continue.dev](https://continue.dev) + +## Requirements. + +Python 3.8+ + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import openapi_client +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import openapi_client +``` + +### Tests + +Execute `pytest` to run the tests. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + always_use_proxy = 'always_use_proxy_example' # str | Whether to always use the Continue-managed proxy for model requests (optional) + organization_id = 'organization_id_example' # str | ID of the organization to scope assistants to. If not provided, personal assistants are returned. (optional) + + try: + # List assistants for IDE + api_response = api_instance.list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id) + print("The response of DefaultApi->list_assistants:\n") + pprint(api_response) + except ApiException as e: + print("Exception when calling DefaultApi->list_assistants: %s\n" % e) + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://api.continue.dev* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**list_assistants**](docs/DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE + + +## Documentation For Models + + - [ListAssistants200ResponseInner](docs/ListAssistants200ResponseInner.md) + - [ListAssistants200ResponseInnerConfigResult](docs/ListAssistants200ResponseInnerConfigResult.md) + - [ListAssistants401Response](docs/ListAssistants401Response.md) + - [ListAssistants404Response](docs/ListAssistants404Response.md) + + + +## Documentation For Authorization + + +Authentication schemes defined for the API: + +### apiKeyAuth + +- **Type**: Bearer authentication + + +## Author + + + + diff --git a/packages/continue-sdk/clients/python/docs/DefaultApi.md b/packages/continue-sdk/clients/python/docs/DefaultApi.md new file mode 100644 index 000000000..9ddf8fb99 --- /dev/null +++ b/packages/continue-sdk/clients/python/docs/DefaultApi.md @@ -0,0 +1,96 @@ +# openapi_client.DefaultApi + +All URIs are relative to *https://api.continue.dev* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**list_assistants**](DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE + + +# **list_assistants** +> List[ListAssistants200ResponseInner] list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id) + +List assistants for IDE + +Returns a complete list of assistants available to the user, with their full configurations, +icons, and other metadata needed by the IDE to display and use them. + +This endpoint performs a full refresh of the list of assistants, including unrolling +configurations and resolving secrets. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + always_use_proxy = 'always_use_proxy_example' # str | Whether to always use the Continue-managed proxy for model requests (optional) + organization_id = 'organization_id_example' # str | ID of the organization to scope assistants to. If not provided, personal assistants are returned. (optional) + + try: + # List assistants for IDE + api_response = api_instance.list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id) + print("The response of DefaultApi->list_assistants:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->list_assistants: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **always_use_proxy** | **str**| Whether to always use the Continue-managed proxy for model requests | [optional] + **organization_id** | **str**| ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional] + +### Return type + +[**List[ListAssistants200ResponseInner]**](ListAssistants200ResponseInner.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved assistants | - | +**401** | Unauthorized - Authentication failed | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInner.md b/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInner.md new file mode 100644 index 000000000..f642b43c2 --- /dev/null +++ b/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInner.md @@ -0,0 +1,35 @@ +# ListAssistants200ResponseInner + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | | +**owner_slug** | **str** | Slug of the user or organization that owns the assistant | +**package_slug** | **str** | Slug of the assistant package | +**icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional] +**on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional] +**use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional] +**raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional] + +## Example + +```python +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner + +# TODO update the JSON string below +json = "{}" +# create an instance of ListAssistants200ResponseInner from a JSON string +list_assistants200_response_inner_instance = ListAssistants200ResponseInner.from_json(json) +# print the JSON string representation of the object +print(ListAssistants200ResponseInner.to_json()) + +# convert the object into a dict +list_assistants200_response_inner_dict = list_assistants200_response_inner_instance.to_dict() +# create an instance of ListAssistants200ResponseInner from a dict +list_assistants200_response_inner_from_dict = ListAssistants200ResponseInner.from_dict(list_assistants200_response_inner_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInnerConfigResult.md b/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInnerConfigResult.md new file mode 100644 index 000000000..bcee818dd --- /dev/null +++ b/packages/continue-sdk/clients/python/docs/ListAssistants200ResponseInnerConfigResult.md @@ -0,0 +1,31 @@ +# ListAssistants200ResponseInnerConfigResult + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**config** | **object** | The unrolled assistant configuration | +**config_load_interrupted** | **bool** | Whether the configuration loading was interrupted | +**errors** | **List[str]** | Any errors that occurred during configuration loading | [optional] + +## Example + +```python +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult + +# TODO update the JSON string below +json = "{}" +# create an instance of ListAssistants200ResponseInnerConfigResult from a JSON string +list_assistants200_response_inner_config_result_instance = ListAssistants200ResponseInnerConfigResult.from_json(json) +# print the JSON string representation of the object +print(ListAssistants200ResponseInnerConfigResult.to_json()) + +# convert the object into a dict +list_assistants200_response_inner_config_result_dict = list_assistants200_response_inner_config_result_instance.to_dict() +# create an instance of ListAssistants200ResponseInnerConfigResult from a dict +list_assistants200_response_inner_config_result_from_dict = ListAssistants200ResponseInnerConfigResult.from_dict(list_assistants200_response_inner_config_result_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/clients/python/docs/ListAssistants401Response.md b/packages/continue-sdk/clients/python/docs/ListAssistants401Response.md new file mode 100644 index 000000000..f10de1a66 --- /dev/null +++ b/packages/continue-sdk/clients/python/docs/ListAssistants401Response.md @@ -0,0 +1,29 @@ +# ListAssistants401Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.list_assistants401_response import ListAssistants401Response + +# TODO update the JSON string below +json = "{}" +# create an instance of ListAssistants401Response from a JSON string +list_assistants401_response_instance = ListAssistants401Response.from_json(json) +# print the JSON string representation of the object +print(ListAssistants401Response.to_json()) + +# convert the object into a dict +list_assistants401_response_dict = list_assistants401_response_instance.to_dict() +# create an instance of ListAssistants401Response from a dict +list_assistants401_response_from_dict = ListAssistants401Response.from_dict(list_assistants401_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/clients/python/docs/ListAssistants404Response.md b/packages/continue-sdk/clients/python/docs/ListAssistants404Response.md new file mode 100644 index 000000000..5752771ec --- /dev/null +++ b/packages/continue-sdk/clients/python/docs/ListAssistants404Response.md @@ -0,0 +1,29 @@ +# ListAssistants404Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.list_assistants404_response import ListAssistants404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of ListAssistants404Response from a JSON string +list_assistants404_response_instance = ListAssistants404Response.from_json(json) +# print the JSON string representation of the object +print(ListAssistants404Response.to_json()) + +# convert the object into a dict +list_assistants404_response_dict = list_assistants404_response_instance.to_dict() +# create an instance of ListAssistants404Response from a dict +list_assistants404_response_from_dict = ListAssistants404Response.from_dict(list_assistants404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/clients/python/git_push.sh b/packages/continue-sdk/clients/python/git_push.sh new file mode 100644 index 000000000..f53a75d4f --- /dev/null +++ b/packages/continue-sdk/clients/python/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/packages/continue-sdk/clients/python/openapi_client/__init__.py b/packages/continue-sdk/clients/python/openapi_client/__init__.py new file mode 100644 index 000000000..c5b552747 --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/__init__.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +# flake8: noqa + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from api.default_api import DefaultApi + +# import ApiClient +from openapi_client.api_response import ApiResponse +from openapi_client.api_client import ApiClient +from openapi_client.configuration import Configuration +from openapi_client.exceptions import OpenApiException +from openapi_client.exceptions import ApiTypeError +from openapi_client.exceptions import ApiValueError +from openapi_client.exceptions import ApiKeyError +from openapi_client.exceptions import ApiAttributeError +from openapi_client.exceptions import ApiException + +# import models into sdk package +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult +from openapi_client.models.list_assistants401_response import ListAssistants401Response +from openapi_client.models.list_assistants404_response import ListAssistants404Response diff --git a/packages/continue-sdk/clients/python/openapi_client/api/__init__.py b/packages/continue-sdk/clients/python/openapi_client/api/__init__.py new file mode 100644 index 000000000..5cfd22a1d --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/api/__init__.py @@ -0,0 +1,5 @@ +# flake8: noqa + +# import apis into api package +from api.default_api import DefaultApi + diff --git a/packages/continue-sdk/clients/python/openapi_client/api/default_api.py b/packages/continue-sdk/clients/python/openapi_client/api/default_api.py new file mode 100644 index 000000000..cd1e05cdf --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/api/default_api.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr, field_validator +from typing import List, Optional +from typing_extensions import Annotated +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner + +from openapi_client.api_client import ApiClient, RequestSerialized +from openapi_client.api_response import ApiResponse +from openapi_client.rest import RESTResponseType + + +class DefaultApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def list_assistants( + self, + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ListAssistants200ResponseInner]: + """List assistants for IDE + + Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistants_serialize( + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ListAssistants200ResponseInner]", + '401': "ListAssistants401Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_assistants_with_http_info( + self, + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ListAssistants200ResponseInner]]: + """List assistants for IDE + + Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistants_serialize( + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ListAssistants200ResponseInner]", + '401': "ListAssistants401Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_assistants_without_preload_content( + self, + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List assistants for IDE + + Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistants_serialize( + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ListAssistants200ResponseInner]", + '401': "ListAssistants401Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_assistants_serialize( + self, + always_use_proxy, + organization_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if always_use_proxy is not None: + + _query_params.append(('alwaysUseProxy', always_use_proxy)) + + if organization_id is not None: + + _query_params.append(('organizationId', organization_id)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/list-assistants', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/packages/continue-sdk/clients/python/openapi_client/api_client.py b/packages/continue-sdk/clients/python/openapi_client/api_client.py new file mode 100644 index 000000000..0371504ea --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/api_client.py @@ -0,0 +1,797 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from openapi_client.configuration import Configuration +from openapi_client.api_response import ApiResponse, T as ApiResponseT +import openapi_client.models +from openapi_client import rest +from openapi_client.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(openapi_client.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + elif klass == decimal.Decimal: + return decimal.Decimal(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, quote(str(value))) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/packages/continue-sdk/clients/python/openapi_client/api_response.py b/packages/continue-sdk/clients/python/openapi_client/api_response.py new file mode 100644 index 000000000..9bc7c11f6 --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/packages/continue-sdk/clients/python/openapi_client/configuration.py b/packages/continue-sdk/clients/python/openapi_client/configuration.py new file mode 100644 index 000000000..a689e96fc --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/configuration.py @@ -0,0 +1,585 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import http.client as httplib +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union +from typing_extensions import NotRequired, Self + +import urllib3 + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +ServerVariablesT = Dict[str, str] + +GenericAuthSetting = TypedDict( + "GenericAuthSetting", + { + "type": str, + "in": str, + "key": str, + "value": str, + }, +) + + +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +APIKeyAuthSetting = TypedDict( + "APIKeyAuthSetting", + { + "type": Literal["api_key"], + "in": str, + "key": str, + "value": Optional[str], + }, +) + + +BasicAuthSetting = TypedDict( + "BasicAuthSetting", + { + "type": Literal["basic"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": Optional[str], + }, +) + + +BearerFormatAuthSetting = TypedDict( + "BearerFormatAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "format": Literal["JWT"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +BearerAuthSetting = TypedDict( + "BearerAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +HTTPSignatureAuthSetting = TypedDict( + "HTTPSignatureAuthSetting", + { + "type": Literal["http-signature"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": None, + }, +) + + +AuthSettings = TypedDict( + "AuthSettings", + { + "apiKeyAuth": BearerAuthSetting, + }, + total=False, +) + + +class HostSettingVariable(TypedDict): + description: str + default_value: str + enum_values: List[str] + + +class HostSetting(TypedDict): + url: str + description: str + variables: NotRequired[Dict[str, HostSettingVariable]] + + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: Number of retries for API requests. + :param ca_cert_data: verify the peer using concatenated CA certificate data + in PEM (str) or DER (bytes) format. + + :Example: + """ + + _default: ClassVar[Optional[Self]] = None + + def __init__( + self, + host: Optional[str]=None, + api_key: Optional[Dict[str, str]]=None, + api_key_prefix: Optional[Dict[str, str]]=None, + username: Optional[str]=None, + password: Optional[str]=None, + access_token: Optional[str]=None, + server_index: Optional[int]=None, + server_variables: Optional[ServerVariablesT]=None, + server_operation_index: Optional[Dict[int, int]]=None, + server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, + ignore_operation_servers: bool=False, + ssl_ca_cert: Optional[str]=None, + retries: Optional[int] = None, + ca_cert_data: Optional[Union[str, bytes]] = None, + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self._base_path = "https://api.continue.dev" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("openapi_client") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.ca_cert_data = ca_cert_data + """Set this to verify the peer using PEM (str) or DER (bytes) + certificate data. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy: Optional[str] = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = retries + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls) -> Self: + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls) -> Self: + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = cls() + return cls._default + + @property + def logger_file(self) -> Optional[str]: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value: bool) -> None: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + return None + + def get_basic_auth_token(self) -> Optional[str]: + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self)-> AuthSettings: + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth: AuthSettings = {} + if self.access_token is not None: + auth['apiKeyAuth'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self) -> str: + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self) -> List[HostSetting]: + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://api.continue.dev", + 'description': "Production server", + }, + { + 'url': "http://localhost:3001", + 'description': "Local development server", + } + ] + + def get_host_from_settings( + self, + index: Optional[int], + variables: Optional[ServerVariablesT]=None, + servers: Optional[List[HostSetting]]=None, + ) -> str: + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self) -> str: + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value: str) -> None: + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/packages/continue-sdk/clients/python/openapi_client/exceptions.py b/packages/continue-sdk/clients/python/openapi_client/exceptions.py new file mode 100644 index 000000000..e8429df70 --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/exceptions.py @@ -0,0 +1,216 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + # Added new conditions for 409 and 422 + if http_resp.status == 409: + raise ConflictException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 422: + raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +class ConflictException(ApiException): + """Exception for HTTP 409 Conflict.""" + pass + + +class UnprocessableEntityException(ApiException): + """Exception for HTTP 422 Unprocessable Entity.""" + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/packages/continue-sdk/clients/python/openapi_client/models/__init__.py b/packages/continue-sdk/clients/python/openapi_client/models/__init__.py new file mode 100644 index 000000000..a26380850 --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/models/__init__.py @@ -0,0 +1,20 @@ +# coding: utf-8 + +# flake8: noqa +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult +from openapi_client.models.list_assistants401_response import ListAssistants401Response +from openapi_client.models.list_assistants404_response import ListAssistants404Response diff --git a/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner.py b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner.py new file mode 100644 index 000000000..ed0b8b316 --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult +from typing import Optional, Set +from typing_extensions import Self + +class ListAssistants200ResponseInner(BaseModel): + """ + ListAssistants200ResponseInner + """ # noqa: E501 + config_result: ListAssistants200ResponseInnerConfigResult = Field(alias="configResult") + owner_slug: StrictStr = Field(description="Slug of the user or organization that owns the assistant", alias="ownerSlug") + package_slug: StrictStr = Field(description="Slug of the assistant package", alias="packageSlug") + icon_url: Optional[StrictStr] = Field(default=None, description="Pre-signed URL for the assistant's icon", alias="iconUrl") + on_prem_proxy_url: Optional[StrictStr] = Field(default=None, description="URL of the on-premises proxy if the organization uses one", alias="onPremProxyUrl") + use_on_prem_proxy: Optional[StrictBool] = Field(default=None, description="Whether the organization uses an on-premises proxy", alias="useOnPremProxy") + raw_yaml: Optional[StrictStr] = Field(default=None, description="Raw YAML configuration of the assistant", alias="rawYaml") + __properties: ClassVar[List[str]] = ["configResult", "ownerSlug", "packageSlug", "iconUrl", "onPremProxyUrl", "useOnPremProxy", "rawYaml"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListAssistants200ResponseInner from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of config_result + if self.config_result: + _dict['configResult'] = self.config_result.to_dict() + # set to None if icon_url (nullable) is None + # and model_fields_set contains the field + if self.icon_url is None and "icon_url" in self.model_fields_set: + _dict['iconUrl'] = None + + # set to None if on_prem_proxy_url (nullable) is None + # and model_fields_set contains the field + if self.on_prem_proxy_url is None and "on_prem_proxy_url" in self.model_fields_set: + _dict['onPremProxyUrl'] = None + + # set to None if use_on_prem_proxy (nullable) is None + # and model_fields_set contains the field + if self.use_on_prem_proxy is None and "use_on_prem_proxy" in self.model_fields_set: + _dict['useOnPremProxy'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListAssistants200ResponseInner from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "configResult": ListAssistants200ResponseInnerConfigResult.from_dict(obj["configResult"]) if obj.get("configResult") is not None else None, + "ownerSlug": obj.get("ownerSlug"), + "packageSlug": obj.get("packageSlug"), + "iconUrl": obj.get("iconUrl"), + "onPremProxyUrl": obj.get("onPremProxyUrl"), + "useOnPremProxy": obj.get("useOnPremProxy"), + "rawYaml": obj.get("rawYaml") + }) + return _obj + + diff --git a/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner_config_result.py b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner_config_result.py new file mode 100644 index 000000000..8f0a7d7bc --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants200_response_inner_config_result.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ListAssistants200ResponseInnerConfigResult(BaseModel): + """ + ListAssistants200ResponseInnerConfigResult + """ # noqa: E501 + config: Optional[Dict[str, Any]] = Field(description="The unrolled assistant configuration") + config_load_interrupted: StrictBool = Field(description="Whether the configuration loading was interrupted", alias="configLoadInterrupted") + errors: Optional[List[StrictStr]] = Field(default=None, description="Any errors that occurred during configuration loading") + __properties: ClassVar[List[str]] = ["config", "configLoadInterrupted", "errors"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListAssistants200ResponseInnerConfigResult from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if config (nullable) is None + # and model_fields_set contains the field + if self.config is None and "config" in self.model_fields_set: + _dict['config'] = None + + # set to None if errors (nullable) is None + # and model_fields_set contains the field + if self.errors is None and "errors" in self.model_fields_set: + _dict['errors'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListAssistants200ResponseInnerConfigResult from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "config": obj.get("config"), + "configLoadInterrupted": obj.get("configLoadInterrupted"), + "errors": obj.get("errors") + }) + return _obj + + diff --git a/packages/continue-sdk/clients/python/openapi_client/models/list_assistants401_response.py b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants401_response.py new file mode 100644 index 000000000..7efba035a --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants401_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ListAssistants401Response(BaseModel): + """ + ListAssistants401Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListAssistants401Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListAssistants401Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/clients/python/openapi_client/models/list_assistants404_response.py b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants404_response.py new file mode 100644 index 000000000..ee76c899f --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/models/list_assistants404_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ListAssistants404Response(BaseModel): + """ + ListAssistants404Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListAssistants404Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListAssistants404Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/clients/python/openapi_client/py.typed b/packages/continue-sdk/clients/python/openapi_client/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/packages/continue-sdk/clients/python/openapi_client/rest.py b/packages/continue-sdk/clients/python/openapi_client/rest.py new file mode 100644 index 000000000..e6df2f74b --- /dev/null +++ b/packages/continue-sdk/clients/python/openapi_client/rest.py @@ -0,0 +1,258 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from openapi_client.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + "ca_cert_data": configuration.ca_cert_data, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/packages/continue-sdk/clients/python/pyproject.toml b/packages/continue-sdk/clients/python/pyproject.toml new file mode 100644 index 000000000..296bf8525 --- /dev/null +++ b/packages/continue-sdk/clients/python/pyproject.toml @@ -0,0 +1,89 @@ +[tool.poetry] +name = "openapi_client" +version = "1.0.0" +description = "Continue Hub IDE API" +authors = ["Continue Dev Team "] +license = "NoLicense" +readme = "README.md" +repository = "https://github.com/GIT_USER_ID/GIT_REPO_ID" +keywords = ["OpenAPI", "OpenAPI-Generator", "Continue Hub IDE API"] +include = ["openapi_client/py.typed"] + +[tool.poetry.dependencies] +python = "^3.8" + +urllib3 = ">= 1.25.3, < 3.0.0" +python-dateutil = ">= 2.8.2" +pydantic = ">= 2" +typing-extensions = ">= 4.7.1" + +[tool.poetry.dev-dependencies] +pytest = ">= 7.2.1" +pytest-cov = ">= 2.8.1" +tox = ">= 3.9.0" +flake8 = ">= 4.0.0" +types-python-dateutil = ">= 2.8.19.14" +mypy = ">= 1.5" + + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.pylint.'MESSAGES CONTROL'] +extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "openapi_client", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +extra_checks = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true + +[[tool.mypy.overrides]] +module = [ + "openapi_client.configuration", +] +warn_unused_ignores = true +strict_equality = true +extra_checks = true +check_untyped_defs = true +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true +disallow_untyped_calls = true +disallow_incomplete_defs = true +disallow_untyped_defs = true +no_implicit_reexport = true +warn_return_any = true diff --git a/packages/continue-sdk/clients/python/requirements.txt b/packages/continue-sdk/clients/python/requirements.txt new file mode 100644 index 000000000..67f7f68df --- /dev/null +++ b/packages/continue-sdk/clients/python/requirements.txt @@ -0,0 +1,4 @@ +urllib3 >= 1.25.3, < 3.0.0 +python_dateutil >= 2.8.2 +pydantic >= 2 +typing-extensions >= 4.7.1 diff --git a/packages/continue-sdk/clients/python/setup.cfg b/packages/continue-sdk/clients/python/setup.cfg new file mode 100644 index 000000000..11433ee87 --- /dev/null +++ b/packages/continue-sdk/clients/python/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/packages/continue-sdk/clients/python/setup.py b/packages/continue-sdk/clients/python/setup.py new file mode 100644 index 000000000..8a59f05f4 --- /dev/null +++ b/packages/continue-sdk/clients/python/setup.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "openapi-client" +VERSION = "1.0.0" +PYTHON_REQUIRES = ">= 3.8" +REQUIRES = [ + "urllib3 >= 1.25.3, < 3.0.0", + "python-dateutil >= 2.8.2", + "pydantic >= 2", + "typing-extensions >= 4.7.1", +] + +setup( + name=NAME, + version=VERSION, + description="Continue Hub IDE API", + author="Continue Dev Team", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "Continue Hub IDE API"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + long_description_content_type='text/markdown', + long_description="""\ + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + """, # noqa: E501 + package_data={"openapi_client": ["py.typed"]}, +) \ No newline at end of file diff --git a/packages/continue-sdk/clients/python/test-requirements.txt b/packages/continue-sdk/clients/python/test-requirements.txt new file mode 100644 index 000000000..e98555c11 --- /dev/null +++ b/packages/continue-sdk/clients/python/test-requirements.txt @@ -0,0 +1,6 @@ +pytest >= 7.2.1 +pytest-cov >= 2.8.1 +tox >= 3.9.0 +flake8 >= 4.0.0 +types-python-dateutil >= 2.8.19.14 +mypy >= 1.5 diff --git a/packages/continue-sdk/clients/python/test/__init__.py b/packages/continue-sdk/clients/python/test/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/continue-sdk/clients/python/test/test_default_api.py b/packages/continue-sdk/clients/python/test/test_default_api.py new file mode 100644 index 000000000..79f2be356 --- /dev/null +++ b/packages/continue-sdk/clients/python/test/test_default_api.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from api.default_api import DefaultApi + + +class TestDefaultApi(unittest.TestCase): + """DefaultApi unit test stubs""" + + def setUp(self) -> None: + self.api = DefaultApi() + + def tearDown(self) -> None: + pass + + def test_list_assistants(self) -> None: + """Test case for list_assistants + + List assistants for IDE + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner.py b/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner.py new file mode 100644 index 000000000..ce69a70b2 --- /dev/null +++ b/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner + +class TestListAssistants200ResponseInner(unittest.TestCase): + """ListAssistants200ResponseInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListAssistants200ResponseInner: + """Test ListAssistants200ResponseInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListAssistants200ResponseInner` + """ + model = ListAssistants200ResponseInner() + if include_optional: + return ListAssistants200ResponseInner( + config_result = openapi_client.models.list_assistants_200_response_inner_config_result.listAssistants_200_response_inner_configResult( + config = openapi_client.models.config.config(), + config_load_interrupted = True, + errors = [ + '' + ], ), + owner_slug = '', + package_slug = '', + icon_url = '', + on_prem_proxy_url = '', + use_on_prem_proxy = True, + raw_yaml = '' + ) + else: + return ListAssistants200ResponseInner( + config_result = openapi_client.models.list_assistants_200_response_inner_config_result.listAssistants_200_response_inner_configResult( + config = openapi_client.models.config.config(), + config_load_interrupted = True, + errors = [ + '' + ], ), + owner_slug = '', + package_slug = '', + ) + """ + + def testListAssistants200ResponseInner(self): + """Test ListAssistants200ResponseInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner_config_result.py b/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner_config_result.py new file mode 100644 index 000000000..59652e538 --- /dev/null +++ b/packages/continue-sdk/clients/python/test/test_list_assistants200_response_inner_config_result.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult + +class TestListAssistants200ResponseInnerConfigResult(unittest.TestCase): + """ListAssistants200ResponseInnerConfigResult unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListAssistants200ResponseInnerConfigResult: + """Test ListAssistants200ResponseInnerConfigResult + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListAssistants200ResponseInnerConfigResult` + """ + model = ListAssistants200ResponseInnerConfigResult() + if include_optional: + return ListAssistants200ResponseInnerConfigResult( + config = None, + config_load_interrupted = True, + errors = [ + '' + ] + ) + else: + return ListAssistants200ResponseInnerConfigResult( + config = None, + config_load_interrupted = True, + ) + """ + + def testListAssistants200ResponseInnerConfigResult(self): + """Test ListAssistants200ResponseInnerConfigResult""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/clients/python/test/test_list_assistants401_response.py b/packages/continue-sdk/clients/python/test/test_list_assistants401_response.py new file mode 100644 index 000000000..1cfe70b0a --- /dev/null +++ b/packages/continue-sdk/clients/python/test/test_list_assistants401_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_assistants401_response import ListAssistants401Response + +class TestListAssistants401Response(unittest.TestCase): + """ListAssistants401Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListAssistants401Response: + """Test ListAssistants401Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListAssistants401Response` + """ + model = ListAssistants401Response() + if include_optional: + return ListAssistants401Response( + message = 'Unauthorized' + ) + else: + return ListAssistants401Response( + ) + """ + + def testListAssistants401Response(self): + """Test ListAssistants401Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/clients/python/test/test_list_assistants404_response.py b/packages/continue-sdk/clients/python/test/test_list_assistants404_response.py new file mode 100644 index 000000000..275abbb90 --- /dev/null +++ b/packages/continue-sdk/clients/python/test/test_list_assistants404_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_assistants404_response import ListAssistants404Response + +class TestListAssistants404Response(unittest.TestCase): + """ListAssistants404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListAssistants404Response: + """Test ListAssistants404Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListAssistants404Response` + """ + model = ListAssistants404Response() + if include_optional: + return ListAssistants404Response( + message = 'User not found' + ) + else: + return ListAssistants404Response( + ) + """ + + def testListAssistants404Response(self): + """Test ListAssistants404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/clients/python/tox.ini b/packages/continue-sdk/clients/python/tox.ini new file mode 100644 index 000000000..1a9028b78 --- /dev/null +++ b/packages/continue-sdk/clients/python/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=openapi_client diff --git a/packages/continue-sdk/clients/typescript/.gitignore b/packages/continue-sdk/clients/typescript/.gitignore new file mode 100644 index 000000000..149b57654 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/packages/continue-sdk/clients/typescript/.npmignore b/packages/continue-sdk/clients/typescript/.npmignore new file mode 100644 index 000000000..42061c01a --- /dev/null +++ b/packages/continue-sdk/clients/typescript/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/packages/continue-sdk/clients/typescript/.openapi-generator-ignore b/packages/continue-sdk/clients/typescript/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/packages/continue-sdk/clients/typescript/.openapi-generator/FILES b/packages/continue-sdk/clients/typescript/.openapi-generator/FILES new file mode 100644 index 000000000..cdc461082 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/.openapi-generator/FILES @@ -0,0 +1,16 @@ +.gitignore +.npmignore +.openapi-generator-ignore +README.md +package.json +src/apis/DefaultApi.ts +src/apis/index.ts +src/index.ts +src/models/ListAssistants200ResponseInner.ts +src/models/ListAssistants200ResponseInnerConfigResult.ts +src/models/ListAssistants401Response.ts +src/models/ListAssistants404Response.ts +src/models/index.ts +src/runtime.ts +tsconfig.esm.json +tsconfig.json diff --git a/packages/continue-sdk/clients/typescript/.openapi-generator/VERSION b/packages/continue-sdk/clients/typescript/.openapi-generator/VERSION new file mode 100644 index 000000000..5f84a81db --- /dev/null +++ b/packages/continue-sdk/clients/typescript/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.12.0 diff --git a/packages/continue-sdk/clients/typescript/README.md b/packages/continue-sdk/clients/typescript/README.md new file mode 100644 index 000000000..4f436550b --- /dev/null +++ b/packages/continue-sdk/clients/typescript/README.md @@ -0,0 +1,46 @@ +## @continuedev/sdk@0.0.1 + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)) + +### Building + +To build and compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### Publishing + +First build the package then run `npm publish` + +### Consuming + +navigate to the folder of your consuming project and run one of the following commands. + +_published:_ + +``` +npm install @continuedev/sdk@0.0.1 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save +``` diff --git a/packages/continue-sdk/clients/typescript/package.json b/packages/continue-sdk/clients/typescript/package.json new file mode 100644 index 000000000..5c2f9e642 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/package.json @@ -0,0 +1,21 @@ +{ + "name": "@continuedev/sdk", + "version": "0.0.1", + "description": "OpenAPI client for @continuedev/sdk", + "author": "OpenAPI-Generator", + "repository": { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + }, + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "module": "./dist/esm/index.js", + "sideEffects": false, + "scripts": { + "build": "tsc && tsc -p tsconfig.esm.json", + "prepare": "npm run build" + }, + "devDependencies": { + "typescript": "^4.0 || ^5.0" + } +} diff --git a/packages/continue-sdk/clients/typescript/src/apis/DefaultApi.ts b/packages/continue-sdk/clients/typescript/src/apis/DefaultApi.ts new file mode 100644 index 000000000..b5d93c0ed --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/apis/DefaultApi.ts @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import type { + ListAssistants200ResponseInner, + ListAssistants401Response, + ListAssistants404Response, +} from '../models/index'; +import { + ListAssistants200ResponseInnerFromJSON, + ListAssistants200ResponseInnerToJSON, + ListAssistants401ResponseFromJSON, + ListAssistants401ResponseToJSON, + ListAssistants404ResponseFromJSON, + ListAssistants404ResponseToJSON, +} from '../models/index'; + +export interface ListAssistantsRequest { + alwaysUseProxy?: ListAssistantsAlwaysUseProxyEnum; + organizationId?: string; +} + +/** + * DefaultApi - interface + * + * @export + * @interface DefaultApiInterface + */ +export interface DefaultApiInterface { + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * @summary List assistants for IDE + * @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests + * @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>>; + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + listAssistants(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + +} + +/** + * + */ +export class DefaultApi extends runtime.BaseAPI implements DefaultApiInterface { + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + async listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + const queryParameters: any = {}; + + if (requestParameters['alwaysUseProxy'] != null) { + queryParameters['alwaysUseProxy'] = requestParameters['alwaysUseProxy']; + } + + if (requestParameters['organizationId'] != null) { + queryParameters['organizationId'] = requestParameters['organizationId']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/list-assistants`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(ListAssistants200ResponseInnerFromJSON)); + } + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + async listAssistants(requestParameters: ListAssistantsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.listAssistantsRaw(requestParameters, initOverrides); + return await response.value(); + } + +} + +/** + * @export + */ +export const ListAssistantsAlwaysUseProxyEnum = { + TRUE: 'true', + FALSE: 'false' +} as const; +export type ListAssistantsAlwaysUseProxyEnum = typeof ListAssistantsAlwaysUseProxyEnum[keyof typeof ListAssistantsAlwaysUseProxyEnum]; diff --git a/packages/continue-sdk/clients/typescript/src/apis/index.ts b/packages/continue-sdk/clients/typescript/src/apis/index.ts new file mode 100644 index 000000000..69c44c00f --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/apis/index.ts @@ -0,0 +1,3 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './DefaultApi'; diff --git a/packages/continue-sdk/clients/typescript/src/index.ts b/packages/continue-sdk/clients/typescript/src/index.ts new file mode 100644 index 000000000..bebe8bbbe --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/index.ts @@ -0,0 +1,5 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './runtime'; +export * from './apis/index'; +export * from './models/index'; diff --git a/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInner.ts b/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInner.ts new file mode 100644 index 000000000..9f572de3e --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInner.ts @@ -0,0 +1,124 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ListAssistants200ResponseInnerConfigResult } from './ListAssistants200ResponseInnerConfigResult'; +import { + ListAssistants200ResponseInnerConfigResultFromJSON, + ListAssistants200ResponseInnerConfigResultFromJSONTyped, + ListAssistants200ResponseInnerConfigResultToJSON, + ListAssistants200ResponseInnerConfigResultToJSONTyped, +} from './ListAssistants200ResponseInnerConfigResult'; + +/** + * + * @export + * @interface ListAssistants200ResponseInner + */ +export interface ListAssistants200ResponseInner { + /** + * + * @type {ListAssistants200ResponseInnerConfigResult} + * @memberof ListAssistants200ResponseInner + */ + configResult: ListAssistants200ResponseInnerConfigResult; + /** + * Slug of the user or organization that owns the assistant + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + ownerSlug: string; + /** + * Slug of the assistant package + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + packageSlug: string; + /** + * Pre-signed URL for the assistant's icon + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + iconUrl?: string | null; + /** + * URL of the on-premises proxy if the organization uses one + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + onPremProxyUrl?: string | null; + /** + * Whether the organization uses an on-premises proxy + * @type {boolean} + * @memberof ListAssistants200ResponseInner + */ + useOnPremProxy?: boolean | null; + /** + * Raw YAML configuration of the assistant + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + rawYaml?: string; +} + +/** + * Check if a given object implements the ListAssistants200ResponseInner interface. + */ +export function instanceOfListAssistants200ResponseInner(value: object): value is ListAssistants200ResponseInner { + if (!('configResult' in value) || value['configResult'] === undefined) return false; + if (!('ownerSlug' in value) || value['ownerSlug'] === undefined) return false; + if (!('packageSlug' in value) || value['packageSlug'] === undefined) return false; + return true; +} + +export function ListAssistants200ResponseInnerFromJSON(json: any): ListAssistants200ResponseInner { + return ListAssistants200ResponseInnerFromJSONTyped(json, false); +} + +export function ListAssistants200ResponseInnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInner { + if (json == null) { + return json; + } + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultFromJSON(json['configResult']), + 'ownerSlug': json['ownerSlug'], + 'packageSlug': json['packageSlug'], + 'iconUrl': json['iconUrl'] == null ? undefined : json['iconUrl'], + 'onPremProxyUrl': json['onPremProxyUrl'] == null ? undefined : json['onPremProxyUrl'], + 'useOnPremProxy': json['useOnPremProxy'] == null ? undefined : json['useOnPremProxy'], + 'rawYaml': json['rawYaml'] == null ? undefined : json['rawYaml'], + }; +} + +export function ListAssistants200ResponseInnerToJSON(json: any): ListAssistants200ResponseInner { + return ListAssistants200ResponseInnerToJSONTyped(json, false); +} + +export function ListAssistants200ResponseInnerToJSONTyped(value?: ListAssistants200ResponseInner | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultToJSON(value['configResult']), + 'ownerSlug': value['ownerSlug'], + 'packageSlug': value['packageSlug'], + 'iconUrl': value['iconUrl'], + 'onPremProxyUrl': value['onPremProxyUrl'], + 'useOnPremProxy': value['useOnPremProxy'], + 'rawYaml': value['rawYaml'], + }; +} + diff --git a/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInnerConfigResult.ts b/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInnerConfigResult.ts new file mode 100644 index 000000000..fd2e6ea8c --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/models/ListAssistants200ResponseInnerConfigResult.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ListAssistants200ResponseInnerConfigResult + */ +export interface ListAssistants200ResponseInnerConfigResult { + /** + * The unrolled assistant configuration + * @type {object} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + config: object | null; + /** + * Whether the configuration loading was interrupted + * @type {boolean} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + configLoadInterrupted: boolean; + /** + * Any errors that occurred during configuration loading + * @type {Array} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + errors?: Array | null; +} + +/** + * Check if a given object implements the ListAssistants200ResponseInnerConfigResult interface. + */ +export function instanceOfListAssistants200ResponseInnerConfigResult(value: object): value is ListAssistants200ResponseInnerConfigResult { + if (!('config' in value) || value['config'] === undefined) return false; + if (!('configLoadInterrupted' in value) || value['configLoadInterrupted'] === undefined) return false; + return true; +} + +export function ListAssistants200ResponseInnerConfigResultFromJSON(json: any): ListAssistants200ResponseInnerConfigResult { + return ListAssistants200ResponseInnerConfigResultFromJSONTyped(json, false); +} + +export function ListAssistants200ResponseInnerConfigResultFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInnerConfigResult { + if (json == null) { + return json; + } + return { + + 'config': json['config'], + 'configLoadInterrupted': json['configLoadInterrupted'], + 'errors': json['errors'] == null ? undefined : json['errors'], + }; +} + +export function ListAssistants200ResponseInnerConfigResultToJSON(json: any): ListAssistants200ResponseInnerConfigResult { + return ListAssistants200ResponseInnerConfigResultToJSONTyped(json, false); +} + +export function ListAssistants200ResponseInnerConfigResultToJSONTyped(value?: ListAssistants200ResponseInnerConfigResult | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'config': value['config'], + 'configLoadInterrupted': value['configLoadInterrupted'], + 'errors': value['errors'], + }; +} + diff --git a/packages/continue-sdk/clients/typescript/src/models/ListAssistants401Response.ts b/packages/continue-sdk/clients/typescript/src/models/ListAssistants401Response.ts new file mode 100644 index 000000000..a8d7d10b1 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/models/ListAssistants401Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ListAssistants401Response + */ +export interface ListAssistants401Response { + /** + * + * @type {string} + * @memberof ListAssistants401Response + */ + message?: string; +} + +/** + * Check if a given object implements the ListAssistants401Response interface. + */ +export function instanceOfListAssistants401Response(value: object): value is ListAssistants401Response { + return true; +} + +export function ListAssistants401ResponseFromJSON(json: any): ListAssistants401Response { + return ListAssistants401ResponseFromJSONTyped(json, false); +} + +export function ListAssistants401ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants401Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function ListAssistants401ResponseToJSON(json: any): ListAssistants401Response { + return ListAssistants401ResponseToJSONTyped(json, false); +} + +export function ListAssistants401ResponseToJSONTyped(value?: ListAssistants401Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/clients/typescript/src/models/ListAssistants404Response.ts b/packages/continue-sdk/clients/typescript/src/models/ListAssistants404Response.ts new file mode 100644 index 000000000..b90a21824 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/models/ListAssistants404Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ListAssistants404Response + */ +export interface ListAssistants404Response { + /** + * + * @type {string} + * @memberof ListAssistants404Response + */ + message?: string; +} + +/** + * Check if a given object implements the ListAssistants404Response interface. + */ +export function instanceOfListAssistants404Response(value: object): value is ListAssistants404Response { + return true; +} + +export function ListAssistants404ResponseFromJSON(json: any): ListAssistants404Response { + return ListAssistants404ResponseFromJSONTyped(json, false); +} + +export function ListAssistants404ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants404Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function ListAssistants404ResponseToJSON(json: any): ListAssistants404Response { + return ListAssistants404ResponseToJSONTyped(json, false); +} + +export function ListAssistants404ResponseToJSONTyped(value?: ListAssistants404Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/clients/typescript/src/models/index.ts b/packages/continue-sdk/clients/typescript/src/models/index.ts new file mode 100644 index 000000000..fe7e507e7 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/models/index.ts @@ -0,0 +1,6 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './ListAssistants200ResponseInner'; +export * from './ListAssistants200ResponseInnerConfigResult'; +export * from './ListAssistants401Response'; +export * from './ListAssistants404Response'; diff --git a/packages/continue-sdk/clients/typescript/src/runtime.ts b/packages/continue-sdk/clients/typescript/src/runtime.ts new file mode 100644 index 000000000..759761f32 --- /dev/null +++ b/packages/continue-sdk/clients/typescript/src/runtime.ts @@ -0,0 +1,431 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "https://api.continue.dev".replace(/\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | Promise | ((name: string) => string | Promise); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string | Promise) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + protected isJsonMime(mime: string | null | undefined): boolean { + if (!mime) { + return false; + } + return BaseAPI.jsonRegex.test(mime); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + let body: any; + if (isFormData(overriddenInit.body) + || (overriddenInit.body instanceof URLSearchParams) + || isBlob(overriddenInit.body)) { + body = overriddenInit.body; + } else if (this.isJsonMime(headers['Content-Type'])) { + body = JSON.stringify(overriddenInit.body); + } else { + body = overriddenInit.body; + } + + const init: RequestInit = { + ...overriddenInit, + body + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob; +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData; +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string; +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/packages/continue-sdk/clients/typescript/tsconfig.esm.json b/packages/continue-sdk/clients/typescript/tsconfig.esm.json new file mode 100644 index 000000000..2c0331cce --- /dev/null +++ b/packages/continue-sdk/clients/typescript/tsconfig.esm.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/esm" + } +} diff --git a/packages/continue-sdk/clients/typescript/tsconfig.json b/packages/continue-sdk/clients/typescript/tsconfig.json new file mode 100644 index 000000000..250280d9a --- /dev/null +++ b/packages/continue-sdk/clients/typescript/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "outDir": "dist", + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/packages/continue-sdk/openapi-generator-config.json b/packages/continue-sdk/openapi-generator-config.json new file mode 100644 index 000000000..c7600d13b --- /dev/null +++ b/packages/continue-sdk/openapi-generator-config.json @@ -0,0 +1,14 @@ +{ + "supportsES6": true, + "modelPropertyNaming": "camelCase", + "enumPropertyNaming": "UPPERCASE", + "apiPackage": "api", + "modelPackage": "models", + "npmName": "@continuedev/sdk", + "npmVersion": "0.0.1", + "withInterfaces": true, + "nullSafeAdditionalProps": true, + "typescriptThreePlus": true, + "useSingleRequestParameter": true, + "withSeparateModelsAndApi": true +} diff --git a/packages/continue-sdk/openapi.yaml b/packages/continue-sdk/openapi.yaml new file mode 100644 index 000000000..de3aee93e --- /dev/null +++ b/packages/continue-sdk/openapi.yaml @@ -0,0 +1,129 @@ +openapi: 3.0.0 +info: + title: Continue Hub IDE API + description: | + API for Continue IDE to fetch assistants and other related information. + These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + version: 1.0.0 + contact: + name: Continue Dev Team + url: https://continue.dev +servers: + - url: https://api.continue.dev + description: Production server + - url: http://localhost:3001 + description: Local development server +paths: + /ide/list-assistants: + get: + summary: List assistants for IDE + description: | + Returns a complete list of assistants available to the user, with their full configurations, + icons, and other metadata needed by the IDE to display and use them. + + This endpoint performs a full refresh of the list of assistants, including unrolling + configurations and resolving secrets. + operationId: listAssistants + parameters: + - name: alwaysUseProxy + in: query + description: Whether to always use the Continue-managed proxy for model requests + required: false + schema: + type: string + enum: ["true", "false"] + - name: organizationId + in: query + description: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + required: false + schema: + type: string + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully retrieved assistants + content: + application/json: + schema: + type: array + items: + type: object + required: + - configResult + - ownerSlug + - packageSlug + properties: + configResult: + type: object + required: + - config + - configLoadInterrupted + properties: + config: + type: object + description: The unrolled assistant configuration + nullable: true + configLoadInterrupted: + type: boolean + description: Whether the configuration loading was interrupted + errors: + type: array + items: + type: string + nullable: true + description: Any errors that occurred during configuration loading + ownerSlug: + type: string + description: Slug of the user or organization that owns the assistant + packageSlug: + type: string + description: Slug of the assistant package + iconUrl: + type: string + nullable: true + description: Pre-signed URL for the assistant's icon + onPremProxyUrl: + type: string + nullable: true + description: URL of the on-premises proxy if the organization uses one + useOnPremProxy: + type: boolean + nullable: true + description: Whether the organization uses an on-premises proxy + rawYaml: + type: string + description: Raw YAML configuration of the assistant + "401": + description: Unauthorized - Authentication failed + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Unauthorized" + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" + +components: + securitySchemes: + apiKeyAuth: + type: http + scheme: bearer + description: | + API Key Authentication + + API keys must be prefixed with "con_" and provided in the Authorization header. + Example: `Authorization: Bearer con_your_api_key_here` + + API keys can be generated in the Continue Hub web interface under account settings. diff --git a/packages/continue-sdk/openapitools.json b/packages/continue-sdk/openapitools.json new file mode 100644 index 000000000..6f7db3e8f --- /dev/null +++ b/packages/continue-sdk/openapitools.json @@ -0,0 +1,7 @@ +{ + "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "7.12.0" + } +} diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json new file mode 100644 index 000000000..6250f87d2 --- /dev/null +++ b/packages/continue-sdk/package-lock.json @@ -0,0 +1,2443 @@ +{ + "name": "@continuedev/sdk", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@continuedev/sdk", + "version": "0.0.1", + "license": "Apache-2.0", + "dependencies": { + "@openapitools/openapi-generator-cli": "^2.19.1", + "express": "^4.18.2", + "js-yaml": "^4.1.0", + "swagger-ui-express": "^5.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz", + "integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@lukeed/csprng": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", + "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/@nestjs/axios": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz", + "integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==", + "peerDependencies": { + "@nestjs/common": "^10.0.0 || ^11.0.0", + "axios": "^1.3.1", + "rxjs": "^7.0.0" + } + }, + "node_modules/@nestjs/common": { + "version": "11.0.20", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.20.tgz", + "integrity": "sha512-/GH8NDCczjn6+6RNEtSNAts/nq/wQE8L1qZ9TRjqjNqEsZNE1vpFuRIhmcO2isQZ0xY5rySnpaRdrOAul3gQ3A==", + "dependencies": { + "file-type": "20.4.1", + "iterare": "1.2.1", + "load-esm": "1.0.2", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "class-transformer": "*", + "class-validator": "*", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/core": { + "version": "11.0.20", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.0.20.tgz", + "integrity": "sha512-yUkEzBGiRNSEThVl6vMCXgoA9sDGWoRbJsTLdYdCC7lg7PE1iXBnna1FiBfQjT995pm0fjyM1e3WsXmyWeJXbw==", + "hasInstallScript": true, + "dependencies": { + "@nuxt/opencollective": "0.4.1", + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.2.0", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^11.0.0", + "@nestjs/microservices": "^11.0.0", + "@nestjs/platform-express": "^11.0.0", + "@nestjs/websockets": "^11.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nuxt/opencollective": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz", + "integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==", + "dependencies": { + "consola": "^3.2.3" + }, + "bin": { + "opencollective": "bin/opencollective.js" + }, + "engines": { + "node": "^14.18.0 || >=16.10.0", + "npm": ">=5.10.0" + } + }, + "node_modules/@nuxtjs/opencollective": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz", + "integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==", + "dependencies": { + "chalk": "^4.1.0", + "consola": "^2.15.0", + "node-fetch": "^2.6.1" + }, + "bin": { + "opencollective": "bin/opencollective.js" + }, + "engines": { + "node": ">=8.0.0", + "npm": ">=5.0.0" + } + }, + "node_modules/@nuxtjs/opencollective/node_modules/consola": { + "version": "2.15.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", + "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==" + }, + "node_modules/@openapitools/openapi-generator-cli": { + "version": "2.19.1", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.19.1.tgz", + "integrity": "sha512-APP3EPI/m7bg220qS+7UAFiyLJFbNCjlsEEjrP2sLmW4Za44U8e3Lb2zDy3sbvJvIUnpYWe+hu9RbrxrPP9djQ==", + "hasInstallScript": true, + "dependencies": { + "@nestjs/axios": "4.0.0", + "@nestjs/common": "11.0.20", + "@nestjs/core": "11.0.20", + "@nuxtjs/opencollective": "0.3.2", + "axios": "1.8.4", + "chalk": "4.1.2", + "commander": "8.3.0", + "compare-versions": "4.1.4", + "concurrently": "6.5.1", + "console.table": "0.10.0", + "fs-extra": "11.3.0", + "glob": "9.3.5", + "inquirer": "8.2.6", + "lodash": "4.17.21", + "proxy-agent": "6.5.0", + "reflect-metadata": "0.2.2", + "rxjs": "7.8.2", + "tslib": "2.8.1" + }, + "bin": { + "openapi-generator-cli": "main.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/openapi_generator" + } + }, + "node_modules/@scarf/scarf": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz", + "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==", + "hasInstallScript": true + }, + "node_modules/@tokenizer/inflate": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", + "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "dependencies": { + "debug": "^4.4.0", + "fflate": "^0.8.2", + "token-types": "^6.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" + }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", + "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==" + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/ast-types": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", + "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", + "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/basic-ftp": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", + "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", + "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/compare-versions": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-4.1.4.tgz", + "integrity": "sha512-FemMreK9xNyL8gQevsdRMrvO4lFCkQP7qbuktn1q8ndcNk1+0mz7lgE7b/sNvbhVgY4w6tMN1FDp6aADjqw2rw==" + }, + "node_modules/concurrently": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.5.1.tgz", + "integrity": "sha512-FlSwNpGjWQfRwPLXvJ/OgysbBxPkWpiVjy1042b0U7on7S7qwwMIILRj7WTN1mTgqa582bG6NFuScOoh6Zgdag==", + "dependencies": { + "chalk": "^4.1.0", + "date-fns": "^2.16.1", + "lodash": "^4.17.21", + "rxjs": "^6.6.3", + "spawn-command": "^0.0.2-1", + "supports-color": "^8.1.0", + "tree-kill": "^1.2.2", + "yargs": "^16.2.0" + }, + "bin": { + "concurrently": "bin/concurrently.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/concurrently/node_modules/rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "dependencies": { + "tslib": "^1.9.0" + }, + "engines": { + "npm": ">=2.0.0" + } + }, + "node_modules/concurrently/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/console.table": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/console.table/-/console.table-0.10.0.tgz", + "integrity": "sha512-dPyZofqggxuvSf7WXvNjuRfnsOk1YazkVP8FdxH4tcH2c37wc79/Yl6Bhr7Lsu00KMgy2ql/qCMuNu8xctZM8g==", + "dependencies": { + "easy-table": "1.1.0" + }, + "engines": { + "node": "> 0.10" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/date-fns": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", + "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==", + "dependencies": { + "@babel/runtime": "^7.21.0" + }, + "engines": { + "node": ">=0.11" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/date-fns" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/defaults": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", + "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", + "dependencies": { + "clone": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/degenerator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", + "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/easy-table": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz", + "integrity": "sha512-oq33hWOSSnl2Hoh00tZWaIPi1ievrD9aFG82/IgjlycAnW9hHx5PkJiXpxPsgEE+H7BsbVQXFVFST8TEXS6/pA==", + "optionalDependencies": { + "wcwidth": ">=1.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "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/escodegen": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", + "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/express/node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==" + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/file-type": { + "version": "20.4.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz", + "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", + "dependencies": { + "@tokenizer/inflate": "^0.2.6", + "strtok3": "^10.2.0", + "token-types": "^6.0.0", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", + "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-extra": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz", + "integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-uri": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz", + "integrity": "sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/glob": { + "version": "9.3.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", + "integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "minimatch": "^8.0.2", + "minipass": "^4.2.4", + "path-scurry": "^1.6.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/inquirer": { + "version": "8.2.6", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.6.tgz", + "integrity": "sha512-M1WuAmb7pn9zdFRtQYk26ZBoY043Sse0wVDdk4Bppr+JOXyQYybdtvK+l9wUibhtjdjvtoiNy8tk+EgsYIUqKg==", + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.5.5", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6", + "wrap-ansi": "^6.0.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/ip-address": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", + "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", + "dependencies": { + "jsbn": "1.1.0", + "sprintf-js": "^1.1.3" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/iterare": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", + "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", + "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==" + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/load-esm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.2.tgz", + "integrity": "sha512-nVAvWk/jeyrWyXEAs84mpQCYccxRqgKY4OznLuJhJCa0XsPSfdOIr2zvBZEj3IHEHbX97jjscKRRV539bW0Gpw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "engines": { + "node": ">=13.2.0" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-8.0.4.tgz", + "integrity": "sha512-W0Wvr9HyFXZRGIDgCicunpQ299OKXs9RgZfaukz4qAW/pJhcpUfupc9c+OObPOFueNy8VSrZgEmDtk6Kh4WzDA==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", + "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/netmask": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", + "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pac-proxy-agent": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.6", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", + "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/path-to-regexp": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", + "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "engines": { + "node": ">=16" + } + }, + "node_modules/peek-readable": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-7.0.0.tgz", + "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-agent": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", + "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.6", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.1.0", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==" + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.4", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.4.tgz", + "integrity": "sha512-D3YaD0aRxR3mEcqnidIs7ReYJFVzWdd6fXJYUM8ixcQcJRGTka/b3saV0KflYhyVJXKhb947GndU35SxYNResQ==", + "dependencies": { + "ip-address": "^9.0.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/spawn-command": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2.tgz", + "integrity": "sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==" + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==" + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strtok3": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", + "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/swagger-ui-dist": { + "version": "5.21.0", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.21.0.tgz", + "integrity": "sha512-E0K3AB6HvQd8yQNSMR7eE5bk+323AUxjtCz/4ZNKiahOlPhPJxqn3UPIGs00cyY/dhrTDJ61L7C/a8u6zhGrZg==", + "dependencies": { + "@scarf/scarf": "=1.4.0" + } + }, + "node_modules/swagger-ui-express": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-5.0.1.tgz", + "integrity": "sha512-SrNU3RiBGTLLmFU8GIJdOdanJTl4TOmT27tt3bWWHppqYmAZ6IDuEuBvMU6nZq0zLEe6b/1rACXCgLZqO6ZfrA==", + "dependencies": { + "swagger-ui-dist": ">=5.0.0" + }, + "engines": { + "node": ">= v0.10.32" + }, + "peerDependencies": { + "express": ">=4.0.0 || >=5.0.0-beta" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/token-types": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", + "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/uid": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", + "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "dependencies": { + "@lukeed/csprng": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/uint8array-extras": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz", + "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "engines": { + "node": ">=10" + } + } + } +} diff --git a/packages/continue-sdk/package.json b/packages/continue-sdk/package.json new file mode 100644 index 000000000..cebac4474 --- /dev/null +++ b/packages/continue-sdk/package.json @@ -0,0 +1,20 @@ +{ + "name": "@continuedev/sdk", + "version": "0.0.1", + "description": "SDK for Continue.dev", + "type": "module", + "scripts": { + "generate-client:typescript": "openapi-generator-cli generate -i ./openapi.yaml -g typescript-fetch -o ./clients/typescript -c ./openapi-generator-config.json", + "generate-client:python": "openapi-generator-cli generate -i ./openapi.yaml -g python -o ./clients/python -c ./openapi-generator-config.json", + "generate-client:ALL": "npm run generate-client:typescript && npm run generate-client:python", + "swagger-ui": "node swagger-ui-server.js" + }, + "author": "Continue Dev, Inc.", + "license": "Apache-2.0", + "dependencies": { + "@openapitools/openapi-generator-cli": "^2.19.1", + "express": "^4.18.2", + "js-yaml": "^4.1.0", + "swagger-ui-express": "^5.0.0" + } +} diff --git a/packages/continue-sdk/swagger-ui-server.js b/packages/continue-sdk/swagger-ui-server.js new file mode 100644 index 000000000..62395b536 --- /dev/null +++ b/packages/continue-sdk/swagger-ui-server.js @@ -0,0 +1,43 @@ +// This is a simple Express server to serve Swagger UI +import express from "express"; +import fs from "fs"; +import yaml from "js-yaml"; +import path from "path"; +import swaggerUi from "swagger-ui-express"; +import { fileURLToPath } from "url"; + +// ES Module handling for __dirname +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Read the OpenAPI spec +const openApiYaml = fs.readFileSync( + path.join(__dirname, "openapi.yaml"), + "utf8", +); +const openApiSpec = yaml.load(openApiYaml); + +const app = express(); +const port = process.env.PORT || 3002; + +// Serve the Swagger UI at the root URL +app.use( + "/", + swaggerUi.serve, + swaggerUi.setup(openApiSpec, { + explorer: true, + customCss: ".swagger-ui .topbar { display: none }", + swaggerOptions: { + docExpansion: "list", // or 'full' or 'none' + filter: true, + showExtensions: true, + showCommonExtensions: true, + }, + }), +); + +// Start the server +app.listen(port, () => { + console.log(`Swagger UI is running at http://localhost:${port}`); + console.log(`Press Ctrl+C to stop the server`); +}); diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1fa921da5..08d52d3b9 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -16,6 +16,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { @@ -4356,6 +4357,18 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 478b50f0d..82ba2509b 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -19,6 +19,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index c17527674..23b3af58d 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -14,6 +14,7 @@ import { Model, } from "openai/resources/index"; +import { v4 as uuidv4 } from "uuid"; import { GeminiConfig } from "../types.js"; import { chatChunk, @@ -21,7 +22,12 @@ import { customFetch, embedding, } from "../util.js"; -import { GeminiToolFunctionDeclaration } from "../util/gemini-types.js"; +import { + convertOpenAIToolToGeminiFunction, + GeminiChatContent, + GeminiChatContentPart, + GeminiToolFunctionDeclaration, +} from "../util/gemini-types.js"; import { BaseLlmApi, CreateRerankResponse, @@ -48,9 +54,15 @@ export class GeminiApi implements BaseLlmApi { } private _oaiPartToGeminiPart( - part: OpenAI.Chat.Completions.ChatCompletionContentPart, - ) { + part: + | OpenAI.Chat.Completions.ChatCompletionContentPart + | OpenAI.Chat.Completions.ChatCompletionContentPartRefusal, + ): GeminiChatContentPart { switch (part.type) { + case "refusal": + return { + text: part.refusal, + }; case "text": return { text: part.text, @@ -88,21 +100,30 @@ export class GeminiApi implements BaseLlmApi { const isV1API = url.includes("/v1/"); const toolCallIdToNameMap = new Map(); - const contents = oaiBody.messages + oaiBody.messages.forEach((msg) => { + if (msg.role === "assistant" && msg.tool_calls) { + msg.tool_calls.forEach((call) => { + toolCallIdToNameMap.set(call.id, call.function.name); + }); + } + }); + + const contents: (GeminiChatContent | null)[] = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } - if (msg.role == "assistant" && msg.tool_calls?.length) { + if (msg.role === "assistant" && msg.tool_calls?.length) { for (const toolCall of msg.tool_calls) { toolCallIdToNameMap.set(toolCall.id, toolCall.function.name); } return { - role: "model", + role: "model" as const, parts: msg.tool_calls.map((toolCall) => ({ functionCall: { + id: toolCall.id, name: toolCall.function.name, args: JSON.parse(toolCall.function.arguments || "{}"), }, @@ -111,14 +132,15 @@ export class GeminiApi implements BaseLlmApi { } if (msg.role === "tool") { + const functionName = toolCallIdToNameMap.get(msg.tool_call_id); return { - role: "user", + role: "user" as const, parts: [ { functionResponse: { - name: msg.tool_call_id, + id: msg.tool_call_id, + name: functionName ?? "unknown", response: { - name: toolCallIdToNameMap.get(msg.tool_call_id), content: typeof msg.content === "string" ? msg.content @@ -135,12 +157,12 @@ export class GeminiApi implements BaseLlmApi { } return { - role: msg.role === "assistant" ? "model" : "user", + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), parts: typeof msg.content === "string" ? [{ text: msg.content }] - : // @ts-ignore - msg.content.map(this._oaiPartToGeminiPart), + : msg.content.map(this._oaiPartToGeminiPart), }; }) .filter((c) => c !== null); @@ -149,7 +171,7 @@ export class GeminiApi implements BaseLlmApi { const finalBody: any = { generationConfig, contents, - // if this.systemMessage is defined, reformat it for Gemini API + // if there is a system message, reformat it for Gemini API ...(sysMsg && !isV1API && { systemInstruction: { parts: [{ text: sysMsg.content }] }, @@ -164,71 +186,15 @@ export class GeminiApi implements BaseLlmApi { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; oaiBody.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: (tool.function.parameters as any)?.type?.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertOpenAIToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); + if (functions.length) { finalBody.tools = [ { @@ -336,7 +302,7 @@ export class GeminiApi implements BaseLlmApi { tool_calls: [ { index: 0, - id: "", // Not supported by Gemini + id: part.functionCall.id ?? uuidv4(), type: "function", function: { name: part.functionCall.name, diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index ab72a85b1..745b94186 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -37,18 +37,23 @@ export class OpenAIApi implements BaseLlmApi { modifyChatBody(body: T): T { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; - if (isOfficialOpenAIAPI && body.model.startsWith("o")) { - // a) use max_completion_tokens instead of max_tokens - body.max_completion_tokens = body.max_tokens; - body.max_tokens = undefined; + if (isOfficialOpenAIAPI) { + if (body.model.startsWith("o")) { + // a) use max_completion_tokens instead of max_tokens + body.max_completion_tokens = body.max_tokens; + body.max_tokens = undefined; - // b) use "developer" message role rather than "system" - body.messages = body.messages.map((message) => { - if (message.role === "system") { - return { ...message, role: "developer" } as any; - } - return message; - }); + // b) use "developer" message role rather than "system" + body.messages = body.messages.map((message) => { + if (message.role === "system") { + return { ...message, role: "developer" } as any; + } + return message; + }); + } + if (body.tools?.length && !body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; } diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index b9fb52c1d..44f752f40 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { ChatCompletionTool } from "openai/resources/index.mjs"; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,70 +17,225 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; } +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertOpenAIToolToGeminiFunction( + tool: ChatCompletionTool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; +} + +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; @@ -88,7 +244,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index 7120e8c5d..a580c9015 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -61,13 +61,18 @@ setup_node_version echo "Installing root-level dependencies..." npm install +echo "Building config-yaml..." +pushd packages/config-yaml +npm install +npm run build +popd + echo "Installing Core extension dependencies..." pushd core ## This flag is set because we pull down Chromium at runtime export PUPPETEER_SKIP_DOWNLOAD='true' npm install npm link - popd echo "Installing GUI extension dependencies..." @@ -75,7 +80,6 @@ pushd gui npm install npm link @continuedev/core npm run build - popd # VSCode Extension (will also package GUI) @@ -86,18 +90,15 @@ npm install npm link @continuedev/core npm run prepackage npm run package - popd echo "Installing binary dependencies..." pushd binary npm install npm run build - popd echo "Installing docs dependencies..." pushd docs npm install - popd