Changesets · Branches · Tags · Compare
| Changeset | 93be46abab09d83a95f572d18b9b27dcaeaa350e220a6cb0f2dafd09e8e7266f |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-09-22 13:45 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-22 13:45 -07:00 |
| Parents | 00c2dcd72a7c, 23e5f6ffdfa7 |
More than 300 files changed
deleted .claude/lint-check.sh +0 −20
| @@ -1,20 +0,0 @@ | ||
| 1 | -#!/bin/bash | |
| 2 | - | |
| 3 | -# Get file path from hook input | |
| 4 | -FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1) | |
| 5 | - | |
| 6 | -# Function to run lint and typecheck | |
| 7 | -run_checks() { | |
| 8 | - local dir=$1 | |
| 9 | - cd "$dir" | |
| 10 | - npm run lint >&2 && npm run tsc:check >&2 | |
| 11 | -} | |
| 12 | - | |
| 13 | -# Run checks based on file location | |
| 14 | -if [[ "$FILE_PATH" == *"/core/"* ]]; then | |
| 15 | - run_checks core | |
| 16 | -elif [[ "$FILE_PATH" == *"/gui/"* ]]; then | |
| 17 | - run_checks gui | |
| 18 | -elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then | |
| 19 | - run_checks extensions/vscode | |
| 20 | -fi | |
| No newline at the end of the file |
deleted .claude/settings.json +0 −15
| @@ -1,15 +0,0 @@ | ||
| 1 | -{ | |
| 2 | - "hooks": { | |
| 3 | - "PostToolUse": [ | |
| 4 | - { | |
| 5 | - "matcher": "Write|Edit|MultiEdit", | |
| 6 | - "hooks": [ | |
| 7 | - { | |
| 8 | - "type": "command", | |
| 9 | - "command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh" | |
| 10 | - } | |
| 11 | - ] | |
| 12 | - } | |
| 13 | - ] | |
| 14 | - } | |
| 15 | -} |
modified .continue/prompts/update-llm-info.prompt +1 −1
| @@ -52,7 +52,7 @@ | ||
| 52 | 52 | // TODO: add info for openai, ollama, etc |
| 53 | 53 | |
| 54 | 54 | For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement. |
| 55 | -Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored. | |
| 55 | +Generally, ignore models that do not support text output. These models will be used in a coding agent client that only supports text/image input and text/output, so extraneous capabilities can be ignored. | |
| 56 | 56 | Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained. |
| 57 | 57 | |
| 58 | 58 | 3. UPDATE THE INFORMATION |
added .continue/rules/no-any-types.md +5 −0
| @@ -0,0 +1,5 @@ | ||
| 1 | +--- | |
| 2 | +globs: "**/*.{ts,tsx}" | |
| 3 | +--- | |
| 4 | + | |
| 5 | +Avoid using the `any` type wherever possible. Use unknown or find the correct type. The only acceptable place to use any is when typecasting for test mocks, and even then it's better to avoid and provide a proper mock. |
modified .github/ISSUE_TEMPLATE/bug_report.yml +2 −2
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | - **Continue version**: v0.9.4 |
| 30 | 30 | - **IDE version**: VSCode 1.85.1 |
| 31 | 31 | - Model: Claude Sonnet 3.5 |
| 32 | - - Assistant configuration | |
| 32 | + - Agent configuration | |
| 33 | 33 | value: | |
| 34 | 34 | - OS: |
| 35 | 35 | - Continue version: |
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | ```yaml |
| 40 | 40 | |
| 41 | 41 | ``` |
| 42 | - OR link to assistant in Continue hub: | |
| 42 | + OR link to agent in Continue hub: | |
| 43 | 43 | render: Markdown |
| 44 | 44 | validations: |
| 45 | 45 | required: false |
added .github/actions/check-llm-changes/action.yml +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +name: "Check LLM Changes" | |
| 2 | +description: "Check if LLM-related files have changed and set environment variable to control API tests" | |
| 3 | +outputs: | |
| 4 | + llm_changed: | |
| 5 | + description: "Whether LLM-related files have changed" | |
| 6 | + value: ${{ steps.check-changes.outputs.llm_changed }} | |
| 7 | + ignore_api_tests: | |
| 8 | + description: "Whether to ignore API tests based on file changes and other conditions" | |
| 9 | + value: ${{ steps.check-changes.outputs.ignore_api_tests }} | |
| 10 | +inputs: | |
| 11 | + is_fork: | |
| 12 | + description: "Whether this is a fork PR" | |
| 13 | + required: false | |
| 14 | + default: "false" | |
| 15 | + is_dependabot: | |
| 16 | + description: "Whether this is a dependabot PR" | |
| 17 | + required: false | |
| 18 | + default: "false" | |
| 19 | + | |
| 20 | +runs: | |
| 21 | + using: "composite" | |
| 22 | + steps: | |
| 23 | + - name: Check if LLM-related files changed | |
| 24 | + id: check-changes | |
| 25 | + shell: bash | |
| 26 | + run: | | |
| 27 | + if [ "${{ github.event_name }}" = "push" ]; then | |
| 28 | + # For push events, compare against the previous commit | |
| 29 | + CHANGED_FILES=$(git diff --name-only HEAD~1...HEAD) | |
| 30 | + else | |
| 31 | + # For PR events, compare against the base branch | |
| 32 | + git fetch origin ${{ github.event.pull_request.base.ref }} | |
| 33 | + CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }}...HEAD) | |
| 34 | + fi | |
| 35 | + | |
| 36 | + echo "Changed files:" | |
| 37 | + echo "$CHANGED_FILES" | |
| 38 | + | |
| 39 | + # Check if any LLM-related files were changed | |
| 40 | + LLM_CHANGED=false | |
| 41 | + if echo "$CHANGED_FILES" | grep -E "(^core/llm/|^core/index\.ts|^core/package\.json|^core/jest\.config\.js|^packages/.*/(.*llm.*|.*openai.*|.*anthropic.*)|\.github/workflows/pr-checks\.yaml|\.github/actions/check-llm-changes/)" > /dev/null; then | |
| 42 | + LLM_CHANGED=true | |
| 43 | + fi | |
| 44 | + | |
| 45 | + echo "LLM files changed: $LLM_CHANGED" | |
| 46 | + echo "llm_changed=$LLM_CHANGED" >> $GITHUB_OUTPUT | |
| 47 | + | |
| 48 | + # Determine whether to ignore API tests | |
| 49 | + IGNORE_API_TESTS=false | |
| 50 | + if [ "${{ inputs.is_fork }}" = "true" ] || [ "${{ inputs.is_dependabot }}" = "true" ] || [ "$LLM_CHANGED" = "false" ]; then | |
| 51 | + IGNORE_API_TESTS=true | |
| 52 | + fi | |
| 53 | + | |
| 54 | + echo "Ignore API tests: $IGNORE_API_TESTS" | |
| 55 | + echo "ignore_api_tests=$IGNORE_API_TESTS" >> $GITHUB_OUTPUT |
modified .github/actions/run-jetbrains-tests/action.yml +20 −18
| @@ -44,6 +44,7 @@ | ||
| 44 | 44 | - name: Setup FFmpeg |
| 45 | 45 | uses: AnimMouse/setup-ffmpeg@v1 |
| 46 | 46 | with: |
| 47 | + version: 7.1 | |
| 47 | 48 | token: ${{ inputs.github-token }} |
| 48 | 49 | |
| 49 | 50 | - name: Setup Gradle |
| @@ -93,13 +94,20 @@ | ||
| 93 | 94 | path: binary/node_modules |
| 94 | 95 | key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} |
| 95 | 96 | |
| 97 | + - name: Install binary dependencies | |
| 98 | + if: steps.binary-cache.outputs.cache-hit != 'true' | |
| 99 | + shell: bash | |
| 100 | + run: | | |
| 101 | + cd binary | |
| 102 | + npm ci | |
| 103 | + | |
| 96 | 104 | - name: Build the binaries |
| 97 | 105 | shell: bash |
| 98 | 106 | run: | |
| 99 | 107 | cd binary |
| 100 | 108 | npm run build |
| 101 | 109 | |
| 102 | - - name: Start test IDE | |
| 110 | + - name: Run tests | |
| 103 | 111 | shell: bash |
| 104 | 112 | run: | |
| 105 | 113 | cd extensions/intellij |
| @@ -107,35 +115,29 @@ | ||
| 107 | 115 | Xvfb -ac :99 -screen 0 1920x1080x24 & |
| 108 | 116 | sleep 10 |
| 109 | 117 | mkdir -p build/reports |
| 110 | - ./gradlew runIdeForUiTests & | |
| 111 | - | |
| 112 | - - name: Wait for JB connection | |
| 113 | - uses: jtalk/url-health-check-action@v3 | |
| 114 | - with: | |
| 115 | - url: http://127.0.0.1:8082 | |
| 116 | - max-attempts: 15 | |
| 117 | - retry-delay: 30s | |
| 118 | - | |
| 119 | - - name: Run tests | |
| 120 | - shell: bash | |
| 121 | - run: | | |
| 122 | - cd extensions/intellij | |
| 123 | - export DISPLAY=:99.0 | |
| 124 | - ./gradlew test | |
| 118 | + ./gradlew test testIntegration | |
| 125 | 119 | |
| 126 | 120 | - name: Move video |
| 127 | 121 | if: ${{ failure() }} |
| 128 | 122 | shell: bash |
| 129 | 123 | run: | |
| 130 | 124 | cd extensions/intellij |
| 131 | - mv video build/reports | |
| 125 | + if [ -d "video" ]; then | |
| 126 | + mv video build/reports | |
| 127 | + else | |
| 128 | + echo "No video directory found to move" | |
| 129 | + fi | |
| 132 | 130 | |
| 133 | 131 | - name: Copy logs |
| 134 | 132 | if: ${{ failure() }} |
| 135 | 133 | shell: bash |
| 136 | 134 | run: | |
| 137 | 135 | cd extensions/intellij |
| 138 | - mv build/idea-sandbox/system/log/ build/reports | |
| 136 | + if [ -d "build/idea-sandbox/system/log/" ]; then | |
| 137 | + mv build/idea-sandbox/system/log/ build/reports | |
| 138 | + else | |
| 139 | + echo "No log directory found to copy" | |
| 140 | + fi | |
| 139 | 141 | |
| 140 | 142 | - name: Save fails report |
| 141 | 143 | if: ${{ failure() }} |
modified .github/actions/run-vscode-e2e-test/action.yml +11 −10
| @@ -1,25 +1,25 @@ | ||
| 1 | -name: 'Run VS Code E2E Test' | |
| 2 | -description: 'Run a single VS Code E2E test with all required setup' | |
| 1 | +name: "Run VS Code E2E Test" | |
| 2 | +description: "Run a single VS Code E2E test with all required setup" | |
| 3 | 3 | inputs: |
| 4 | 4 | test_file: |
| 5 | - description: 'E2E test file to run' | |
| 5 | + description: "E2E test file to run" | |
| 6 | 6 | required: true |
| 7 | 7 | command: |
| 8 | - description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)' | |
| 8 | + description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)" | |
| 9 | 9 | required: true |
| 10 | 10 | ssh_key: |
| 11 | - description: 'SSH private key for testing' | |
| 11 | + description: "SSH private key for testing" | |
| 12 | 12 | required: false |
| 13 | 13 | ssh_host: |
| 14 | - description: 'SSH host for testing' | |
| 14 | + description: "SSH host for testing" | |
| 15 | 15 | required: false |
| 16 | 16 | is_fork: |
| 17 | - description: 'Whether this is a fork (affects SSH tests)' | |
| 17 | + description: "Whether this is a fork (affects SSH tests)" | |
| 18 | 18 | required: false |
| 19 | - default: 'false' | |
| 19 | + default: "false" | |
| 20 | 20 | |
| 21 | 21 | runs: |
| 22 | - using: 'composite' | |
| 22 | + using: "composite" | |
| 23 | 23 | steps: |
| 24 | 24 | - uses: actions/setup-node@v4 |
| 25 | 25 | with: |
| @@ -58,6 +58,7 @@ | ||
| 58 | 58 | cd core |
| 59 | 59 | npm ci |
| 60 | 60 | cd ../extensions/vscode |
| 61 | + npm ci | |
| 61 | 62 | npm run e2e:ci:download |
| 62 | 63 | else |
| 63 | 64 | cd core |
| @@ -131,4 +132,4 @@ | ||
| 131 | 132 | uses: actions/upload-artifact@v4 |
| 132 | 133 | with: |
| 133 | 134 | name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} |
| 134 | - path: extensions/vscode/e2e.log | |
| No newline at the end of the file | ||
| 135 | + path: extensions/vscode/e2e.log |
added .github/actions/track-rerun/action.yml +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +name: Track Workflow Rerun | |
| 2 | +description: Track when GitHub Actions workflows are rerun (attempt > 1) | |
| 3 | + | |
| 4 | +runs: | |
| 5 | + using: composite | |
| 6 | + steps: | |
| 7 | + # Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.) | |
| 8 | + - name: Track workflow rerun | |
| 9 | + if: github.run_attempt > 1 | |
| 10 | + shell: bash | |
| 11 | + run: | | |
| 12 | + echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}" | |
| 13 | + echo "📊 Workflow: ${{ github.workflow }}" | |
| 14 | + echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}" | |
| 15 | + echo "📝 Commit: ${{ github.sha }}" | |
| 16 | + echo "👤 Actor: ${{ github.actor }}" | |
| 17 | + echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 18 | + echo "" | |
| 19 | + echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'" |
added .github/workflows/auto-fix-failed-tests.yml +170 −0
| @@ -0,0 +1,170 @@ | ||
| 1 | +name: Auto Fix Failed Tests | |
| 2 | + | |
| 3 | +on: | |
| 4 | + workflow_run: | |
| 5 | + workflows: ["PR Checks", "CLI PR Checks"] | |
| 6 | + types: | |
| 7 | + - completed | |
| 8 | + | |
| 9 | +permissions: | |
| 10 | + contents: write | |
| 11 | + pull-requests: write | |
| 12 | + issues: write | |
| 13 | + actions: read | |
| 14 | + | |
| 15 | +jobs: | |
| 16 | + fix-failed-tests: | |
| 17 | + # Only run if the workflow failed | |
| 18 | + # DISABLED: Remove 'false && ' on the next line to enable auto-fixing | |
| 19 | + if: false && github.event.workflow_run.conclusion == 'failure' | |
| 20 | + runs-on: ubuntu-latest | |
| 21 | + | |
| 22 | + steps: | |
| 23 | + - name: Get workflow run details | |
| 24 | + id: workflow-details | |
| 25 | + uses: actions/github-script@v8 | |
| 26 | + with: | |
| 27 | + script: | | |
| 28 | + const workflowRun = context.payload.workflow_run; | |
| 29 | + const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({ | |
| 30 | + owner: context.repo.owner, | |
| 31 | + repo: context.repo.repo, | |
| 32 | + run_id: workflowRun.id | |
| 33 | + }); | |
| 34 | + | |
| 35 | + // Find all failed jobs since we're only monitoring specific test workflows | |
| 36 | + const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure'); | |
| 37 | + | |
| 38 | + if (failedJobs.length === 0) { | |
| 39 | + core.info('No failed jobs found'); | |
| 40 | + return null; | |
| 41 | + } | |
| 42 | + | |
| 43 | + core.setOutput('has_failed_tests', 'true'); | |
| 44 | + core.setOutput('workflow_name', workflowRun.name); | |
| 45 | + core.setOutput('workflow_run_id', workflowRun.id); | |
| 46 | + core.setOutput('head_branch', workflowRun.head_branch); | |
| 47 | + core.setOutput('head_sha', workflowRun.head_sha); | |
| 48 | + core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name))); | |
| 49 | + | |
| 50 | + return failedJobs; | |
| 51 | + | |
| 52 | + - name: Get job logs for failed tests | |
| 53 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 54 | + id: get-logs | |
| 55 | + uses: actions/github-script@v8 | |
| 56 | + with: | |
| 57 | + script: | | |
| 58 | + const workflowRunId = ${{ github.event.workflow_run.id }}; | |
| 59 | + const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({ | |
| 60 | + owner: context.repo.owner, | |
| 61 | + repo: context.repo.repo, | |
| 62 | + run_id: workflowRunId | |
| 63 | + }); | |
| 64 | + | |
| 65 | + let errorLogs = ''; | |
| 66 | + | |
| 67 | + for (const job of jobs.jobs) { | |
| 68 | + if (job.conclusion === 'failure') { | |
| 69 | + try { | |
| 70 | + const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({ | |
| 71 | + owner: context.repo.owner, | |
| 72 | + repo: context.repo.repo, | |
| 73 | + job_id: job.id | |
| 74 | + }); | |
| 75 | + | |
| 76 | + errorLogs += `\n\n=== Job: ${job.name} ===\n`; | |
| 77 | + errorLogs += logData; | |
| 78 | + } catch (error) { | |
| 79 | + core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`); | |
| 80 | + } | |
| 81 | + } | |
| 82 | + } | |
| 83 | + | |
| 84 | + // Store logs in environment file for next step | |
| 85 | + const fs = require('fs'); | |
| 86 | + fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs); | |
| 87 | + | |
| 88 | + core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false'); | |
| 89 | + | |
| 90 | + - name: Checkout repository | |
| 91 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 92 | + uses: actions/checkout@v5 | |
| 93 | + with: | |
| 94 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 95 | + fetch-depth: 0 | |
| 96 | + ref: ${{ steps.workflow-details.outputs.head_sha }} | |
| 97 | + | |
| 98 | + - name: Setup Node.js | |
| 99 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 100 | + uses: actions/setup-node@v5 | |
| 101 | + with: | |
| 102 | + node-version: "20" | |
| 103 | + | |
| 104 | + - name: Install Continue CLI globally | |
| 105 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 106 | + run: npm i -g @continuedev/cli | |
| 107 | + | |
| 108 | + - name: Start remote session to fix failed tests | |
| 109 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 110 | + id: remote-session | |
| 111 | + env: | |
| 112 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 113 | + run: | | |
| 114 | + # Create a detailed prompt for fixing the failed tests | |
| 115 | + cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF' | |
| 116 | + 🔧 **Auto Test Fix Request** | |
| 117 | + | |
| 118 | + The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}): | |
| 119 | + | |
| 120 | + **Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }} | |
| 121 | + **Branch:** ${{ steps.workflow-details.outputs.head_branch }} | |
| 122 | + **Commit:** ${{ steps.workflow-details.outputs.head_sha }} | |
| 123 | + | |
| 124 | + **Your Task:** | |
| 125 | + 1. Analyze the test failure logs and error messages | |
| 126 | + 2. Identify the root cause of the test failures | |
| 127 | + 3. Fix the failing tests by updating the test code or the underlying implementation | |
| 128 | + 4. Ensure all tests pass after your changes | |
| 129 | + 5. Commit your fixes with a descriptive message | |
| 130 | + | |
| 131 | + **Test Failure Context:** | |
| 132 | + Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes. | |
| 133 | + | |
| 134 | + Focus on: | |
| 135 | + - Understanding what the tests are trying to validate | |
| 136 | + - Identifying why they're failing (code changes, environment issues, test logic errors) | |
| 137 | + - Making minimal, targeted fixes that address the root cause | |
| 138 | + - Ensuring the fixes don't break other functionality | |
| 139 | + | |
| 140 | + Please start by examining the failing tests and their error messages, then proceed with the necessary fixes. | |
| 141 | + PROMPT_EOF | |
| 142 | + | |
| 143 | + echo "Starting Continue CLI remote session for test fixes..." | |
| 144 | + echo "Prompt content:" | |
| 145 | + cat /tmp/fix_tests_prompt.txt | |
| 146 | + | |
| 147 | + # Start remote session and capture JSON output | |
| 148 | + SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }}) | |
| 149 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 150 | + | |
| 151 | + # Extract URL from JSON output | |
| 152 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 153 | + | |
| 154 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 155 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 156 | + exit 1 | |
| 157 | + fi | |
| 158 | + | |
| 159 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 160 | + echo "✅ Started remote session: $SESSION_URL" | |
| 161 | + | |
| 162 | + - name: Log session details | |
| 163 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 164 | + run: | | |
| 165 | + echo "✅ Successfully started auto-fix session for failed tests" | |
| 166 | + echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}" | |
| 167 | + echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}" | |
| 168 | + echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}" | |
| 169 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 170 | + echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}" |
added .github/workflows/beta-release.yml +115 −0
| @@ -0,0 +1,115 @@ | ||
| 1 | +name: Beta Release | |
| 2 | + | |
| 3 | +on: | |
| 4 | + schedule: | |
| 5 | + # Run every day at 9am UTC | |
| 6 | + - cron: "0 9 * * *" | |
| 7 | + workflow_dispatch: | |
| 8 | + # Allow manual triggering | |
| 9 | + | |
| 10 | +permissions: | |
| 11 | + contents: write | |
| 12 | + issues: write | |
| 13 | + pull-requests: write | |
| 14 | + | |
| 15 | +jobs: | |
| 16 | + beta-release: | |
| 17 | + name: Beta Release | |
| 18 | + runs-on: ubuntu-latest | |
| 19 | + steps: | |
| 20 | + - name: Checkout | |
| 21 | + uses: actions/checkout@v5 | |
| 22 | + with: | |
| 23 | + fetch-depth: 0 | |
| 24 | + token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} | |
| 25 | + | |
| 26 | + - name: Setup Node.js | |
| 27 | + uses: actions/setup-node@v5 | |
| 28 | + with: | |
| 29 | + node-version: 20 | |
| 30 | + registry-url: "https://registry.npmjs.org" | |
| 31 | + always-auth: true | |
| 32 | + | |
| 33 | + - name: Setup packages | |
| 34 | + uses: ./.github/actions/setup-packages | |
| 35 | + | |
| 36 | + - name: Setup core component | |
| 37 | + uses: ./.github/actions/setup-component | |
| 38 | + with: | |
| 39 | + component: core | |
| 40 | + include-root: true | |
| 41 | + | |
| 42 | + - name: Build core | |
| 43 | + run: | | |
| 44 | + cd core | |
| 45 | + npm run build | |
| 46 | + | |
| 47 | + - name: Install CLI dependencies | |
| 48 | + working-directory: extensions/cli | |
| 49 | + run: npm ci | |
| 50 | + env: | |
| 51 | + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 52 | + | |
| 53 | + - name: Get current version | |
| 54 | + id: get_version | |
| 55 | + working-directory: extensions/cli | |
| 56 | + run: | | |
| 57 | + # Get the latest version from package.json or npm registry | |
| 58 | + CURRENT_VERSION=$(node -p "require('./package.json').version") | |
| 59 | + if [[ "$CURRENT_VERSION" == "0.0.0-dev" ]]; then | |
| 60 | + # If it's dev version, get latest from npm registry | |
| 61 | + LATEST_VERSION=$(npm view @continuedev/cli version --silent 2>/dev/null || echo "0.0.0") | |
| 62 | + echo "Using latest npm version: $LATEST_VERSION" | |
| 63 | + CURRENT_VERSION=$LATEST_VERSION | |
| 64 | + fi | |
| 65 | + | |
| 66 | + # Create beta version with current date | |
| 67 | + DATE_SUFFIX=$(date -u +%Y%m%d) | |
| 68 | + BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}" | |
| 69 | + | |
| 70 | + # Check if this version already exists on npm | |
| 71 | + if npm view @continuedev/cli@$BETA_VERSION version --silent >/dev/null 2>&1; then | |
| 72 | + echo "Version $BETA_VERSION already exists, adding timestamp" | |
| 73 | + # Add hour and minute to make it unique | |
| 74 | + TIMESTAMP_SUFFIX=$(date -u +%Y%m%d.%H%M) | |
| 75 | + BETA_VERSION="${CURRENT_VERSION}-beta.${TIMESTAMP_SUFFIX}" | |
| 76 | + echo "Using timestamped version: $BETA_VERSION" | |
| 77 | + fi | |
| 78 | + | |
| 79 | + echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT | |
| 80 | + echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT | |
| 81 | + echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT | |
| 82 | + | |
| 83 | + - name: Update package.json for beta | |
| 84 | + working-directory: extensions/cli | |
| 85 | + run: | | |
| 86 | + # Update version in package.json | |
| 87 | + npm version ${{ steps.get_version.outputs.beta_version }} --no-git-tag-version | |
| 88 | + | |
| 89 | + - name: Build | |
| 90 | + working-directory: extensions/cli | |
| 91 | + run: npm run build | |
| 92 | + | |
| 93 | + - name: Publish beta to npm | |
| 94 | + working-directory: extensions/cli | |
| 95 | + env: | |
| 96 | + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 97 | + run: | | |
| 98 | + npm publish --tag beta | |
| 99 | + echo "Published beta version: ${{ steps.get_version.outputs.beta_version }}" | |
| 100 | + | |
| 101 | + - name: Create beta release on GitHub | |
| 102 | + env: | |
| 103 | + GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} | |
| 104 | + run: | | |
| 105 | + # Create a git tag for the beta | |
| 106 | + git config --local user.email "action@github.com" | |
| 107 | + git config --local user.name "GitHub Action" | |
| 108 | + git tag "v${{ steps.get_version.outputs.beta_version }}" | |
| 109 | + git push origin "v${{ steps.get_version.outputs.beta_version }}" | |
| 110 | + | |
| 111 | + # Create GitHub release | |
| 112 | + gh release create "v${{ steps.get_version.outputs.beta_version }}" \ | |
| 113 | + --title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \ | |
| 114 | + --notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \ | |
| 115 | + --prerelease |
modified .github/workflows/cla.yaml +1 −1
| @@ -27,5 +27,5 @@ | ||
| 27 | 27 | path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md" |
| 28 | 28 | branch: cla-signatures |
| 29 | 29 | # Bots and CLAs signed outside of GitHub |
| 30 | - allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline | |
| 30 | + allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev | |
| 31 | 31 | signed-commit-message: "CLA signed in $pullRequestNo" |
added .github/workflows/cli-pr-checks.yml +136 −0
| @@ -0,0 +1,136 @@ | ||
| 1 | +name: CLI PR Checks | |
| 2 | + | |
| 3 | +on: | |
| 4 | + pull_request: | |
| 5 | + branches: [main] | |
| 6 | + | |
| 7 | +permissions: | |
| 8 | + contents: read | |
| 9 | + pull-requests: write | |
| 10 | + issues: write | |
| 11 | + | |
| 12 | +jobs: | |
| 13 | + track-rerun: | |
| 14 | + runs-on: ubuntu-latest | |
| 15 | + if: github.run_attempt > 1 | |
| 16 | + steps: | |
| 17 | + - uses: actions/checkout@v5 | |
| 18 | + - name: Track workflow rerun | |
| 19 | + uses: ./.github/actions/track-rerun | |
| 20 | + | |
| 21 | + lint: | |
| 22 | + runs-on: ubuntu-latest | |
| 23 | + steps: | |
| 24 | + - name: Checkout code | |
| 25 | + uses: actions/checkout@v5 | |
| 26 | + | |
| 27 | + - name: Setup Node.js | |
| 28 | + uses: actions/setup-node@v5 | |
| 29 | + with: | |
| 30 | + node-version: 20 | |
| 31 | + cache: "npm" | |
| 32 | + cache-dependency-path: extensions/cli/package-lock.json | |
| 33 | + | |
| 34 | + - name: Setup packages | |
| 35 | + uses: ./.github/actions/setup-packages | |
| 36 | + - name: Setup core component | |
| 37 | + uses: ./.github/actions/setup-component | |
| 38 | + with: | |
| 39 | + component: core | |
| 40 | + include-root: true | |
| 41 | + | |
| 42 | + - name: Build core | |
| 43 | + run: | | |
| 44 | + cd core | |
| 45 | + npm run build | |
| 46 | + | |
| 47 | + - name: Install dependencies | |
| 48 | + run: | | |
| 49 | + cd extensions/cli | |
| 50 | + npm ci --include=optional | |
| 51 | + | |
| 52 | + - name: Run linting | |
| 53 | + run: | | |
| 54 | + cd extensions/cli | |
| 55 | + npm run lint | |
| 56 | + | |
| 57 | + test: | |
| 58 | + strategy: | |
| 59 | + matrix: | |
| 60 | + os: [ubuntu-latest, windows-latest, macos-latest] | |
| 61 | + node-version: [18, 20, 22, 24] | |
| 62 | + fail-fast: false | |
| 63 | + runs-on: ${{ matrix.os }} | |
| 64 | + | |
| 65 | + steps: | |
| 66 | + - name: Checkout code | |
| 67 | + uses: actions/checkout@v5 | |
| 68 | + | |
| 69 | + - name: Setup Node.js ${{ matrix.node-version }} | |
| 70 | + uses: actions/setup-node@v5 | |
| 71 | + with: | |
| 72 | + node-version: ${{ matrix.node-version }} | |
| 73 | + | |
| 74 | + - name: Cache CLI node_modules | |
| 75 | + uses: actions/cache@v4 | |
| 76 | + with: | |
| 77 | + path: extensions/cli/node_modules | |
| 78 | + key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }} | |
| 79 | + restore-keys: | | |
| 80 | + ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules- | |
| 81 | + | |
| 82 | + - name: Setup packages | |
| 83 | + uses: ./.github/actions/setup-packages | |
| 84 | + - name: Setup core component | |
| 85 | + uses: ./.github/actions/setup-component | |
| 86 | + with: | |
| 87 | + component: core | |
| 88 | + include-root: true | |
| 89 | + | |
| 90 | + - name: Build core | |
| 91 | + run: | | |
| 92 | + cd core | |
| 93 | + npm run build | |
| 94 | + | |
| 95 | + - name: Install dependencies | |
| 96 | + run: | | |
| 97 | + cd extensions/cli | |
| 98 | + npm ci --include=optional | |
| 99 | + | |
| 100 | + - name: Build | |
| 101 | + run: | | |
| 102 | + cd extensions/cli | |
| 103 | + npm run build | |
| 104 | + | |
| 105 | + - name: Run smoke tests | |
| 106 | + run: | | |
| 107 | + cd extensions/cli | |
| 108 | + npm run test:smoke | |
| 109 | + | |
| 110 | + - name: Run tests | |
| 111 | + run: | | |
| 112 | + cd extensions/cli | |
| 113 | + npm test | |
| 114 | + | |
| 115 | + # e2e tests are failing on Windows specifically - likely due to stdout flush issues | |
| 116 | + - name: Run e2e tests | |
| 117 | + if: matrix.os != 'windows-latest' | |
| 118 | + run: | | |
| 119 | + cd extensions/cli | |
| 120 | + npm run test:e2e | |
| 121 | + | |
| 122 | + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) | |
| 123 | + # This action at least lets us manage the list of required tests via source control | |
| 124 | + # so that creators of new jobs can add them to this list | |
| 125 | + require-all-checks-to-pass-cli: | |
| 126 | + if: always() | |
| 127 | + runs-on: ubuntu-latest | |
| 128 | + needs: | |
| 129 | + - lint | |
| 130 | + - test | |
| 131 | + | |
| 132 | + steps: | |
| 133 | + - name: Decide whether the needed jobs succeeded or failed | |
| 134 | + uses: re-actors/alls-green@release/v1 | |
| 135 | + with: | |
| 136 | + jobs: ${{ toJSON(needs) }} |
modified .github/workflows/compliance.yaml +3 −3
| @@ -36,12 +36,12 @@ | ||
| 36 | 36 | else |
| 37 | 37 | echo "❌ PR title does not follow conventional commit format" |
| 38 | 38 | echo "valid=false" >> $GITHUB_OUTPUT |
| 39 | - exit 1 | |
| 39 | + # Don't exit with failure - just mark as invalid for comment | |
| 40 | 40 | fi |
| 41 | 41 | |
| 42 | 42 | - name: Add PR title guidance comment |
| 43 | 43 | if: always() && steps.pr-title-check.outputs.valid == 'false' |
| 44 | - uses: actions/github-script@v7 | |
| 44 | + uses: actions/github-script@v8 | |
| 45 | 45 | with: |
| 46 | 46 | script: | |
| 47 | 47 | const { data: comments } = await github.rest.issues.listComments({ |
| @@ -104,7 +104,7 @@ | ||
| 104 | 104 | uses: actions/checkout@v5 |
| 105 | 105 | |
| 106 | 106 | - name: Setup Node.js |
| 107 | - uses: actions/setup-node@v4 | |
| 107 | + uses: actions/setup-node@v5 | |
| 108 | 108 | with: |
| 109 | 109 | node-version-file: ".nvmrc" |
| 110 | 110 | cache: "npm" |
modified .github/workflows/continue-detailed-review.yaml +1 −1
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | timeout-minutes: 10 |
| 19 | 19 | steps: |
| 20 | 20 | - name: Run Detailed PR Review |
| 21 | - uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070 | |
| 21 | + uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52 | |
| 22 | 22 | with: |
| 23 | 23 | continue-api-key: ${{ secrets.CONTINUE_API_KEY }} |
| 24 | 24 | continue-org: continuedev |
modified .github/workflows/continue-general-review.yaml +1 −1
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | timeout-minutes: 10 |
| 19 | 19 | steps: |
| 20 | 20 | - name: Run Continue PR Review Action |
| 21 | - uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070 | |
| 21 | + uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52 | |
| 22 | 22 | with: |
| 23 | 23 | continue-api-key: ${{ secrets.CONTINUE_API_KEY }} |
| 24 | 24 | continue-org: "continuedev" |
deleted .github/workflows/docs.yml +0 −32
| @@ -1,32 +0,0 @@ | ||
| 1 | -name: Docs Check | |
| 2 | - | |
| 3 | -on: | |
| 4 | - push: | |
| 5 | - paths: | |
| 6 | - - 'docs2/**' | |
| 7 | - pull_request: | |
| 8 | - paths: | |
| 9 | - - 'docs2/**' | |
| 10 | - | |
| 11 | -jobs: | |
| 12 | - check-broken-links: | |
| 13 | - runs-on: ubuntu-latest | |
| 14 | - | |
| 15 | - steps: | |
| 16 | - - name: Checkout repository | |
| 17 | - uses: actions/checkout@v5 | |
| 18 | - | |
| 19 | - - name: Setup Node.js | |
| 20 | - uses: actions/setup-node@v4 | |
| 21 | - with: | |
| 22 | - node-version: '18' | |
| 23 | - cache: 'npm' | |
| 24 | - cache-dependency-path: docs2/package-lock.json | |
| 25 | - | |
| 26 | - - name: Install dependencies | |
| 27 | - working-directory: ./docs2 | |
| 28 | - run: npm ci | |
| 29 | - | |
| 30 | - - name: Check for broken links | |
| 31 | - working-directory: ./docs2 | |
| 32 | - run: npx mintlify broken-links | |
| No newline at the end of the file |
modified .github/workflows/jetbrains-release.yaml +10 −12
| @@ -120,7 +120,7 @@ | ||
| 120 | 120 | |
| 121 | 121 | # # Set up Java environment for the next steps |
| 122 | 122 | - name: Setup Java |
| 123 | - uses: actions/setup-java@v4 | |
| 123 | + uses: actions/setup-java@v5 | |
| 124 | 124 | with: |
| 125 | 125 | distribution: zulu |
| 126 | 126 | java-version: 17 |
| @@ -152,7 +152,7 @@ | ||
| 152 | 152 | |
| 153 | 153 | # # Setup Node.js |
| 154 | 154 | - name: Use Node.js from .nvmrc |
| 155 | - uses: actions/setup-node@v4 | |
| 155 | + uses: actions/setup-node@v5 | |
| 156 | 156 | with: |
| 157 | 157 | node-version-file: ".nvmrc" |
| 158 | 158 | |
| @@ -189,6 +189,8 @@ | ||
| 189 | 189 | cd ../../gui |
| 190 | 190 | npm ci |
| 191 | 191 | npm run build |
| 192 | + env: | |
| 193 | + NODE_OPTIONS: "--max-old-space-size=8192" | |
| 192 | 194 | |
| 193 | 195 | # Run prepackage.js script |
| 194 | 196 | - name: Run prepackage script |
| @@ -255,6 +257,7 @@ | ||
| 255 | 257 | # Publish the plugin to JetBrains Marketplace |
| 256 | 258 | - name: Publish EAP Plugin |
| 257 | 259 | if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true') |
| 260 | + continue-on-error: true | |
| 258 | 261 | env: |
| 259 | 262 | PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} |
| 260 | 263 | CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} |
| @@ -265,6 +268,7 @@ | ||
| 265 | 268 | |
| 266 | 269 | - name: Publish Stable Plugin |
| 267 | 270 | if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true') |
| 271 | + continue-on-error: true | |
| 268 | 272 | env: |
| 269 | 273 | PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} |
| 270 | 274 | CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} |
| @@ -366,7 +370,7 @@ | ||
| 366 | 370 | |
| 367 | 371 | # 2. Install npm dependencies |
| 368 | 372 | - name: Use Node.js from .nvmrc |
| 369 | - uses: actions/setup-node@v4 | |
| 373 | + uses: actions/setup-node@v5 | |
| 370 | 374 | with: |
| 371 | 375 | node-version-file: ".nvmrc" |
| 372 | 376 | |
| @@ -433,7 +437,7 @@ | ||
| 433 | 437 | |
| 434 | 438 | # Set up Java environment for the next steps |
| 435 | 439 | - name: Setup Java |
| 436 | - uses: actions/setup-java@v4 | |
| 440 | + uses: actions/setup-java@v5 | |
| 437 | 441 | with: |
| 438 | 442 | distribution: zulu |
| 439 | 443 | java-version: 17 |
| @@ -456,12 +460,6 @@ | ||
| 456 | 460 | name: tests-result |
| 457 | 461 | path: ${{ github.workspace }}/extensions/intellij/build/reports/tests |
| 458 | 462 | |
| 459 | - # Upload the Kover report to CodeCov | |
| 460 | - # - name: Upload Code Coverage Report | |
| 461 | - # uses: codecov/codecov-action@v4 | |
| 462 | - # with: | |
| 463 | - # files: ${{ github.workspace }}/build/reports/kover/report.xml | |
| 464 | - | |
| 465 | 463 | # Run Qodana inspections and provide report |
| 466 | 464 | inspectCode: |
| 467 | 465 | if: false |
| @@ -486,7 +484,7 @@ | ||
| 486 | 484 | |
| 487 | 485 | # Set up Java environment for the next steps |
| 488 | 486 | - name: Setup Java |
| 489 | - uses: actions/setup-java@v4 | |
| 487 | + uses: actions/setup-java@v5 | |
| 490 | 488 | with: |
| 491 | 489 | distribution: zulu |
| 492 | 490 | java-version: 17 |
| @@ -517,7 +515,7 @@ | ||
| 517 | 515 | |
| 518 | 516 | # Set up Java environment for the next steps |
| 519 | 517 | - name: Setup Java |
| 520 | - uses: actions/setup-java@v4 | |
| 518 | + uses: actions/setup-java@v5 | |
| 521 | 519 | with: |
| 522 | 520 | distribution: zulu |
| 523 | 521 | java-version: 17 |
modified .github/workflows/label-merged-prs.yml +1 −1
| @@ -44,7 +44,7 @@ | ||
| 44 | 44 | |
| 45 | 45 | - name: Determine and apply tier label |
| 46 | 46 | if: steps.check-author.outputs.should_label == 'true' |
| 47 | - uses: actions/github-script@v7 | |
| 47 | + uses: actions/github-script@v8 | |
| 48 | 48 | with: |
| 49 | 49 | script: | |
| 50 | 50 | const pr = context.payload.pull_request; |
modified .github/workflows/main-build.yaml +9 −7
| @@ -24,17 +24,19 @@ | ||
| 24 | 24 | |
| 25 | 25 | - name: Get merged PR number |
| 26 | 26 | id: get-pr |
| 27 | + env: | |
| 28 | + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
| 27 | 29 | run: | |
| 28 | - # Get the commit message of the merge commit | |
| 29 | - COMMIT_MSG=$(git log --format=%B -n 1 HEAD) | |
| 30 | - echo "Commit message: $COMMIT_MSG" | |
| 30 | + # Get PR number for the current commit using GitHub API | |
| 31 | + COMMIT_SHA=$(git rev-parse HEAD) | |
| 32 | + echo "Getting PR for commit: $COMMIT_SHA" | |
| 31 | 33 | |
| 32 | - # Extract PR number from merge commit message (format: "Merge pull request #123 from...") | |
| 33 | - PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723") | |
| 34 | + PR_NUMBER=$(curl -s -H "Authorization: token $GH_TOKEN" \ | |
| 35 | + "https://api.github.com/repos/${{ github.repository }}/commits/$COMMIT_SHA/pulls" \ | |
| 36 | + | jq -r '.[0].number // empty') | |
| 34 | 37 | |
| 35 | 38 | if [ -z "$PR_NUMBER" ]; then |
| 36 | - echo "❌ Could not extract PR number from commit message. This might not be a PR merge." | |
| 37 | - echo "Commit message was: $COMMIT_MSG" | |
| 39 | + echo "❌ Could not find PR for commit $COMMIT_SHA" | |
| 38 | 40 | exit 1 |
| 39 | 41 | fi |
| 40 | 42 |
modified .github/workflows/main.yaml +3 −3
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | publish_build: |
| 10 | 10 | description: "Whether or not to publish the built extension to the VS Code marketplace" |
| 11 | 11 | required: true |
| 12 | - default: false | |
| 12 | + default: "false" | |
| 13 | 13 | |
| 14 | 14 | jobs: |
| 15 | 15 | check_release_name: |
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | - id: check |
| 21 | 21 | working-directory: . |
| 22 | 22 | run: | |
| 23 | - if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then | |
| 23 | + if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then | |
| 24 | 24 | echo "should_run=true" >> $GITHUB_OUTPUT |
| 25 | 25 | else |
| 26 | 26 | echo "should_run=false" >> $GITHUB_OUTPUT |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | with: |
| 71 | 71 | fetch-depth: 0 |
| 72 | 72 | |
| 73 | - - uses: actions/setup-node@v4 | |
| 73 | + - uses: actions/setup-node@v5 | |
| 74 | 74 | with: |
| 75 | 75 | node-version-file: ".nvmrc" |
| 76 | 76 |
modified .github/workflows/pr-checks.yaml +36 −5
| @@ -11,11 +11,19 @@ | ||
| 11 | 11 | - main |
| 12 | 12 | |
| 13 | 13 | jobs: |
| 14 | + track-rerun: | |
| 15 | + runs-on: ubuntu-latest | |
| 16 | + if: github.run_attempt > 1 | |
| 17 | + steps: | |
| 18 | + - uses: actions/checkout@v5 | |
| 19 | + - name: Track workflow rerun | |
| 20 | + uses: ./.github/actions/track-rerun | |
| 21 | + | |
| 14 | 22 | prettier-check: |
| 15 | 23 | runs-on: ubuntu-latest |
| 16 | 24 | steps: |
| 17 | 25 | - uses: actions/checkout@v5 |
| 18 | - - uses: actions/setup-node@v4 | |
| 26 | + - uses: actions/setup-node@v5 | |
| 19 | 27 | with: |
| 20 | 28 | node-version-file: ".nvmrc" |
| 21 | 29 | |
| @@ -36,6 +44,8 @@ | ||
| 36 | 44 | runs-on: ubuntu-latest |
| 37 | 45 | steps: |
| 38 | 46 | - uses: actions/checkout@v5 |
| 47 | + with: | |
| 48 | + fetch-depth: 0 # Needed for git diff to work | |
| 39 | 49 | - name: Setup packages |
| 40 | 50 | uses: ./.github/actions/setup-packages |
| 41 | 51 | - name: Setup core component |
| @@ -44,6 +54,13 @@ | ||
| 44 | 54 | component: core |
| 45 | 55 | include-root: true |
| 46 | 56 | |
| 57 | + - name: Check if LLM-related files changed | |
| 58 | + id: llm-changes | |
| 59 | + uses: ./.github/actions/check-llm-changes | |
| 60 | + with: | |
| 61 | + is_fork: ${{ github.event.pull_request.head.repo.fork == true }} | |
| 62 | + is_dependabot: ${{ github.actor == 'dependabot[bot]' }} | |
| 63 | + | |
| 47 | 64 | - name: Type check and lint |
| 48 | 65 | run: | |
| 49 | 66 | cd core |
| @@ -58,7 +75,7 @@ | ||
| 58 | 75 | npm test |
| 59 | 76 | npm run vitest |
| 60 | 77 | env: |
| 61 | - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} | |
| 78 | + IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }} | |
| 62 | 79 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} |
| 63 | 80 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} |
| 64 | 81 | GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} |
| @@ -67,6 +84,9 @@ | ||
| 67 | 84 | AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} |
| 68 | 85 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 69 | 86 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 87 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 88 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 89 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 70 | 90 | |
| 71 | 91 | gui-checks: |
| 72 | 92 | runs-on: ubuntu-latest |
| @@ -172,16 +192,25 @@ | ||
| 172 | 192 | package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }} |
| 173 | 193 | steps: |
| 174 | 194 | - uses: actions/checkout@v5 |
| 195 | + with: | |
| 196 | + fetch-depth: 0 # Needed for git diff to work | |
| 175 | 197 | - name: Setup packages |
| 176 | 198 | uses: ./.github/actions/setup-packages |
| 177 | 199 | |
| 200 | + - name: Check if LLM-related files changed | |
| 201 | + id: llm-changes | |
| 202 | + uses: ./.github/actions/check-llm-changes | |
| 203 | + with: | |
| 204 | + is_fork: ${{ github.event.pull_request.head.repo.fork == true }} | |
| 205 | + is_dependabot: ${{ github.actor == 'dependabot[bot]' }} | |
| 206 | + | |
| 178 | 207 | - name: Test and check ${{ matrix.package }} |
| 179 | 208 | run: | |
| 180 | 209 | cd packages/${{ matrix.package }} |
| 181 | 210 | npm ci |
| 182 | 211 | npm test |
| 183 | 212 | env: |
| 184 | - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} | |
| 213 | + IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }} | |
| 185 | 214 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} |
| 186 | 215 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} |
| 187 | 216 | GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} |
| @@ -191,6 +220,8 @@ | ||
| 191 | 220 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 192 | 221 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 193 | 222 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 223 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 224 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 194 | 225 | |
| 195 | 226 | vscode-get-test-file-matrix: |
| 196 | 227 | runs-on: ubuntu-latest |
| @@ -198,7 +229,7 @@ | ||
| 198 | 229 | test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} |
| 199 | 230 | steps: |
| 200 | 231 | - uses: actions/checkout@v5 |
| 201 | - - uses: actions/setup-node@v4 | |
| 232 | + - uses: actions/setup-node@v5 | |
| 202 | 233 | with: |
| 203 | 234 | node-version-file: ".nvmrc" |
| 204 | 235 | |
| @@ -316,7 +347,7 @@ | ||
| 316 | 347 | runs-on: ubuntu-latest |
| 317 | 348 | steps: |
| 318 | 349 | - uses: actions/checkout@v5 |
| 319 | - - uses: actions/setup-node@v4 | |
| 350 | + - uses: actions/setup-node@v5 | |
| 320 | 351 | with: |
| 321 | 352 | node-version: 20 |
| 322 | 353 |
modified .github/workflows/preview.yaml +4 −4
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | publish_build: |
| 10 | 10 | description: "Whether or not to publish the built extension to the VS Code marketplace" |
| 11 | 11 | required: true |
| 12 | - default: false | |
| 12 | + default: "false" | |
| 13 | 13 | |
| 14 | 14 | jobs: |
| 15 | 15 | check_release_name: |
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | - id: check |
| 21 | 21 | working-directory: . |
| 22 | 22 | run: | |
| 23 | - if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then | |
| 23 | + if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then | |
| 24 | 24 | echo "should_run=true" >> $GITHUB_OUTPUT |
| 25 | 25 | else |
| 26 | 26 | echo "should_run=false" >> $GITHUB_OUTPUT |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | with: |
| 71 | 71 | fetch-depth: 0 |
| 72 | 72 | |
| 73 | - - uses: actions/setup-node@v4 | |
| 73 | + - uses: actions/setup-node@v5 | |
| 74 | 74 | with: |
| 75 | 75 | node-version-file: ".nvmrc" |
| 76 | 76 | |
| @@ -165,7 +165,7 @@ | ||
| 165 | 165 | |
| 166 | 166 | # 4. Create PR with version bump |
| 167 | 167 | - name: Setup Node.js |
| 168 | - uses: actions/setup-node@v4 | |
| 168 | + uses: actions/setup-node@v5 | |
| 169 | 169 | with: |
| 170 | 170 | node-version-file: ".nvmrc" |
| 171 | 171 |
modified .github/workflows/release-config-yaml.yml +2 −0
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
modified .github/workflows/release-fetch.yml +2 −0
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
modified .github/workflows/release-llm-info.yml +4 −1
| @@ -23,4 +23,7 @@ | ||
| 23 | 23 | AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} |
| 24 | 24 | AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} |
| 25 | 25 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 26 | - AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| No newline at the end of the file | ||
| 26 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 27 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 28 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 29 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
modified .github/workflows/release-openai-adapters.yml +2 −0
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
added .github/workflows/respond-to-cubic.yaml +302 −0
| @@ -0,0 +1,302 @@ | ||
| 1 | +name: Respond to @continuedev Comments | |
| 2 | + | |
| 3 | +on: | |
| 4 | + issue_comment: | |
| 5 | + types: [created] | |
| 6 | + pull_request_review_comment: | |
| 7 | + types: [created] | |
| 8 | + | |
| 9 | +permissions: | |
| 10 | + contents: write | |
| 11 | + pull-requests: write | |
| 12 | + issues: write | |
| 13 | + | |
| 14 | +jobs: | |
| 15 | + respond-to-comment: | |
| 16 | + # Only run on pull request comments | |
| 17 | + if: github.event_name == 'issue_comment' && github.event.issue.pull_request | |
| 18 | + runs-on: ubuntu-latest | |
| 19 | + | |
| 20 | + steps: | |
| 21 | + - name: Check if comment contains @continuedev | |
| 22 | + id: check-mention | |
| 23 | + run: | | |
| 24 | + # Create a temporary file to safely handle comment body with special characters | |
| 25 | + cat > /tmp/comment.txt << 'COMMENT_EOF' | |
| 26 | + ${{ github.event.comment.body }} | |
| 27 | + COMMENT_EOF | |
| 28 | + | |
| 29 | + if grep -q "@continuedev" /tmp/comment.txt; then | |
| 30 | + echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 31 | + else | |
| 32 | + echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 33 | + fi | |
| 34 | + | |
| 35 | + - name: Add eyes reaction to comment | |
| 36 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 37 | + uses: actions/github-script@v8 | |
| 38 | + with: | |
| 39 | + script: | | |
| 40 | + await github.rest.reactions.createForIssueComment({ | |
| 41 | + owner: context.repo.owner, | |
| 42 | + repo: context.repo.repo, | |
| 43 | + comment_id: ${{ github.event.comment.id }}, | |
| 44 | + content: 'eyes' | |
| 45 | + }); | |
| 46 | + | |
| 47 | + - name: Checkout PR branch | |
| 48 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 49 | + uses: actions/checkout@v5 | |
| 50 | + with: | |
| 51 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 52 | + fetch-depth: 0 | |
| 53 | + | |
| 54 | + - name: Get PR information | |
| 55 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 56 | + id: pr-info | |
| 57 | + uses: actions/github-script@v8 | |
| 58 | + with: | |
| 59 | + script: | | |
| 60 | + const { data: pr } = await github.rest.pulls.get({ | |
| 61 | + owner: context.repo.owner, | |
| 62 | + repo: context.repo.repo, | |
| 63 | + pull_number: context.issue.number | |
| 64 | + }); | |
| 65 | + | |
| 66 | + core.setOutput('head_ref', pr.head.ref); | |
| 67 | + core.setOutput('head_sha', pr.head.sha); | |
| 68 | + return pr; | |
| 69 | + | |
| 70 | + - name: Checkout PR branch | |
| 71 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 72 | + run: | | |
| 73 | + git checkout ${{ steps.pr-info.outputs.head_ref }} | |
| 74 | + | |
| 75 | + - name: Setup Node.js | |
| 76 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 77 | + uses: actions/setup-node@v5 | |
| 78 | + with: | |
| 79 | + node-version: "20" | |
| 80 | + | |
| 81 | + - name: Install Continue CLI globally | |
| 82 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 83 | + run: npm i -g @continuedev/cli | |
| 84 | + | |
| 85 | + - name: Start remote session | |
| 86 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 87 | + id: remote-session | |
| 88 | + env: | |
| 89 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 90 | + run: | | |
| 91 | + # Create a temporary file for the prompt to handle special characters and newlines properly | |
| 92 | + cat > /tmp/prompt.txt << 'PROMPT_EOF' | |
| 93 | + Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: | |
| 94 | + | |
| 95 | + ${{ github.event.comment.body }} | |
| 96 | + | |
| 97 | + Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch. | |
| 98 | + PROMPT_EOF | |
| 99 | + | |
| 100 | + # Debug output | |
| 101 | + echo "PROMPT content:" | |
| 102 | + cat /tmp/prompt.txt | |
| 103 | + | |
| 104 | + # Start remote session and capture JSON output | |
| 105 | + echo "Starting cn with prompt..." | |
| 106 | + SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }}) | |
| 107 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 108 | + | |
| 109 | + # Extract URL from JSON output | |
| 110 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 111 | + | |
| 112 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 113 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 114 | + exit 1 | |
| 115 | + fi | |
| 116 | + | |
| 117 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 118 | + echo "✅ Started remote session: $SESSION_URL" | |
| 119 | + | |
| 120 | + - name: Comment with session URL | |
| 121 | + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 122 | + uses: actions/github-script@v8 | |
| 123 | + env: | |
| 124 | + ORIGINAL_COMMENT: ${{ github.event.comment.body }} | |
| 125 | + with: | |
| 126 | + script: | | |
| 127 | + const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; | |
| 128 | + const originalComment = process.env.ORIGINAL_COMMENT; | |
| 129 | + const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; | |
| 130 | + | |
| 131 | + await github.rest.issues.createComment({ | |
| 132 | + owner: context.repo.owner, | |
| 133 | + repo: context.repo.repo, | |
| 134 | + issue_number: context.issue.number, | |
| 135 | + body: commentBody | |
| 136 | + }); | |
| 137 | + | |
| 138 | + - name: Log session details | |
| 139 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 140 | + run: | | |
| 141 | + echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" | |
| 142 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 143 | + echo "Original comment:" | |
| 144 | + cat /tmp/comment.txt | |
| 145 | + | |
| 146 | + respond-to-review-comment: | |
| 147 | + # Only run on pull request review comments | |
| 148 | + if: github.event_name == 'pull_request_review_comment' | |
| 149 | + runs-on: ubuntu-latest | |
| 150 | + | |
| 151 | + steps: | |
| 152 | + - name: Check if comment contains @continuedev | |
| 153 | + id: check-mention | |
| 154 | + run: | | |
| 155 | + # Create a temporary file to safely handle comment body with special characters | |
| 156 | + cat > /tmp/review_comment.txt << 'COMMENT_EOF' | |
| 157 | + ${{ github.event.comment.body }} | |
| 158 | + COMMENT_EOF | |
| 159 | + | |
| 160 | + if grep -q "@continuedev" /tmp/review_comment.txt; then | |
| 161 | + echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 162 | + else | |
| 163 | + echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 164 | + fi | |
| 165 | + | |
| 166 | + - name: Add eyes reaction to comment | |
| 167 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 168 | + uses: actions/github-script@v8 | |
| 169 | + with: | |
| 170 | + script: | | |
| 171 | + await github.rest.reactions.createForPullRequestReviewComment({ | |
| 172 | + owner: context.repo.owner, | |
| 173 | + repo: context.repo.repo, | |
| 174 | + comment_id: ${{ github.event.comment.id }}, | |
| 175 | + content: 'eyes' | |
| 176 | + }); | |
| 177 | + | |
| 178 | + - name: Checkout PR branch | |
| 179 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 180 | + uses: actions/checkout@v5 | |
| 181 | + with: | |
| 182 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 183 | + fetch-depth: 0 | |
| 184 | + ref: ${{ github.event.pull_request.head.ref }} | |
| 185 | + | |
| 186 | + - name: Setup Node.js | |
| 187 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 188 | + uses: actions/setup-node@v5 | |
| 189 | + with: | |
| 190 | + node-version: "20" | |
| 191 | + | |
| 192 | + - name: Install Continue CLI globally | |
| 193 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 194 | + run: npm i -g @continuedev/cli | |
| 195 | + | |
| 196 | + - name: Get review context | |
| 197 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 198 | + id: review-context | |
| 199 | + uses: actions/github-script@v8 | |
| 200 | + with: | |
| 201 | + script: | | |
| 202 | + let reviewContext = ''; | |
| 203 | + | |
| 204 | + // Check if this comment is a reply to another review comment | |
| 205 | + if (context.payload.comment.in_reply_to_id) { | |
| 206 | + try { | |
| 207 | + const { data: originalComment } = await github.rest.pulls.getReviewComment({ | |
| 208 | + owner: context.repo.owner, | |
| 209 | + repo: context.repo.repo, | |
| 210 | + comment_id: context.payload.comment.in_reply_to_id | |
| 211 | + }); | |
| 212 | + | |
| 213 | + reviewContext = `**Original review comment by @${originalComment.user.login}:** | |
| 214 | + ${originalComment.body} | |
| 215 | + | |
| 216 | + **Reply by @${{ github.event.comment.user.login }}:** | |
| 217 | + ${{ github.event.comment.body }}`; | |
| 218 | + } catch (error) { | |
| 219 | + console.log('Could not fetch original comment, using current comment only'); | |
| 220 | + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** | |
| 221 | + ${{ github.event.comment.body }}`; | |
| 222 | + } | |
| 223 | + } else { | |
| 224 | + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** | |
| 225 | + ${{ github.event.comment.body }}`; | |
| 226 | + } | |
| 227 | + | |
| 228 | + core.setOutput('context', reviewContext); | |
| 229 | + | |
| 230 | + - name: Start remote session | |
| 231 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 232 | + id: remote-session | |
| 233 | + env: | |
| 234 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 235 | + run: | | |
| 236 | + # Debug: Echo the branch we're starting the session on | |
| 237 | + echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}" | |
| 238 | + | |
| 239 | + # Create a temporary file for the prompt to handle special characters and newlines properly | |
| 240 | + cat > /tmp/prompt.txt << 'PROMPT_EOF' | |
| 241 | + Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}: | |
| 242 | + | |
| 243 | + **File:** ${{ github.event.comment.path }} | |
| 244 | + **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} | |
| 245 | + | |
| 246 | + ${{ steps.review-context.outputs.context }} | |
| 247 | + | |
| 248 | + 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. | |
| 249 | + PROMPT_EOF | |
| 250 | + | |
| 251 | + # Debug output | |
| 252 | + echo "PROMPT content:" | |
| 253 | + cat /tmp/prompt.txt | |
| 254 | + | |
| 255 | + # Start remote session and capture JSON output | |
| 256 | + echo "Starting cn with prompt..." | |
| 257 | + SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }}) | |
| 258 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 259 | + | |
| 260 | + # Extract URL from JSON output | |
| 261 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 262 | + | |
| 263 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 264 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 265 | + exit 1 | |
| 266 | + fi | |
| 267 | + | |
| 268 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 269 | + echo "✅ Started remote session: $SESSION_URL" | |
| 270 | + | |
| 271 | + - name: Comment with session URL | |
| 272 | + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 273 | + uses: actions/github-script@v8 | |
| 274 | + env: | |
| 275 | + ORIGINAL_COMMENT: ${{ github.event.comment.body }} | |
| 276 | + with: | |
| 277 | + script: | | |
| 278 | + const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; | |
| 279 | + const originalComment = process.env.ORIGINAL_COMMENT; | |
| 280 | + const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; | |
| 281 | + | |
| 282 | + const commentParams = { | |
| 283 | + owner: context.repo.owner, | |
| 284 | + repo: context.repo.repo, | |
| 285 | + pull_number: ${{ github.event.pull_request.number }}, | |
| 286 | + body: commentBody, | |
| 287 | + commit_id: '${{ github.event.pull_request.head.sha }}', | |
| 288 | + path: '${{ github.event.comment.path }}', | |
| 289 | + in_reply_to: ${{ github.event.comment.id }} | |
| 290 | + }; | |
| 291 | + | |
| 292 | + await github.rest.pulls.createReviewComment(commentParams); | |
| 293 | + | |
| 294 | + - name: Log session details | |
| 295 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 296 | + run: | | |
| 297 | + echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}" | |
| 298 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 299 | + echo "File: ${{ github.event.comment.path }}" | |
| 300 | + echo "Line: ${{ github.event.comment.line }}" | |
| 301 | + echo "Original comment:" | |
| 302 | + cat /tmp/review_comment.txt |
modified .github/workflows/reusable-release.yml +10 −1
| @@ -32,6 +32,10 @@ | ||
| 32 | 32 | required: false |
| 33 | 33 | VOYAGE_API_KEY: |
| 34 | 34 | required: false |
| 35 | + RELACE_API_KEY: | |
| 36 | + required: false | |
| 37 | + INCEPTION_API_KEY: | |
| 38 | + required: false | |
| 35 | 39 | |
| 36 | 40 | permissions: |
| 37 | 41 | contents: write |
| @@ -51,8 +55,11 @@ | ||
| 51 | 55 | with: |
| 52 | 56 | fetch-depth: 0 |
| 53 | 57 | |
| 58 | + - name: Setup packages | |
| 59 | + uses: ./.github/actions/setup-packages | |
| 60 | + | |
| 54 | 61 | - name: Use Node.js from .nvmrc |
| 55 | - uses: actions/setup-node@v4 | |
| 62 | + uses: actions/setup-node@v5 | |
| 56 | 63 | with: |
| 57 | 64 | node-version-file: ".nvmrc" |
| 58 | 65 | |
| @@ -74,6 +81,8 @@ | ||
| 74 | 81 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 75 | 82 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 76 | 83 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 84 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 85 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 77 | 86 | |
| 78 | 87 | - name: Release |
| 79 | 88 | env: |
modified .github/workflows/similar-issues.yml +3 −3
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | path: deja-view |
| 32 | 32 | |
| 33 | 33 | - name: Setup Python |
| 34 | - uses: actions/setup-python@v5 | |
| 34 | + uses: actions/setup-python@v6 | |
| 35 | 35 | with: |
| 36 | 36 | python-version: "3.11" |
| 37 | 37 | |
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT |
| 191 | 191 | |
| 192 | 192 | - name: Comment with analysis |
| 193 | - uses: actions/github-script@v7 | |
| 193 | + uses: actions/github-script@v8 | |
| 194 | 194 | with: |
| 195 | 195 | script: | |
| 196 | 196 | let comment = ''; |
| @@ -307,7 +307,7 @@ | ||
| 307 | 307 | |
| 308 | 308 | - name: Add labels |
| 309 | 309 | if: github.event_name == 'issues' |
| 310 | - uses: actions/github-script@v7 | |
| 310 | + uses: actions/github-script@v8 | |
| 311 | 311 | with: |
| 312 | 312 | script: | |
| 313 | 313 | const labels = []; |
added .github/workflows/stable-release.yml +222 −0
| @@ -0,0 +1,222 @@ | ||
| 1 | +name: Stable Release | |
| 2 | + | |
| 3 | +on: | |
| 4 | + schedule: | |
| 5 | + # Run every Monday at 10am UTC (1 hour after beta release) | |
| 6 | + - cron: "0 10 * * 1" | |
| 7 | + workflow_dispatch: | |
| 8 | + inputs: | |
| 9 | + release_type: | |
| 10 | + description: "Release type" | |
| 11 | + required: true | |
| 12 | + type: choice | |
| 13 | + options: | |
| 14 | + - "promote-beta" | |
| 15 | + - "direct-stable" | |
| 16 | + default: "promote-beta" | |
| 17 | + beta_version: | |
| 18 | + description: "Specific beta version to promote (required if release_type is 'promote-beta')" | |
| 19 | + required: false | |
| 20 | + type: string | |
| 21 | + stable_version: | |
| 22 | + description: "Version for direct stable release (e.g., 1.2.3) - required if release_type is 'direct-stable'" | |
| 23 | + required: false | |
| 24 | + type: string | |
| 25 | + | |
| 26 | +permissions: | |
| 27 | + contents: write | |
| 28 | + issues: write | |
| 29 | + pull-requests: write | |
| 30 | + | |
| 31 | +jobs: | |
| 32 | + stable-release: | |
| 33 | + name: Stable Release | |
| 34 | + runs-on: ubuntu-latest | |
| 35 | + steps: | |
| 36 | + - name: Checkout | |
| 37 | + uses: actions/checkout@v5 | |
| 38 | + with: | |
| 39 | + fetch-depth: 0 | |
| 40 | + token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} | |
| 41 | + | |
| 42 | + - name: Setup Node.js | |
| 43 | + uses: actions/setup-node@v5 | |
| 44 | + with: | |
| 45 | + node-version: 20 | |
| 46 | + registry-url: "https://registry.npmjs.org" | |
| 47 | + always-auth: true | |
| 48 | + | |
| 49 | + - name: Validate inputs | |
| 50 | + run: | | |
| 51 | + RELEASE_TYPE="${{ inputs.release_type || 'promote-beta' }}" | |
| 52 | + echo "Release type: $RELEASE_TYPE" | |
| 53 | + | |
| 54 | + if [[ "$RELEASE_TYPE" == "direct-stable" ]]; then | |
| 55 | + if [[ -z "${{ inputs.stable_version }}" ]]; then | |
| 56 | + echo "Error: stable_version is required for direct-stable release type" | |
| 57 | + exit 1 | |
| 58 | + fi | |
| 59 | + echo "Direct stable release version: ${{ inputs.stable_version }}" | |
| 60 | + elif [[ "$RELEASE_TYPE" == "promote-beta" ]]; then | |
| 61 | + echo "Beta promotion release (beta_version: ${{ inputs.beta_version }})" | |
| 62 | + else | |
| 63 | + echo "Error: Invalid release type: $RELEASE_TYPE" | |
| 64 | + exit 1 | |
| 65 | + fi | |
| 66 | + | |
| 67 | + - name: Find beta version to promote | |
| 68 | + if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} | |
| 69 | + id: find_beta | |
| 70 | + working-directory: extensions/cli | |
| 71 | + env: | |
| 72 | + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 73 | + run: | | |
| 74 | + if [[ -n "${{ inputs.beta_version }}" ]]; then | |
| 75 | + # Manual input provided | |
| 76 | + BETA_VERSION="${{ inputs.beta_version }}" | |
| 77 | + echo "Using manually specified beta version: $BETA_VERSION" | |
| 78 | + else | |
| 79 | + # Find beta version that's at least 7 days old | |
| 80 | + SEVEN_DAYS_AGO=$(date -u -d '7 days ago' +%Y%m%d) | |
| 81 | + echo "Looking for beta versions from $SEVEN_DAYS_AGO or earlier" | |
| 82 | + | |
| 83 | + # Get all beta versions from npm | |
| 84 | + BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' | sort -V) | |
| 85 | + | |
| 86 | + CANDIDATE_VERSION="" | |
| 87 | + for version in $BETA_VERSIONS; do | |
| 88 | + # Extract date from beta version (format: x.y.z-beta.YYYYMMDD) | |
| 89 | + if [[ $version =~ -beta\.([0-9]{8}) ]]; then | |
| 90 | + BETA_DATE="${BASH_REMATCH[1]}" | |
| 91 | + if [[ $BETA_DATE -le $SEVEN_DAYS_AGO ]]; then | |
| 92 | + CANDIDATE_VERSION=$version | |
| 93 | + fi | |
| 94 | + fi | |
| 95 | + done | |
| 96 | + | |
| 97 | + if [[ -z "$CANDIDATE_VERSION" ]]; then | |
| 98 | + echo "No beta version found that is at least 7 days old" | |
| 99 | + exit 1 | |
| 100 | + fi | |
| 101 | + | |
| 102 | + BETA_VERSION=$CANDIDATE_VERSION | |
| 103 | + echo "Selected beta version for promotion: $BETA_VERSION" | |
| 104 | + fi | |
| 105 | + | |
| 106 | + # Extract base version (remove -beta.YYYYMMDD suffix) | |
| 107 | + STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//') | |
| 108 | + | |
| 109 | + echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT | |
| 110 | + echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT | |
| 111 | + | |
| 112 | + - name: Set version for direct stable release | |
| 113 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 114 | + id: direct_stable | |
| 115 | + run: | | |
| 116 | + echo "stable_version=${{ inputs.stable_version }}" >> $GITHUB_OUTPUT | |
| 117 | + | |
| 118 | + - name: Download and verify beta package | |
| 119 | + if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} | |
| 120 | + working-directory: extensions/cli | |
| 121 | + env: | |
| 122 | + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 123 | + run: | | |
| 124 | + # Download the specific beta version | |
| 125 | + npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }} | |
| 126 | + | |
| 127 | + # Extract and verify the package | |
| 128 | + PACKAGE_FILE=$(ls continuedev-cli-*.tgz) | |
| 129 | + tar -xzf "$PACKAGE_FILE" | |
| 130 | + | |
| 131 | + echo "Beta package contents verified" | |
| 132 | + ls -la package/ | |
| 133 | + | |
| 134 | + - name: Prepare package for beta promotion | |
| 135 | + if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} | |
| 136 | + working-directory: extensions/cli | |
| 137 | + run: | | |
| 138 | + # Copy the beta package contents | |
| 139 | + cp -r package/* . | |
| 140 | + | |
| 141 | + # Update version to stable (remove beta suffix) | |
| 142 | + npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version | |
| 143 | + | |
| 144 | + - name: Setup packages (for direct stable release) | |
| 145 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 146 | + uses: ./.github/actions/setup-packages | |
| 147 | + | |
| 148 | + - name: Setup core component (for direct stable release) | |
| 149 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 150 | + uses: ./.github/actions/setup-component | |
| 151 | + with: | |
| 152 | + component: core | |
| 153 | + include-root: true | |
| 154 | + | |
| 155 | + - name: Build core | |
| 156 | + run: | | |
| 157 | + cd core | |
| 158 | + npm run build | |
| 159 | + | |
| 160 | + - name: Prepare package for direct stable release | |
| 161 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 162 | + working-directory: extensions/cli | |
| 163 | + run: | | |
| 164 | + # Install dependencies for direct build | |
| 165 | + npm ci | |
| 166 | + | |
| 167 | + # Update version to the specified stable version | |
| 168 | + npm version ${{ inputs.stable_version }} --no-git-tag-version | |
| 169 | + | |
| 170 | + - name: Build (verification step) | |
| 171 | + working-directory: extensions/cli | |
| 172 | + run: npm run build | |
| 173 | + | |
| 174 | + - name: Run tests (verification step) | |
| 175 | + working-directory: extensions/cli | |
| 176 | + run: npm test | |
| 177 | + | |
| 178 | + - name: Set final version | |
| 179 | + id: final_version | |
| 180 | + run: | | |
| 181 | + if [[ "${{ inputs.release_type || 'promote-beta' }}" == "direct-stable" ]]; then | |
| 182 | + STABLE_VERSION="${{ steps.direct_stable.outputs.stable_version }}" | |
| 183 | + RELEASE_NOTES="Direct stable release from main branch. Version $STABLE_VERSION built and published directly from the latest main branch." | |
| 184 | + else | |
| 185 | + STABLE_VERSION="${{ steps.find_beta.outputs.stable_version }}" | |
| 186 | + RELEASE_NOTES="Stable release promoted from tested beta version ${{ steps.find_beta.outputs.beta_version }}. This version has been thoroughly tested in beta for at least 7 days." | |
| 187 | + fi | |
| 188 | + echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT | |
| 189 | + echo "release_notes=$RELEASE_NOTES" >> $GITHUB_OUTPUT | |
| 190 | + | |
| 191 | + - name: Publish stable to npm | |
| 192 | + working-directory: extensions/cli | |
| 193 | + env: | |
| 194 | + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | |
| 195 | + run: | | |
| 196 | + npm publish --tag latest | |
| 197 | + echo "Published stable version: ${{ steps.final_version.outputs.stable_version }}" | |
| 198 | + | |
| 199 | + - name: Create stable release on GitHub | |
| 200 | + env: | |
| 201 | + GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} | |
| 202 | + run: | | |
| 203 | + # Create a git tag for the stable release | |
| 204 | + git config --local user.email "action@github.com" | |
| 205 | + git config --local user.name "GitHub Action" | |
| 206 | + git tag "v${{ steps.final_version.outputs.stable_version }}" | |
| 207 | + git push origin "v${{ steps.final_version.outputs.stable_version }}" | |
| 208 | + | |
| 209 | + # Create GitHub release | |
| 210 | + gh release create "v${{ steps.final_version.outputs.stable_version }}" \ | |
| 211 | + --title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \ | |
| 212 | + --notes "${{ steps.final_version.outputs.release_notes }}" \ | |
| 213 | + --latest | |
| 214 | + | |
| 215 | + - name: Update GitHub release notes for beta promotion | |
| 216 | + if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} | |
| 217 | + env: | |
| 218 | + GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} | |
| 219 | + run: | | |
| 220 | + # Mark the original beta release as superseded | |
| 221 | + gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \ | |
| 222 | + --notes "This beta version has been promoted to stable as v${{ steps.final_version.outputs.stable_version }}." |
modified .github/workflows/stale-issue-helper.yaml +1 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | pull-requests: write |
| 11 | 11 | runs-on: ubuntu-latest |
| 12 | 12 | steps: |
| 13 | - - uses: actions/stale@v9 | |
| 13 | + - uses: actions/stale@v10 | |
| 14 | 14 | with: |
| 15 | 15 | close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" |
| 16 | 16 | stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." |
modified .github/workflows/submit-github-dependency-graph.yml +1 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | - name: Checkout sources |
| 15 | 15 | uses: actions/checkout@v5 |
| 16 | 16 | - name: Setup Java |
| 17 | - uses: actions/setup-java@v4 | |
| 17 | + uses: actions/setup-java@v5 | |
| 18 | 18 | with: |
| 19 | 19 | distribution: "temurin" |
| 20 | 20 | java-version: 17 |
modified .github/workflows/vscode-version-bump.yml +1 −1
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | gh auth login --with-token <<< "${{ github.token }}" |
| 22 | 22 | |
| 23 | 23 | - name: Use Node.js from .nvmrc |
| 24 | - uses: actions/setup-node@v4 | |
| 24 | + uses: actions/setup-node@v5 | |
| 25 | 25 | with: |
| 26 | 26 | node-version-file: ".nvmrc" |
| 27 | 27 |
modified .gitignore +2 −0
| @@ -158,6 +158,7 @@ | ||
| 158 | 158 | **/.idea/shelf/ |
| 159 | 159 | **/.idea/inspectionProfiles/Project_Default.xml |
| 160 | 160 | **/.idea/php.xml |
| 161 | +**/.idea/kotlinc.xml | |
| 161 | 162 | |
| 162 | 163 | |
| 163 | 164 | extensions/intellij/bin |
| @@ -170,4 +171,5 @@ | ||
| 170 | 171 | |
| 171 | 172 | .continuerules |
| 172 | 173 | **/.continue/assistants/ |
| 174 | +**/.continue/agents/ | |
| 173 | 175 | keys |
| No newline at the end of the file |
deleted .idea/kotlinc.xml +0 −6
| @@ -1,6 +0,0 @@ | ||
| 1 | -<?xml version="1.0" encoding="UTF-8"?> | |
| 2 | -<project version="4"> | |
| 3 | - <component name="KotlinJpsPluginSettings"> | |
| 4 | - <option name="version" value="1.8.0" /> | |
| 5 | - </component> | |
| 6 | -</project> | |
| No newline at the end of the file |
modified .prettierignore +1 −1
| @@ -23,5 +23,5 @@ | ||
| 23 | 23 | **/CODEOWNERS |
| 24 | 24 | core/vendor |
| 25 | 25 | coverage |
| 26 | -e2e | |
| 26 | +# e2e | |
| 27 | 27 | packages/continue-sdk |
| No newline at the end of the file |
modified .vscode/launch.json +44 −1
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | ], |
| 19 | 19 | "pauseForSourceMap": false, |
| 20 | 20 | "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], |
| 21 | - "preLaunchTask": "vscode-extension:build-with-packages", | |
| 21 | + "preLaunchTask": "vscode-extension:build-without-watch", | |
| 22 | 22 | "env": { |
| 23 | 23 | // "CONTROL_PLANE_ENV": "local", |
| 24 | 24 | "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" |
| @@ -131,6 +131,49 @@ | ||
| 131 | 131 | "env": { |
| 132 | 132 | "NODE_OPTIONS": "--experimental-vm-modules" |
| 133 | 133 | } |
| 134 | + }, | |
| 135 | + { | |
| 136 | + "name": "Debug CLI", | |
| 137 | + "type": "node", | |
| 138 | + "request": "launch", | |
| 139 | + "program": "${workspaceFolder}/extensions/cli/src/index.ts", | |
| 140 | + "args": [], | |
| 141 | + "env": { | |
| 142 | + "NODE_ENV": "development" | |
| 143 | + // "CONTINUE_API_BASE": "http://localhost:3001/", | |
| 144 | + // "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ", | |
| 145 | + // "HUB_URL": "http://localhost:3000" | |
| 146 | + }, | |
| 147 | + "console": "integratedTerminal", | |
| 148 | + "internalConsoleOptions": "neverOpen", | |
| 149 | + "skipFiles": ["<node_internals>/**"], | |
| 150 | + "runtimeArgs": ["--loader", "ts-node/esm"], | |
| 151 | + "sourceMaps": true, | |
| 152 | + "resolveSourceMapLocations": [ | |
| 153 | + "${workspaceFolder}/**", | |
| 154 | + "!**/node_modules/**" | |
| 155 | + ], | |
| 156 | + "preLaunchTask": "cli:build-and-watch-logs", | |
| 157 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 158 | + }, | |
| 159 | + { | |
| 160 | + "name": "Debug CLI Tests", | |
| 161 | + "type": "node", | |
| 162 | + "request": "launch", | |
| 163 | + "program": "${workspaceFolder}/extensions/cli/node_modules/.bin/vitest", | |
| 164 | + "args": ["--run", "--no-cache"], | |
| 165 | + "env": { | |
| 166 | + "NODE_ENV": "test" | |
| 167 | + }, | |
| 168 | + "console": "integratedTerminal", | |
| 169 | + "internalConsoleOptions": "neverOpen", | |
| 170 | + "skipFiles": ["<node_internals>/**"], | |
| 171 | + "sourceMaps": true, | |
| 172 | + "resolveSourceMapLocations": [ | |
| 173 | + "${workspaceFolder}/**", | |
| 174 | + "!**/node_modules/**" | |
| 175 | + ], | |
| 176 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 134 | 177 | } |
| 135 | 178 | ] |
| 136 | 179 | } |
modified .vscode/settings.json +3 −1
| @@ -42,7 +42,9 @@ | ||
| 42 | 42 | "extensions/vscode/e2e/_output": true, |
| 43 | 43 | "extensions/vscode/e2e/storage": true, |
| 44 | 44 | "extensions/vscode/e2e/vsix": true, |
| 45 | - "extensions/.continue-debug": true | |
| 45 | + "extensions/.continue-debug": true, | |
| 46 | + "extensions/cli/dist/**": true, | |
| 47 | + "packages/config-yaml/dist/**": true | |
| 46 | 48 | // "sync/**": true |
| 47 | 49 | }, |
| 48 | 50 | "editor.formatOnSave": true, |
modified .vscode/tasks.json +116 −0
| @@ -174,6 +174,25 @@ | ||
| 174 | 174 | } |
| 175 | 175 | ] |
| 176 | 176 | }, |
| 177 | + { | |
| 178 | + "label": "gui:build", | |
| 179 | + "type": "shell", | |
| 180 | + "command": "npm", | |
| 181 | + "options": { | |
| 182 | + "cwd": "${workspaceFolder}/gui", | |
| 183 | + "env": { | |
| 184 | + "NODE_OPTIONS": "--max-old-space-size=4096" | |
| 185 | + } | |
| 186 | + }, | |
| 187 | + "args": ["run", "build"], | |
| 188 | + "problemMatcher": ["$tsc"], | |
| 189 | + "presentation": { | |
| 190 | + "group": "build-tasks", | |
| 191 | + "panel": "shared", | |
| 192 | + "reveal": "silent", | |
| 193 | + "close": true | |
| 194 | + } | |
| 195 | + }, | |
| 177 | 196 | { |
| 178 | 197 | "label": "binary:esbuild", |
| 179 | 198 | "type": "shell", |
| @@ -311,6 +330,103 @@ | ||
| 311 | 330 | "close": true, |
| 312 | 331 | "focus": false |
| 313 | 332 | } |
| 333 | + }, | |
| 334 | + { | |
| 335 | + "label": "cli:build", | |
| 336 | + "type": "npm", | |
| 337 | + "script": "build", | |
| 338 | + "group": "build", | |
| 339 | + "presentation": { | |
| 340 | + "echo": true, | |
| 341 | + "reveal": "silent", | |
| 342 | + "focus": false, | |
| 343 | + "panel": "shared", | |
| 344 | + "showReuseMessage": true, | |
| 345 | + "clear": false | |
| 346 | + }, | |
| 347 | + "problemMatcher": ["$tsc"], | |
| 348 | + "options": { | |
| 349 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 350 | + } | |
| 351 | + }, | |
| 352 | + { | |
| 353 | + "label": "cli:build-no-minify", | |
| 354 | + "type": "shell", | |
| 355 | + "command": "npm", | |
| 356 | + "args": ["run", "build:bundle", "--", "--no-minify"], | |
| 357 | + "group": "build", | |
| 358 | + "presentation": { | |
| 359 | + "echo": true, | |
| 360 | + "reveal": "silent", | |
| 361 | + "focus": false, | |
| 362 | + "panel": "shared", | |
| 363 | + "showReuseMessage": true, | |
| 364 | + "clear": false, | |
| 365 | + "close": true | |
| 366 | + }, | |
| 367 | + "problemMatcher": ["$tsc"], | |
| 368 | + "options": { | |
| 369 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 370 | + } | |
| 371 | + }, | |
| 372 | + { | |
| 373 | + "label": "cli:test", | |
| 374 | + "type": "npm", | |
| 375 | + "script": "test", | |
| 376 | + "group": "test", | |
| 377 | + "presentation": { | |
| 378 | + "echo": true, | |
| 379 | + "reveal": "always", | |
| 380 | + "focus": false, | |
| 381 | + "panel": "shared", | |
| 382 | + "showReuseMessage": true, | |
| 383 | + "clear": false | |
| 384 | + }, | |
| 385 | + "options": { | |
| 386 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 387 | + } | |
| 388 | + }, | |
| 389 | + { | |
| 390 | + "label": "watch-logs", | |
| 391 | + "type": "shell", | |
| 392 | + "command": "npm run watch:logs", | |
| 393 | + "isBackground": true, | |
| 394 | + "problemMatcher": { | |
| 395 | + "pattern": { | |
| 396 | + "regexp": "^$", | |
| 397 | + "file": 1, | |
| 398 | + "location": 2, | |
| 399 | + "message": 3 | |
| 400 | + }, | |
| 401 | + "background": { | |
| 402 | + "activeOnStart": true, | |
| 403 | + "beginsPattern": "^.*$", | |
| 404 | + "endsPattern": "^.*$" | |
| 405 | + } | |
| 406 | + }, | |
| 407 | + "presentation": { | |
| 408 | + "reveal": "always", | |
| 409 | + "panel": "new", | |
| 410 | + "focus": false | |
| 411 | + }, | |
| 412 | + "options": { | |
| 413 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 414 | + } | |
| 415 | + }, | |
| 416 | + { | |
| 417 | + "label": "cli:build-and-watch-logs", | |
| 418 | + "dependsOn": ["cli:build-no-minify", "watch-logs"], | |
| 419 | + "dependsOrder": "sequence", | |
| 420 | + "type": "shell", | |
| 421 | + "command": "echo", | |
| 422 | + "args": ["Build and watch logs completed"], | |
| 423 | + "presentation": { | |
| 424 | + "group": "build-tasks", | |
| 425 | + "panel": "shared", | |
| 426 | + "reveal": "silent", | |
| 427 | + "close": true, | |
| 428 | + "focus": false | |
| 429 | + } | |
| 314 | 430 | } |
| 315 | 431 | ] |
| 316 | 432 | } |
modified CONTRIBUTING.md +3 −3
| @@ -176,9 +176,9 @@ | ||
| 176 | 176 | ### Our Git Workflow |
| 177 | 177 | |
| 178 | 178 | We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the |
| 179 | -`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow | |
| 179 | +`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow | |
| 180 | 180 | in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When |
| 181 | -a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar | |
| 181 | +a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar | |
| 182 | 182 | workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code |
| 183 | 183 | extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow |
| 184 | 184 | is well explained by <http://releaseflow.org>. |
| @@ -288,4 +288,4 @@ | ||
| 288 | 288 | I have read the CLA Document and I hereby sign the CLA |
| 289 | 289 | ``` |
| 290 | 290 | |
| 291 | -3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed. | |
| 291 | +3. The CLA-Assistant bot records your signature in the repo and marks the status check as passed. |
modified README.md +4 −4
| @@ -35,25 +35,25 @@ | ||
| 35 | 35 | |
| 36 | 36 | ## Agent |
| 37 | 37 | |
| 38 | -[Agent](/features/agent/quick-start) to work on development tasks together with AI | |
| 38 | +[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI | |
| 39 | 39 | |
| 40 | 40 |  |
| 41 | 41 | |
| 42 | 42 | ## Chat |
| 43 | 43 | |
| 44 | -[Chat](/features/chat/quick-start) to ask general questions and clarify code sections | |
| 44 | +[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections | |
| 45 | 45 | |
| 46 | 46 |  |
| 47 | 47 | |
| 48 | 48 | ## Edit |
| 49 | 49 | |
| 50 | -[Edit](/features/edit/quick-start) to modify a code section without leaving your current file | |
| 50 | +[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file | |
| 51 | 51 | |
| 52 | 52 |  |
| 53 | 53 | |
| 54 | 54 | ## Autocomplete |
| 55 | 55 | |
| 56 | -[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type | |
| 56 | +[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type | |
| 57 | 57 | |
| 58 | 58 |  |
| 59 | 59 |
modified actions/README.md +1 −1
| @@ -219,7 +219,7 @@ | ||
| 219 | 219 | Example: |
| 220 | 220 | |
| 221 | 221 | ```yaml |
| 222 | -uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266 | |
| 222 | +uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe | |
| 223 | 223 | ``` |
| 224 | 224 | |
| 225 | 225 | ## Troubleshooting |
modified actions/detailed-review/action.yml +119 −35
| @@ -29,12 +29,17 @@ | ||
| 29 | 29 | SHOULD_RUN="false" |
| 30 | 30 | |
| 31 | 31 | if [ "${{ github.event_name }}" = "pull_request" ]; then |
| 32 | - # Check PR author association | |
| 33 | - AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" | |
| 34 | - if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then | |
| 35 | - SHOULD_RUN="true" | |
| 32 | + # Check if PR is a draft | |
| 33 | + if [ "${{ github.event.pull_request.draft }}" = "true" ]; then | |
| 34 | + echo "::notice::Skipping review - PR is a draft" | |
| 36 | 35 | else |
| 37 | - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" | |
| 36 | + # Check PR author association | |
| 37 | + AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" | |
| 38 | + if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then | |
| 39 | + SHOULD_RUN="true" | |
| 40 | + else | |
| 41 | + echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" | |
| 42 | + fi | |
| 38 | 43 | fi |
| 39 | 44 | elif [ "${{ github.event_name }}" = "issue_comment" ]; then |
| 40 | 45 | # Check if it's a PR comment with the trigger phrase |
| @@ -68,7 +73,7 @@ | ||
| 68 | 73 | - name: Install Continue CLI |
| 69 | 74 | if: env.SKIP_REVIEW != 'true' |
| 70 | 75 | shell: bash |
| 71 | - run: npm install -g @continuedev/cli@1.4.25 | |
| 76 | + run: npm install -g @continuedev/cli@1.4.30 | |
| 72 | 77 | |
| 73 | 78 | - name: Build Inline Review Prompt |
| 74 | 79 | if: env.SKIP_REVIEW != 'true' |
| @@ -189,6 +194,21 @@ | ||
| 189 | 194 | exit 1 |
| 190 | 195 | fi |
| 191 | 196 | |
| 197 | + # Validate API key | |
| 198 | + if [ -z "$CONTINUE_API_KEY" ]; then | |
| 199 | + echo "Warning: CONTINUE_API_KEY environment variable is not set" | |
| 200 | + # Create fallback review and continue | |
| 201 | + cat > inline_review.json << 'EOF' | |
| 202 | + { | |
| 203 | + "review_summary": "AI review skipped: CONTINUE_API_KEY not configured.", | |
| 204 | + "comments": [] | |
| 205 | + } | |
| 206 | + EOF | |
| 207 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 208 | + else | |
| 209 | + echo "SKIP_CLI=false" >> $GITHUB_ENV | |
| 210 | + fi | |
| 211 | + | |
| 192 | 212 | # Log the prompt for debugging |
| 193 | 213 | echo "===== START REVIEW PROMPT =====" |
| 194 | 214 | head -n 50 inline_review_prompt.txt |
| @@ -196,23 +216,67 @@ | ||
| 196 | 216 | tail -n 20 inline_review_prompt.txt |
| 197 | 217 | echo "===== END REVIEW PROMPT =====" |
| 198 | 218 | |
| 199 | - # Run the CLI and capture JSON output | |
| 200 | - cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json | |
| 201 | - | |
| 202 | - # Log the output for debugging | |
| 203 | - echo "Initial Continue CLI output:" | |
| 204 | - cat inline_review_raw.json | |
| 219 | + # Test Continue CLI availability | |
| 220 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 221 | + echo "Testing Continue CLI..." | |
| 222 | + if ! cn --version; then | |
| 223 | + echo "Warning: Continue CLI not found or not working" | |
| 224 | + cat > inline_review.json << 'EOF' | |
| 225 | + { | |
| 226 | + "review_summary": "AI review skipped: Continue CLI installation failed.", | |
| 227 | + "comments": [] | |
| 228 | + } | |
| 229 | + EOF | |
| 230 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 231 | + else | |
| 232 | + echo "Continue CLI version: $(cn --version)" | |
| 233 | + fi | |
| 234 | + fi | |
| 205 | 235 | |
| 206 | - # Validate JSON output and use it directly | |
| 207 | - if ! jq empty inline_review_raw.json 2>/dev/null; then | |
| 208 | - echo "Error: Invalid JSON output from Continue CLI" | |
| 209 | - exit 1 | |
| 236 | + # Run the CLI and capture JSON output with error handling | |
| 237 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 238 | + echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}" | |
| 239 | + | |
| 240 | + # Write prompt to temp file for better handling | |
| 241 | + PROMPT_FILE="/tmp/continue-prompt-$.txt" | |
| 242 | + cp inline_review_prompt.txt "$PROMPT_FILE" | |
| 243 | + | |
| 244 | + # Use timeout to prevent hanging (240 seconds = 4 minutes) | |
| 245 | + 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 | |
| 246 | + echo "Warning: Continue CLI command failed" | |
| 247 | + echo "CLI error log:" | |
| 248 | + cat cli_error.log | |
| 249 | + | |
| 250 | + # Create fallback review | |
| 251 | + cat > inline_review.json << 'EOF' | |
| 252 | + { | |
| 253 | + "review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.", | |
| 254 | + "comments": [] | |
| 255 | + } | |
| 256 | + EOF | |
| 257 | + echo "Created fallback review due to CLI failure" | |
| 258 | + else | |
| 259 | + # Log the output for debugging | |
| 260 | + echo "Initial Continue CLI output:" | |
| 261 | + cat inline_review_raw.json | |
| 262 | + | |
| 263 | + # Validate JSON output and use it directly | |
| 264 | + if ! jq empty inline_review_raw.json 2>/dev/null; then | |
| 265 | + echo "Warning: Invalid JSON output from Continue CLI, using fallback" | |
| 266 | + cat > inline_review.json << 'EOF' | |
| 267 | + { | |
| 268 | + "review_summary": "AI review completed but failed to parse output correctly.", | |
| 269 | + "comments": [] | |
| 270 | + } | |
| 271 | + EOF | |
| 272 | + else | |
| 273 | + # Use the JSON output directly | |
| 274 | + cp inline_review_raw.json inline_review.json | |
| 275 | + echo "Review output:" | |
| 276 | + cat inline_review.json | |
| 277 | + fi | |
| 278 | + fi | |
| 210 | 279 | fi |
| 211 | - | |
| 212 | - # Use the JSON output directly | |
| 213 | - cp inline_review_raw.json inline_review.json | |
| 214 | - echo "Review output:" | |
| 215 | - cat inline_review.json | |
| 216 | 280 | |
| 217 | 281 | - name: Post Inline Review Comments |
| 218 | 282 | if: env.SKIP_REVIEW != 'true' |
| @@ -268,7 +332,23 @@ | ||
| 268 | 332 | console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2)); |
| 269 | 333 | } |
| 270 | 334 | |
| 271 | - const comments = validComments.map(comment => ({ | |
| 335 | + // Deduplicate comments based on path + position + body | |
| 336 | + const uniqueComments = []; | |
| 337 | + const seen = new Set(); | |
| 338 | + | |
| 339 | + for (const comment of validComments) { | |
| 340 | + const key = `${comment.path}:${comment.position}:${comment.body}`; | |
| 341 | + if (!seen.has(key)) { | |
| 342 | + seen.add(key); | |
| 343 | + uniqueComments.push(comment); | |
| 344 | + } | |
| 345 | + } | |
| 346 | + | |
| 347 | + if (uniqueComments.length < validComments.length) { | |
| 348 | + console.log(`Filtered out ${validComments.length - uniqueComments.length} duplicate comments (same path + position + body)`); | |
| 349 | + } | |
| 350 | + | |
| 351 | + const comments = uniqueComments.map(comment => ({ | |
| 272 | 352 | path: comment.path, |
| 273 | 353 | position: comment.position, |
| 274 | 354 | body: comment.body |
| @@ -283,12 +363,19 @@ | ||
| 283 | 363 | // Create the review |
| 284 | 364 | if (comments.length > 0) { |
| 285 | 365 | try { |
| 366 | + let reviewBody = `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; | |
| 367 | + | |
| 368 | + // Add triggered by note if from comment | |
| 369 | + if (context.eventName === 'issue_comment') { | |
| 370 | + reviewBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewBody}`; | |
| 371 | + } | |
| 372 | + | |
| 286 | 373 | await github.rest.pulls.createReview({ |
| 287 | 374 | owner: context.repo.owner, |
| 288 | 375 | repo: context.repo.repo, |
| 289 | 376 | pull_number: prNumber, |
| 290 | 377 | commit_id: commitSha, |
| 291 | - body: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`, | |
| 378 | + body: reviewBody, | |
| 292 | 379 | event: 'COMMENT', |
| 293 | 380 | comments: comments |
| 294 | 381 | }); |
| @@ -310,22 +397,19 @@ | ||
| 310 | 397 | } |
| 311 | 398 | } else { |
| 312 | 399 | // No inline comments, just post the summary |
| 400 | + let summaryBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` + | |
| 401 | + `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; | |
| 402 | + | |
| 403 | + // Add triggered by note if from comment | |
| 404 | + if (context.eventName === 'issue_comment') { | |
| 405 | + summaryBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${summaryBody}`; | |
| 406 | + } | |
| 407 | + | |
| 313 | 408 | await github.rest.issues.createComment({ |
| 314 | 409 | issue_number: prNumber, |
| 315 | 410 | owner: context.repo.owner, |
| 316 | 411 | repo: context.repo.repo, |
| 317 | - body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` + | |
| 318 | - `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*` | |
| 319 | - }); | |
| 320 | - } | |
| 321 | - | |
| 322 | - // Add triggered by note if from comment | |
| 323 | - if (context.eventName === 'issue_comment') { | |
| 324 | - await github.rest.issues.createComment({ | |
| 325 | - issue_number: prNumber, | |
| 326 | - owner: context.repo.owner, | |
| 327 | - repo: context.repo.repo, | |
| 328 | - body: `*Inline review triggered by @${context.payload.comment.user.login}*` | |
| 412 | + body: summaryBody | |
| 329 | 413 | }); |
| 330 | 414 | } |
| 331 | 415 |
modified actions/general-review/action.yml +89 −19
| @@ -1,20 +1,20 @@ | ||
| 1 | -name: 'Continue PR Review' | |
| 2 | -description: 'Automated code review for pull requests using Continue CLI' | |
| 3 | -author: 'Continue Dev, Inc.' | |
| 1 | +name: "Continue PR Review" | |
| 2 | +description: "Automated code review for pull requests using Continue CLI" | |
| 3 | +author: "Continue Dev, Inc." | |
| 4 | 4 | |
| 5 | 5 | inputs: |
| 6 | 6 | continue-api-key: |
| 7 | - description: 'API key for Continue service' | |
| 7 | + description: "API key for Continue service" | |
| 8 | 8 | required: true |
| 9 | 9 | continue-org: |
| 10 | - description: 'Organization for Continue config' | |
| 10 | + description: "Organization for Continue config" | |
| 11 | 11 | required: true |
| 12 | 12 | continue-config: |
| 13 | 13 | description: 'Config path to use (e.g., "myorg/review-bot")' |
| 14 | 14 | required: true |
| 15 | 15 | |
| 16 | 16 | runs: |
| 17 | - using: 'composite' | |
| 17 | + using: "composite" | |
| 18 | 18 | steps: |
| 19 | 19 | - name: Checkout Repository |
| 20 | 20 | uses: actions/checkout@v4 |
| @@ -27,14 +27,19 @@ | ||
| 27 | 27 | run: | |
| 28 | 28 | # Check if this action should run based on event type and user permissions |
| 29 | 29 | SHOULD_RUN="false" |
| 30 | - | |
| 30 | + | |
| 31 | 31 | if [ "${{ github.event_name }}" = "pull_request" ]; then |
| 32 | - # Check PR author association | |
| 33 | - AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" | |
| 34 | - if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then | |
| 35 | - SHOULD_RUN="true" | |
| 32 | + # Check if PR is a draft | |
| 33 | + if [ "${{ github.event.pull_request.draft }}" = "true" ]; then | |
| 34 | + echo "::notice::Skipping review - PR is a draft" | |
| 36 | 35 | else |
| 37 | - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" | |
| 36 | + # Check PR author association | |
| 37 | + AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" | |
| 38 | + if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then | |
| 39 | + SHOULD_RUN="true" | |
| 40 | + else | |
| 41 | + echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" | |
| 42 | + fi | |
| 38 | 43 | fi |
| 39 | 44 | elif [ "${{ github.event_name }}" = "issue_comment" ]; then |
| 40 | 45 | # Check if it's a PR comment with the trigger phrase |
| @@ -51,7 +56,7 @@ | ||
| 51 | 56 | else |
| 52 | 57 | echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}" |
| 53 | 58 | fi |
| 54 | - | |
| 59 | + | |
| 55 | 60 | echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV |
| 56 | 61 | |
| 57 | 62 | - name: Setup Node.js |
| @@ -63,7 +68,7 @@ | ||
| 63 | 68 | - name: Install Continue CLI |
| 64 | 69 | if: env.SHOULD_RUN == 'true' |
| 65 | 70 | shell: bash |
| 66 | - run: npm install -g @continuedev/cli@1.4.25 | |
| 71 | + run: npm install -g @continuedev/cli@1.4.30 | |
| 67 | 72 | |
| 68 | 73 | - name: Build PR Review Prompt |
| 69 | 74 | if: env.SHOULD_RUN == 'true' |
| @@ -152,19 +157,84 @@ | ||
| 152 | 157 | echo "==================================" |
| 153 | 158 | echo "" |
| 154 | 159 | |
| 160 | + # Validate API key | |
| 161 | + if [ -z "$CONTINUE_API_KEY" ]; then | |
| 162 | + echo "Warning: CONTINUE_API_KEY environment variable is not set" | |
| 163 | + # Create fallback review and continue | |
| 164 | + cat > code_review.md << 'EOF' | |
| 165 | + ## Code Review Summary | |
| 166 | + | |
| 167 | + ⚠️ AI review skipped: CONTINUE_API_KEY not configured. | |
| 168 | + | |
| 169 | + ### Configuration Required | |
| 170 | + - Please set the CONTINUE_API_KEY secret in repository settings | |
| 171 | + - Verify that the organization and config path are valid | |
| 172 | + EOF | |
| 173 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 174 | + else | |
| 175 | + echo "SKIP_CLI=false" >> $GITHUB_ENV | |
| 176 | + fi | |
| 177 | + | |
| 155 | 178 | # Validate inputs to prevent command injection |
| 156 | 179 | if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then |
| 157 | 180 | echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores." |
| 158 | 181 | exit 1 |
| 159 | 182 | fi |
| 160 | - | |
| 183 | + | |
| 161 | 184 | if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then |
| 162 | 185 | echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes." |
| 163 | 186 | exit 1 |
| 164 | 187 | fi |
| 165 | 188 | |
| 166 | - # Run the CLI with validated config | |
| 167 | - cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md | |
| 189 | + # Test Continue CLI availability | |
| 190 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 191 | + echo "Testing Continue CLI..." | |
| 192 | + if ! cn --version; then | |
| 193 | + echo "Warning: Continue CLI not found or not working" | |
| 194 | + cat > code_review.md << 'EOF' | |
| 195 | + ## Code Review Summary | |
| 196 | + | |
| 197 | + ⚠️ AI review skipped: Continue CLI installation failed. | |
| 198 | + | |
| 199 | + ### Troubleshooting | |
| 200 | + - Check that npm installation succeeded | |
| 201 | + - Verify @continuedev/cli package is available | |
| 202 | + EOF | |
| 203 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 204 | + else | |
| 205 | + echo "Continue CLI version: $(cn --version)" | |
| 206 | + fi | |
| 207 | + fi | |
| 208 | + | |
| 209 | + # Run the CLI with validated config and error handling | |
| 210 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 211 | + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" | |
| 212 | + | |
| 213 | + # Write prompt to temp file for better handling | |
| 214 | + PROMPT_FILE="/tmp/continue-prompt-$.txt" | |
| 215 | + cp review_prompt.txt "$PROMPT_FILE" | |
| 216 | + | |
| 217 | + # Use timeout to prevent hanging (240 seconds = 4 minutes) | |
| 218 | + if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then | |
| 219 | + echo "Error: Continue CLI command failed" | |
| 220 | + echo "CLI error log:" | |
| 221 | + cat cli_error.log | |
| 222 | + | |
| 223 | + # Create fallback review | |
| 224 | + cat > code_review.md << 'EOF' | |
| 225 | + ## Code Review Summary | |
| 226 | + | |
| 227 | + ⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. | |
| 228 | + | |
| 229 | + ### Troubleshooting | |
| 230 | + - Verify the CONTINUE_API_KEY secret is set correctly | |
| 231 | + - Check that the organization and config path are valid | |
| 232 | + - Ensure the Continue service is accessible | |
| 233 | + EOF | |
| 234 | + else | |
| 235 | + echo "Review generated successfully" | |
| 236 | + fi | |
| 237 | + fi | |
| 168 | 238 | |
| 169 | 239 | - name: Upload Review Results |
| 170 | 240 | if: env.SHOULD_RUN == 'true' && always() |
| @@ -224,5 +294,5 @@ | ||
| 224 | 294 | } |
| 225 | 295 | |
| 226 | 296 | branding: |
| 227 | - icon: 'code' | |
| 228 | - color: 'blue' | |
| No newline at the end of the file | ||
| 297 | + icon: "code" | |
| 298 | + color: "blue" |
modified binary/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified binary/package.json +1 −1
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | "pkg": "^5.8.1", |
| 40 | 40 | "rimraf": "^5.0.7", |
| 41 | 41 | "ts-jest": "^29.1.4", |
| 42 | - "typescript": "^5.3.3" | |
| 42 | + "typescript": "^5.6.3" | |
| 43 | 43 | }, |
| 44 | 44 | "dependencies": { |
| 45 | 45 | "@octokit/rest": "^20.0.2", |
modified core/autocomplete/CompletionProvider.ts +6 −7
| @@ -6,12 +6,13 @@ | ||
| 6 | 6 | import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; |
| 7 | 7 | import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; |
| 8 | 8 | |
| 9 | +import { isSecurityConcern } from "../indexing/ignore.js"; | |
| 9 | 10 | import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; |
| 10 | 11 | import { CompletionStreamer } from "./generation/CompletionStreamer.js"; |
| 11 | 12 | import { postprocessCompletion } from "./postprocessing/index.js"; |
| 12 | 13 | import { shouldPrefilter } from "./prefiltering/index.js"; |
| 13 | -import { renderPromptWithTokenLimit } from "./templating/index.js"; | |
| 14 | 14 | import { getAllSnippetsWithoutRace } from "./snippets/index.js"; |
| 15 | +import { renderPromptWithTokenLimit } from "./templating/index.js"; | |
| 15 | 16 | import { GetLspDefinitionsFunction } from "./types.js"; |
| 16 | 17 | import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; |
| 17 | 18 | import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; |
| @@ -150,6 +151,10 @@ | ||
| 150 | 151 | return undefined; |
| 151 | 152 | } |
| 152 | 153 | |
| 154 | + if (isSecurityConcern(input.filepath)) { | |
| 155 | + return undefined; | |
| 156 | + } | |
| 157 | + | |
| 153 | 158 | const options = await this._getAutocompleteOptions(llm); |
| 154 | 159 | |
| 155 | 160 | // Debounce |
| @@ -210,12 +215,6 @@ | ||
| 210 | 215 | const multiline = |
| 211 | 216 | !helper.options.transform || shouldCompleteMultiline(helper); |
| 212 | 217 | |
| 213 | - const rawGeneration = await llm.complete( | |
| 214 | - prompt, | |
| 215 | - token, | |
| 216 | - completionOptions, | |
| 217 | - ); | |
| 218 | - | |
| 219 | 218 | const completionStream = |
| 220 | 219 | this.completionStreamer.streamCompletionWithFilters( |
| 221 | 220 | token, |
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +7 −2
| @@ -166,8 +166,13 @@ | ||
| 166 | 166 | export const CODE_STOP_BLOCK = "[/CODE]"; |
| 167 | 167 | export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; |
| 168 | 168 | export const PREFIXES_TO_SKIP = ["<COMPLETION>"]; |
| 169 | -export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"]; | |
| 170 | -export const LINES_TO_SKIP = ["</START EDITING HERE>"]; | |
| 169 | +export const LINES_TO_STOP_AT = [ | |
| 170 | + "# End of file.", | |
| 171 | + "<STOP EDITING HERE", | |
| 172 | + "<|/updated_code|>", | |
| 173 | + "```", | |
| 174 | +]; | |
| 175 | +export const LINES_TO_SKIP = ["</START EDITING HERE>", "<|updated_code|>"]; | |
| 171 | 176 | export const LINES_TO_REMOVE_BEFORE_START = [ |
| 172 | 177 | "<COMPLETION>", |
| 173 | 178 | "[CODE]", |
modified core/autocomplete/prefiltering/index.ts +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | import { |
| 5 | 5 | getGlobalContinueIgArray, |
| 6 | 6 | getWorkspaceContinueIgArray, |
| 7 | -} from "../../indexing/ignore"; | |
| 7 | +} from "../../indexing/continueignore"; | |
| 8 | 8 | import { getConfigJsonPath } from "../../util/paths"; |
| 9 | 9 | import { findUriInDirs } from "../../util/uri"; |
| 10 | 10 | import { HelperVars } from "../util/HelperVars"; |
modified core/codeRenderer/CodeRenderer.ts +76 −51
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | getSingletonHighlighter, |
| 20 | 20 | Highlighter, |
| 21 | 21 | } from "shiki"; |
| 22 | -import { DiffLine } from ".."; | |
| 22 | +import { DiffChar, DiffLine } from ".."; | |
| 23 | 23 | import { escapeForSVG, kebabOfThemeStr } from "../util/text"; |
| 24 | 24 | |
| 25 | 25 | interface CodeRendererOptions { |
| @@ -228,6 +228,7 @@ | ||
| 228 | 228 | options: ConversionOptions, |
| 229 | 229 | currLineOffsetFromTop: number, |
| 230 | 230 | newDiffLines: DiffLine[], |
| 231 | + newDiffChars: DiffChar[], | |
| 231 | 232 | ): Promise<Buffer> { |
| 232 | 233 | const strokeWidth = 1; |
| 233 | 234 | const highlightedCodeHtml = await this.highlightCode( |
| @@ -236,13 +237,14 @@ | ||
| 236 | 237 | currLineOffsetFromTop, |
| 237 | 238 | newDiffLines, |
| 238 | 239 | ); |
| 239 | - // console.log(highlightedCodeHtml); | |
| 240 | 240 | |
| 241 | 241 | const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut( |
| 242 | 242 | highlightedCodeHtml, |
| 243 | 243 | options, |
| 244 | + newDiffChars, | |
| 244 | 245 | ); |
| 245 | 246 | const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); |
| 247 | + const borderColor = "#6b6b6b"; | |
| 246 | 248 | |
| 247 | 249 | const lines = code.split("\n"); |
| 248 | 250 | const actualHeight = lines.length * options.lineHeight; |
| @@ -256,12 +258,11 @@ | ||
| 256 | 258 | } |
| 257 | 259 | </style> |
| 258 | 260 | <g> |
| 259 | - <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" /> | |
| 261 | + <rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" /> | |
| 260 | 262 | ${lineBackgrounds} |
| 261 | 263 | ${guts} |
| 262 | 264 | </g> |
| 263 | 265 | </svg>`; |
| 264 | - // console.log(svg); | |
| 265 | 266 | |
| 266 | 267 | return Buffer.from(svg, "utf8"); |
| 267 | 268 | } |
| @@ -269,11 +270,56 @@ | ||
| 269 | 270 | convertShikiHtmlToSvgGut( |
| 270 | 271 | shikiHtml: string, |
| 271 | 272 | options: ConversionOptions, |
| 273 | + diffChars: DiffChar[], | |
| 272 | 274 | ): { guts: string; lineBackgrounds: string } { |
| 273 | 275 | const dom = new JSDOM(shikiHtml); |
| 274 | 276 | const document = dom.window.document; |
| 275 | 277 | |
| 276 | 278 | const lines = Array.from(document.querySelectorAll(".line")); |
| 279 | + | |
| 280 | + const additionSegmentsByLine = new Map< | |
| 281 | + number, | |
| 282 | + Array<{ start: number; end: number }> | |
| 283 | + >(); | |
| 284 | + | |
| 285 | + diffChars.forEach((diff) => { | |
| 286 | + if ( | |
| 287 | + diff.type !== "new" || | |
| 288 | + diff.newLineIndex === undefined || | |
| 289 | + diff.newCharIndexInLine === undefined | |
| 290 | + ) { | |
| 291 | + return; | |
| 292 | + } | |
| 293 | + | |
| 294 | + if (diff.char.includes("\n")) { | |
| 295 | + return; | |
| 296 | + } | |
| 297 | + | |
| 298 | + const start = diff.newCharIndexInLine; | |
| 299 | + const end = start + diff.char.length; | |
| 300 | + const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? []; | |
| 301 | + existing.push({ start, end }); | |
| 302 | + additionSegmentsByLine.set(diff.newLineIndex, existing); | |
| 303 | + }); | |
| 304 | + | |
| 305 | + additionSegmentsByLine.forEach((segments, lineIndex) => { | |
| 306 | + segments.sort((a, b) => a.start - b.start); | |
| 307 | + const merged: Array<{ start: number; end: number }> = []; | |
| 308 | + segments.forEach((segment) => { | |
| 309 | + if (merged.length === 0) { | |
| 310 | + merged.push({ ...segment }); | |
| 311 | + return; | |
| 312 | + } | |
| 313 | + | |
| 314 | + const last = merged[merged.length - 1]; | |
| 315 | + if (segment.start <= last.end) { | |
| 316 | + last.end = Math.max(last.end, segment.end); | |
| 317 | + } else { | |
| 318 | + merged.push({ ...segment }); | |
| 319 | + } | |
| 320 | + }); | |
| 321 | + additionSegmentsByLine.set(lineIndex, merged); | |
| 322 | + }); | |
| 277 | 323 | const svgLines = lines.map((line, index) => { |
| 278 | 324 | const spans = Array.from(line.childNodes) |
| 279 | 325 | .map((node) => { |
| @@ -309,60 +355,37 @@ | ||
| 309 | 355 | return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`; |
| 310 | 356 | }); |
| 311 | 357 | |
| 358 | + const estimatedCharWidth = options.fontSize * 0.6; | |
| 359 | + const additionFill = "rgba(40, 167, 69, 0.25)"; | |
| 360 | + | |
| 312 | 361 | const lineBackgrounds = lines |
| 313 | 362 | .map((line, index) => { |
| 314 | 363 | const classes = line?.getAttribute("class") || ""; |
| 315 | - const bgColor = classes.includes("highlighted") | |
| 316 | - ? this.editorLineHighlight | |
| 317 | - : classes.includes("diff add") | |
| 318 | - ? "rgba(255, 255, 0, 0.2)" | |
| 319 | - : this.editorBackground; | |
| 320 | - | |
| 321 | 364 | const y = index * options.lineHeight; |
| 322 | - const isFirst = index === 0; | |
| 323 | - const isLast = index === lines.length - 1; | |
| 324 | - const isSingleLine = isFirst && isLast; | |
| 325 | - const radius = 10; | |
| 326 | - | |
| 327 | - // Handle single line case (both first and last) | |
| 328 | - if (isSingleLine) { | |
| 329 | - return `<path d="M ${radius} ${y} | |
| 330 | - L ${options.dimensions.width - radius} ${y} | |
| 331 | - Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius} | |
| 332 | - L ${options.dimensions.width} ${y + options.lineHeight - radius} | |
| 333 | - Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight} | |
| 334 | - L ${radius} ${y + options.lineHeight} | |
| 335 | - Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius} | |
| 336 | - L ${0} ${y + radius} | |
| 337 | - Q ${0} ${y} ${radius} ${y} | |
| 338 | - Z" | |
| 339 | - fill="${bgColor}" />`; | |
| 365 | + const segments = additionSegmentsByLine.get(index) ?? []; | |
| 366 | + const backgrounds: string[] = []; | |
| 367 | + | |
| 368 | + if (classes.includes("highlighted")) { | |
| 369 | + backgrounds.push( | |
| 370 | + `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`, | |
| 371 | + ); | |
| 340 | 372 | } |
| 341 | 373 | |
| 342 | - // SVG notes: | |
| 343 | - // By default SVGs have anti-aliasing on. | |
| 344 | - // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps. | |
| 345 | - // Turning it off with 'shape-rendering="crispEdges"' solves the issue. | |
| 346 | - return isFirst | |
| 347 | - ? `<path d="M ${0} ${y + options.lineHeight} | |
| 348 | - L ${0} ${y + radius} | |
| 349 | - Q ${0} ${y} ${radius} ${y} | |
| 350 | - L ${options.dimensions.width - radius} ${y} | |
| 351 | - Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius} | |
| 352 | - L ${options.dimensions.width} ${y + options.lineHeight} | |
| 353 | - Z" | |
| 354 | - fill="${bgColor}" />` | |
| 355 | - : isLast | |
| 356 | - ? `<path d="M ${0} ${y} | |
| 357 | - L ${0} ${y + options.lineHeight - radius} | |
| 358 | - Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight} | |
| 359 | - L ${options.dimensions.width - radius} ${y + options.lineHeight} | |
| 360 | - Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10} | |
| 361 | - L ${options.dimensions.width} ${y} | |
| 362 | - Z" | |
| 363 | - fill="${bgColor}" />` | |
| 364 | - : `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`; | |
| 374 | + segments.forEach(({ start, end }) => { | |
| 375 | + const widthInChars = Math.max(end - start, 0); | |
| 376 | + if (widthInChars <= 0) { | |
| 377 | + return; | |
| 378 | + } | |
| 379 | + const x = start * estimatedCharWidth; | |
| 380 | + const segmentWidth = widthInChars * estimatedCharWidth; | |
| 381 | + backgrounds.push( | |
| 382 | + `<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`, | |
| 383 | + ); | |
| 384 | + }); | |
| 385 | + | |
| 386 | + return backgrounds.join("\n"); | |
| 365 | 387 | }) |
| 388 | + .filter((bg) => bg.length > 0) | |
| 366 | 389 | .join("\n"); |
| 367 | 390 | |
| 368 | 391 | return { |
| @@ -394,6 +417,7 @@ | ||
| 394 | 417 | options: ConversionOptions, |
| 395 | 418 | currLineOffsetFromTop: number, |
| 396 | 419 | newDiffLines: DiffLine[], |
| 420 | + newDiffChars: DiffChar[], | |
| 397 | 421 | ): Promise<DataUri> { |
| 398 | 422 | switch (options.imageType) { |
| 399 | 423 | // case "png": |
| @@ -413,6 +437,7 @@ | ||
| 413 | 437 | options, |
| 414 | 438 | currLineOffsetFromTop, |
| 415 | 439 | newDiffLines, |
| 440 | + newDiffChars, | |
| 416 | 441 | ); |
| 417 | 442 | return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; |
| 418 | 443 | } |
modified core/commands/slash/built-in-legacy/onboard.ts +2 −5
| @@ -1,11 +1,8 @@ | ||
| 1 | 1 | import ignore from "ignore"; |
| 2 | 2 | |
| 3 | 3 | import type { FileType, IDE, SlashCommand } from "../../.."; |
| 4 | -import { | |
| 5 | - DEFAULT_IGNORE, | |
| 6 | - getGlobalContinueIgArray, | |
| 7 | - gitIgArrayFromFile, | |
| 8 | -} from "../../../indexing/ignore"; | |
| 4 | +import { getGlobalContinueIgArray } from "../../../indexing/continueignore"; | |
| 5 | +import { DEFAULT_IGNORE, gitIgArrayFromFile } from "../../../indexing/ignore"; | |
| 9 | 6 | import { renderChatMessage } from "../../../util/messageContent"; |
| 10 | 7 | import { |
| 11 | 8 | findUriInDirs, |
added core/commands/slash/ruleBlockSlashCommand.ts +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { RuleWithSource, SlashCommandWithSource } from "../.."; | |
| 2 | + | |
| 3 | +export function convertRuleBlockToSlashCommand( | |
| 4 | + rule: RuleWithSource, | |
| 5 | +): SlashCommandWithSource { | |
| 6 | + return { | |
| 7 | + name: | |
| 8 | + rule.name || | |
| 9 | + (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), | |
| 10 | + description: rule.description ?? "", | |
| 11 | + prompt: rule.rule, | |
| 12 | + source: "invokable-rule", | |
| 13 | + promptFile: rule.ruleFile, | |
| 14 | + }; | |
| 15 | +} |
added core/commands/slash/ruleBlockSlashCommand.vitest.ts +93 −0
| @@ -0,0 +1,93 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { RuleWithSource } from "../.."; | |
| 3 | +import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand"; | |
| 4 | + | |
| 5 | +describe("convertRuleBlockToSlashCommand", () => { | |
| 6 | + it("should convert a rule with all properties to a slash command", () => { | |
| 7 | + const rule: RuleWithSource = { | |
| 8 | + name: "Code Review", | |
| 9 | + rule: "Review this code for best practices", | |
| 10 | + description: "Performs a code review", | |
| 11 | + source: "rules-block", | |
| 12 | + ruleFile: "/path/to/rules.yaml", | |
| 13 | + invokable: true, | |
| 14 | + }; | |
| 15 | + | |
| 16 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 17 | + | |
| 18 | + expect(result).toEqual({ | |
| 19 | + name: "Code Review", | |
| 20 | + description: "Performs a code review", | |
| 21 | + prompt: "Review this code for best practices", | |
| 22 | + source: "invokable-rule", | |
| 23 | + promptFile: "/path/to/rules.yaml", | |
| 24 | + }); | |
| 25 | + }); | |
| 26 | + | |
| 27 | + it("should handle a rule without name", () => { | |
| 28 | + const rule: RuleWithSource = { | |
| 29 | + rule: "Review this code", | |
| 30 | + source: "rules-block", | |
| 31 | + invokable: true, | |
| 32 | + }; | |
| 33 | + | |
| 34 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 35 | + | |
| 36 | + expect(result.name).toBe("Review this code"); | |
| 37 | + expect(result.prompt).toBe("Review this code"); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should truncate long rule text when used as name", () => { | |
| 41 | + const rule: RuleWithSource = { | |
| 42 | + rule: "This is a very long rule text that should be truncated", | |
| 43 | + source: "rules-block", | |
| 44 | + invokable: true, | |
| 45 | + }; | |
| 46 | + | |
| 47 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 48 | + | |
| 49 | + expect(result.name).toBe("This is a very long ..."); | |
| 50 | + expect(result.prompt).toBe( | |
| 51 | + "This is a very long rule text that should be truncated", | |
| 52 | + ); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("should handle a rule without description", () => { | |
| 56 | + const rule: RuleWithSource = { | |
| 57 | + name: "Test Rule", | |
| 58 | + rule: "Test rule content", | |
| 59 | + source: "rules-block", | |
| 60 | + invokable: true, | |
| 61 | + }; | |
| 62 | + | |
| 63 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 64 | + | |
| 65 | + expect(result.description).toBe(""); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + it("should use rule text as the prompt", () => { | |
| 69 | + const rule: RuleWithSource = { | |
| 70 | + name: "Explain Code", | |
| 71 | + rule: "Explain what this code does in simple terms", | |
| 72 | + source: "rules-block", | |
| 73 | + invokable: true, | |
| 74 | + }; | |
| 75 | + | |
| 76 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 77 | + | |
| 78 | + expect(result.prompt).toBe("Explain what this code does in simple terms"); | |
| 79 | + }); | |
| 80 | + | |
| 81 | + it("should always set source to 'invokable-rule'", () => { | |
| 82 | + const rule: RuleWithSource = { | |
| 83 | + name: "Test", | |
| 84 | + rule: "Test", | |
| 85 | + source: "default-chat", | |
| 86 | + invokable: true, | |
| 87 | + }; | |
| 88 | + | |
| 89 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 90 | + | |
| 91 | + expect(result.source).toBe("invokable-rule"); | |
| 92 | + }); | |
| 93 | +}); |
modified core/config/ConfigHandler.ts +23 −23
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | import { Logger } from "../util/Logger.js"; |
| 22 | 22 | import { Telemetry } from "../util/posthog.js"; |
| 23 | 23 | import { |
| 24 | - ASSISTANTS, | |
| 25 | 24 | getAllDotContinueDefinitionFiles, |
| 26 | 25 | LoadAssistantFilesOptions, |
| 27 | 26 | } from "./loadLocalAssistants.js"; |
| @@ -60,27 +59,17 @@ | ||
| 60 | 59 | |
| 61 | 60 | constructor( |
| 62 | 61 | private readonly ide: IDE, |
| 63 | - private ideSettingsPromise: Promise<IdeSettings>, | |
| 64 | 62 | private llmLogger: ILLMLogger, |
| 65 | - sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, | |
| 63 | + initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, | |
| 66 | 64 | ) { |
| 67 | - this.ide = ide; | |
| 68 | - this.ideSettingsPromise = ideSettingsPromise; | |
| 69 | - | |
| 70 | 65 | this.controlPlaneClient = new ControlPlaneClient( |
| 71 | - sessionInfoPromise, | |
| 72 | - ideSettingsPromise, | |
| 73 | - this.ide.getIdeInfo(), | |
| 66 | + initialSessionInfoPromise, | |
| 67 | + this.ide, | |
| 74 | 68 | ); |
| 75 | 69 | |
| 76 | 70 | // This profile manager will always be available |
| 77 | 71 | this.globalLocalProfileManager = new ProfileLifecycleManager( |
| 78 | - new LocalProfileLoader( | |
| 79 | - ide, | |
| 80 | - ideSettingsPromise, | |
| 81 | - this.controlPlaneClient, | |
| 82 | - this.llmLogger, | |
| 83 | - ), | |
| 72 | + new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger), | |
| 84 | 73 | this.ide, |
| 85 | 74 | ); |
| 86 | 75 | |
| @@ -98,6 +87,7 @@ | ||
| 98 | 87 | } |
| 99 | 88 | |
| 100 | 89 | private workspaceDirs: string[] | null = null; |
| 90 | + | |
| 101 | 91 | async getWorkspaceId() { |
| 102 | 92 | if (!this.workspaceDirs) { |
| 103 | 93 | this.workspaceDirs = await this.ide.getWorkspaceDirs(); |
| @@ -114,6 +104,13 @@ | ||
| 114 | 104 | const signal = this.cascadeAbortController.signal; |
| 115 | 105 | this.workspaceDirs = null; // forces workspace dirs reload |
| 116 | 106 | |
| 107 | + // Always update globalLocalProfileManager before recreating all the loaders | |
| 108 | + // during every cascadeInit so it holds the most recent controlPlaneClient. | |
| 109 | + this.globalLocalProfileManager = new ProfileLifecycleManager( | |
| 110 | + new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger), | |
| 111 | + this.ide, | |
| 112 | + ); | |
| 113 | + | |
| 117 | 114 | try { |
| 118 | 115 | const { orgs, errors } = await this.getOrgs(); |
| 119 | 116 | |
| @@ -203,6 +200,8 @@ | ||
| 203 | 200 | message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`, |
| 204 | 201 | }); |
| 205 | 202 | } |
| 203 | + } else { | |
| 204 | + PolicySingleton.getInstance().policy = null; | |
| 206 | 205 | } |
| 207 | 206 | // Load local org if not signed in or hub orgs fail |
| 208 | 207 | try { |
| @@ -247,7 +246,6 @@ | ||
| 247 | 246 | versionSlug: assistant.configResult.config?.version ?? "latest", |
| 248 | 247 | controlPlaneClient: this.controlPlaneClient, |
| 249 | 248 | ide: this.ide, |
| 250 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 251 | 249 | llmLogger: this.llmLogger, |
| 252 | 250 | rawYaml: assistant.rawYaml, |
| 253 | 251 | orgScopeId: orgScopeId, |
| @@ -339,7 +337,7 @@ | ||
| 339 | 337 | |
| 340 | 338 | async getLocalProfiles(options: LoadAssistantFilesOptions) { |
| 341 | 339 | /** |
| 342 | - * Users can define as many local assistants as they want in a `.continue/assistants` folder | |
| 340 | + * Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder | |
| 343 | 341 | */ |
| 344 | 342 | |
| 345 | 343 | // Local customization disabled for on-premise deployments |
| @@ -358,12 +356,16 @@ | ||
| 358 | 356 | const assistantFiles = await getAllDotContinueDefinitionFiles( |
| 359 | 357 | this.ide, |
| 360 | 358 | options, |
| 361 | - ASSISTANTS, | |
| 359 | + "assistants", | |
| 360 | + ); | |
| 361 | + const agentFiles = await getAllDotContinueDefinitionFiles( | |
| 362 | + this.ide, | |
| 363 | + options, | |
| 364 | + "agents", | |
| 362 | 365 | ); |
| 363 | - const profiles = assistantFiles.map((assistant) => { | |
| 366 | + const profiles = [...assistantFiles, ...agentFiles].map((assistant) => { | |
| 364 | 367 | return new LocalProfileLoader( |
| 365 | 368 | this.ide, |
| 366 | - this.ideSettingsPromise, | |
| 367 | 369 | this.controlPlaneClient, |
| 368 | 370 | this.llmLogger, |
| 369 | 371 | assistant, |
| @@ -388,7 +390,6 @@ | ||
| 388 | 390 | |
| 389 | 391 | // Ide settings change: refresh session and cascade refresh from the top |
| 390 | 392 | async updateIdeSettings(ideSettings: IdeSettings) { |
| 391 | - this.ideSettingsPromise = Promise.resolve(ideSettings); | |
| 392 | 393 | this.abortCascade(); |
| 393 | 394 | await this.cascadeInit("IDE settings update"); |
| 394 | 395 | } |
| @@ -426,8 +427,7 @@ | ||
| 426 | 427 | if (reload) { |
| 427 | 428 | this.controlPlaneClient = new ControlPlaneClient( |
| 428 | 429 | Promise.resolve(sessionInfo), |
| 429 | - this.ideSettingsPromise, | |
| 430 | - this.ide.getIdeInfo(), | |
| 430 | + this.ide, | |
| 431 | 431 | ); |
| 432 | 432 | this.abortCascade(); |
| 433 | 433 | await this.cascadeInit("Control plane session info update"); |
added core/config/createNewAssistantFile.ts +59 −0
| @@ -0,0 +1,59 @@ | ||
| 1 | +import { IDE } from ".."; | |
| 2 | +import { joinPathsToUri } from "../util/uri"; | |
| 3 | + | |
| 4 | +const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file | |
| 5 | +# It is used to define custom AI agents within Continue | |
| 6 | +# Each agent file can be accessed by selecting it from the agent dropdown | |
| 7 | + | |
| 8 | +# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference | |
| 9 | + | |
| 10 | +name: Example Agent | |
| 11 | +version: 1.0.0 | |
| 12 | +schema: v1 | |
| 13 | + | |
| 14 | +# Models define which AI models this agent can use | |
| 15 | +# https://docs.continue.dev/customization/models | |
| 16 | +models: | |
| 17 | + - name: my gpt-5 | |
| 18 | + provider: openai | |
| 19 | + model: gpt-5 | |
| 20 | + apiKey: YOUR_OPENAI_API_KEY_HERE | |
| 21 | + - uses: ollama/qwen2.5-coder-7b | |
| 22 | + - uses: anthropic/claude-4-sonnet | |
| 23 | + with: | |
| 24 | + ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }} | |
| 25 | + | |
| 26 | +# MCP Servers the agent can use | |
| 27 | +# https://docs.continue.dev/customization/mcp-tools | |
| 28 | +mcpServers: | |
| 29 | + - uses: anthropic/memory-mcp | |
| 30 | +`; | |
| 31 | + | |
| 32 | +export async function createNewAssistantFile( | |
| 33 | + ide: IDE, | |
| 34 | + assistantPath: string | undefined, | |
| 35 | +): Promise<void> { | |
| 36 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 37 | + if (workspaceDirs.length === 0) { | |
| 38 | + throw new Error( | |
| 39 | + "No workspace directories found. Make sure you've opened a folder in your IDE.", | |
| 40 | + ); | |
| 41 | + } | |
| 42 | + | |
| 43 | + const baseDirUri = joinPathsToUri( | |
| 44 | + workspaceDirs[0], | |
| 45 | + assistantPath ?? ".continue/agents", | |
| 46 | + ); | |
| 47 | + | |
| 48 | + // Find the first available filename | |
| 49 | + let counter = 0; | |
| 50 | + let assistantFileUri: string; | |
| 51 | + do { | |
| 52 | + const suffix = counter === 0 ? "" : `-${counter}`; | |
| 53 | + assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`); | |
| 54 | + counter++; | |
| 55 | + } while (await ide.fileExists(assistantFileUri)); | |
| 56 | + | |
| 57 | + await ide.writeFile(assistantFileUri, DEFAULT_ASSISTANT_FILE); | |
| 58 | + await ide.openFile(assistantFileUri); | |
| 59 | +} |
modified core/config/default.ts +1 −30
| @@ -1,37 +1,8 @@ | ||
| 1 | 1 | import { ConfigYaml } from "@continuedev/config-yaml"; |
| 2 | 2 | |
| 3 | -export const defaultContextProvidersVsCode: NonNullable< | |
| 4 | - ConfigYaml["context"] | |
| 5 | ->[number][] = [ | |
| 6 | - { provider: "code" }, | |
| 7 | - { provider: "docs" }, | |
| 8 | - { provider: "diff" }, | |
| 9 | - { provider: "terminal" }, | |
| 10 | - { provider: "problems" }, | |
| 11 | - { provider: "folder" }, | |
| 12 | - { provider: "codebase" }, | |
| 13 | -]; | |
| 14 | - | |
| 15 | -export const defaultContextProvidersJetBrains: NonNullable< | |
| 16 | - ConfigYaml["context"] | |
| 17 | ->[number][] = [ | |
| 18 | - { provider: "diff" }, | |
| 19 | - { provider: "folder" }, | |
| 20 | - { provider: "codebase" }, | |
| 21 | -]; | |
| 22 | - | |
| 23 | 3 | export const defaultConfig: ConfigYaml = { |
| 24 | - name: "Local Assistant", | |
| 4 | + name: "Local Agent", | |
| 25 | 5 | version: "1.0.0", |
| 26 | 6 | schema: "v1", |
| 27 | 7 | models: [], |
| 28 | - context: defaultContextProvidersVsCode, | |
| 29 | -}; | |
| 30 | - | |
| 31 | -export const defaultConfigJetBrains: ConfigYaml = { | |
| 32 | - name: "Local Assistant", | |
| 33 | - version: "1.0.0", | |
| 34 | - schema: "v1", | |
| 35 | - models: [], | |
| 36 | - context: defaultContextProvidersJetBrains, | |
| 37 | 8 | }; |
modified core/config/load.ts +43 −60
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | ContinueRcJson, |
| 20 | 20 | CustomContextProvider, |
| 21 | 21 | EmbeddingsProviderDescription, |
| 22 | - IContextProvider, | |
| 23 | 22 | IDE, |
| 24 | 23 | IdeInfo, |
| 25 | 24 | IdeSettings, |
| @@ -36,10 +35,6 @@ | ||
| 36 | 35 | import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand"; |
| 37 | 36 | import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand"; |
| 38 | 37 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 39 | -import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; | |
| 40 | -import CustomContextProviderClass from "../context/providers/CustomContextProvider"; | |
| 41 | -import FileContextProvider from "../context/providers/FileContextProvider"; | |
| 42 | -import { contextProviderClassFromName } from "../context/providers/index"; | |
| 43 | 38 | import { useHub } from "../control-plane/env"; |
| 44 | 39 | import { BaseLLM } from "../llm"; |
| 45 | 40 | import { LLMClasses, llmFromDescription } from "../llm/llms"; |
| @@ -62,9 +57,12 @@ | ||
| 62 | 57 | } from "../util/paths"; |
| 63 | 58 | import { localPathToUri } from "../util/pathToUri"; |
| 64 | 59 | |
| 65 | -import { getToolsForIde } from "../tools"; | |
| 60 | +import { PolicySingleton } from "../control-plane/PolicySingleton"; | |
| 61 | +import CustomContextProviderClass from "../context/providers/CustomContextProvider"; | |
| 62 | +import { getBaseToolDefinitions } from "../tools"; | |
| 66 | 63 | import { resolveRelativePathInDir } from "../util/ideUtils"; |
| 67 | 64 | import { getWorkspaceRcConfigs } from "./json/loadRcConfigs"; |
| 65 | +import { loadConfigContextProviders } from "./loadContextProviders"; | |
| 68 | 66 | import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; |
| 69 | 67 | import { |
| 70 | 68 | getModelByRole, |
| @@ -217,8 +215,8 @@ | ||
| 217 | 215 | // Prepare models |
| 218 | 216 | for (const model of models) { |
| 219 | 217 | model.requestOptions = { |
| 220 | - ...model.requestOptions, | |
| 221 | 218 | ...config.requestOptions, |
| 219 | + ...model.requestOptions, | |
| 222 | 220 | }; |
| 223 | 221 | if (roles !== undefined) { |
| 224 | 222 | model.roles = model.roles ?? roles; |
| @@ -229,7 +227,7 @@ | ||
| 229 | 227 | export function isContextProviderWithParams( |
| 230 | 228 | contextProvider: CustomContextProvider | ContextProviderWithParams, |
| 231 | 229 | ): contextProvider is ContextProviderWithParams { |
| 232 | - return (contextProvider as ContextProviderWithParams).name !== undefined; | |
| 230 | + return "name" in contextProvider && !!contextProvider.name; | |
| 233 | 231 | } |
| 234 | 232 | |
| 235 | 233 | /** Only difference between intermediate and final configs is the `models` array */ |
| @@ -285,6 +283,7 @@ | ||
| 285 | 283 | ...desc, |
| 286 | 284 | model: modelName, |
| 287 | 285 | title: modelName, |
| 286 | + isFromAutoDetect: true, | |
| 288 | 287 | }, |
| 289 | 288 | ide.readFile.bind(ide), |
| 290 | 289 | getUriFromPath, |
| @@ -322,6 +321,7 @@ | ||
| 322 | 321 | ...desc.options, |
| 323 | 322 | model: modelName, |
| 324 | 323 | logger: llmLogger, |
| 324 | + isFromAutoDetect: true, | |
| 325 | 325 | }, |
| 326 | 326 | }), |
| 327 | 327 | ); |
| @@ -386,50 +386,25 @@ | ||
| 386 | 386 | |
| 387 | 387 | applyRequestOptionsToModels(tabAutocompleteModels, config); |
| 388 | 388 | |
| 389 | - // These context providers are always included, regardless of what, if anything, | |
| 390 | - // the user has configured in config.json | |
| 391 | - | |
| 392 | - const codebaseContextParams = | |
| 393 | - ( | |
| 394 | - (config.contextProviders || []) | |
| 395 | - .filter(isContextProviderWithParams) | |
| 396 | - .find((cp) => cp.name === "codebase") as | |
| 397 | - | ContextProviderWithParams | |
| 398 | - | undefined | |
| 399 | - )?.params || {}; | |
| 400 | - | |
| 401 | - const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})]; | |
| 402 | - | |
| 403 | - const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( | |
| 404 | - ({ description: { title } }) => title, | |
| 405 | - ); | |
| 406 | - | |
| 407 | - // Context providers | |
| 408 | - const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS; | |
| 409 | - | |
| 410 | - for (const provider of config.contextProviders || []) { | |
| 411 | - if (isContextProviderWithParams(provider)) { | |
| 412 | - const cls = contextProviderClassFromName(provider.name) as any; | |
| 413 | - if (!cls) { | |
| 414 | - if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) { | |
| 415 | - console.warn(`Unknown context provider ${provider.name}`); | |
| 416 | - } | |
| 417 | - | |
| 418 | - continue; | |
| 419 | - } | |
| 420 | - const instance: IContextProvider = new cls(provider.params); | |
| 421 | - | |
| 422 | - // Handle continue-proxy | |
| 423 | - if (instance.description.title === "continue-proxy") { | |
| 424 | - (instance as ContinueProxyContextProvider).workOsAccessToken = | |
| 425 | - workOsAccessToken; | |
| 426 | - } | |
| 389 | + // Load context providers | |
| 390 | + const { providers: contextProviders, errors: contextErrors } = | |
| 391 | + loadConfigContextProviders( | |
| 392 | + config.contextProviders | |
| 393 | + ?.filter((cp) => isContextProviderWithParams(cp)) | |
| 394 | + .map((cp) => ({ | |
| 395 | + provider: (cp as ContextProviderWithParams).name, | |
| 396 | + params: (cp as ContextProviderWithParams).params, | |
| 397 | + })), | |
| 398 | + !!config.docs?.length, | |
| 399 | + ideInfo.ideType, | |
| 400 | + ); | |
| 427 | 401 | |
| 428 | - contextProviders.push(instance); | |
| 429 | - } else { | |
| 430 | - contextProviders.push(new CustomContextProviderClass(provider)); | |
| 402 | + for (const cp of config.contextProviders ?? []) { | |
| 403 | + if (!isContextProviderWithParams(cp)) { | |
| 404 | + contextProviders.push(new CustomContextProviderClass(cp)); | |
| 431 | 405 | } |
| 432 | 406 | } |
| 407 | + errors.push(...contextErrors); | |
| 433 | 408 | |
| 434 | 409 | // Embeddings Provider |
| 435 | 410 | function getEmbeddingsILLM( |
| @@ -526,7 +501,7 @@ | ||
| 526 | 501 | const continueConfig: ContinueConfig = { |
| 527 | 502 | ...config, |
| 528 | 503 | contextProviders, |
| 529 | - tools: await getToolsForIde(ide), | |
| 504 | + tools: getBaseToolDefinitions(), | |
| 530 | 505 | mcpServerStatuses: [], |
| 531 | 506 | slashCommands: [], |
| 532 | 507 | modelsByRole: { |
| @@ -570,16 +545,23 @@ | ||
| 570 | 545 | |
| 571 | 546 | // Trigger MCP server refreshes (Config is reloaded again once connected!) |
| 572 | 547 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 573 | - mcpManager.setConnections( | |
| 574 | - (config.experimental?.modelContextProtocolServers ?? []).map( | |
| 575 | - (server, index) => ({ | |
| 576 | - id: `continue-mcp-server-${index + 1}`, | |
| 577 | - name: `MCP Server`, | |
| 578 | - ...server, | |
| 579 | - }), | |
| 580 | - ), | |
| 581 | - false, | |
| 582 | - ); | |
| 548 | + | |
| 549 | + const orgPolicy = PolicySingleton.getInstance().policy; | |
| 550 | + if (orgPolicy?.policy?.allowMcpServers === false) { | |
| 551 | + await mcpManager.shutdown(); | |
| 552 | + } else { | |
| 553 | + mcpManager.setConnections( | |
| 554 | + (config.experimental?.modelContextProtocolServers ?? []).map( | |
| 555 | + (server, index) => ({ | |
| 556 | + id: `continue-mcp-server-${index + 1}`, | |
| 557 | + name: `MCP Server`, | |
| 558 | + ...server, | |
| 559 | + requestOptions: config.requestOptions, | |
| 560 | + }), | |
| 561 | + ), | |
| 562 | + false, | |
| 563 | + ); | |
| 564 | + } | |
| 583 | 565 | |
| 584 | 566 | // Handle experimental modelRole config values for apply and edit |
| 585 | 567 | const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; |
| @@ -654,6 +636,7 @@ | ||
| 654 | 636 | apiKeyLocation: llm.apiKeyLocation, |
| 655 | 637 | envSecretLocations: llm.envSecretLocations, |
| 656 | 638 | sourceFile: llm.sourceFile, |
| 639 | + isFromAutoDetect: llm.isFromAutoDetect, | |
| 657 | 640 | }; |
| 658 | 641 | } |
| 659 | 642 |
added core/config/loadContextProviders.ts +95 −0
| @@ -0,0 +1,95 @@ | ||
| 1 | +import { | |
| 2 | + AssistantUnrolledNonNullable, | |
| 3 | + ConfigValidationError, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 5 | +import { IContextProvider, IdeType } from ".."; | |
| 6 | +import { contextProviderClassFromName } from "../context/providers"; | |
| 7 | +import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider"; | |
| 8 | +import DiffContextProvider from "../context/providers/DiffContextProvider"; | |
| 9 | +import DocsContextProvider from "../context/providers/DocsContextProvider"; | |
| 10 | +import FileContextProvider from "../context/providers/FileContextProvider"; | |
| 11 | +import ProblemsContextProvider from "../context/providers/ProblemsContextProvider"; | |
| 12 | +import RulesContextProvider from "../context/providers/RulesContextProvider"; | |
| 13 | +import TerminalContextProvider from "../context/providers/TerminalContextProvider"; | |
| 14 | + | |
| 15 | +/* | |
| 16 | + Loads context providers based on configuration | |
| 17 | + - default providers will always be loaded, using config params if present | |
| 18 | + - other providers will be loaded if configured | |
| 19 | + | |
| 20 | + NOTE the MCPContextProvider is added in doLoadConfig if any resources are present | |
| 21 | +*/ | |
| 22 | +export function loadConfigContextProviders( | |
| 23 | + configContext: AssistantUnrolledNonNullable["context"], | |
| 24 | + hasDocs: boolean, | |
| 25 | + ideType: IdeType, | |
| 26 | +): { | |
| 27 | + providers: IContextProvider[]; | |
| 28 | + errors: ConfigValidationError[]; | |
| 29 | +} { | |
| 30 | + const providers: IContextProvider[] = []; | |
| 31 | + const errors: ConfigValidationError[] = []; | |
| 32 | + | |
| 33 | + const defaultProviders: IContextProvider[] = [ | |
| 34 | + new FileContextProvider({}), | |
| 35 | + new CurrentFileContextProvider({}), | |
| 36 | + new DiffContextProvider({}), | |
| 37 | + new TerminalContextProvider({}), | |
| 38 | + new ProblemsContextProvider({}), | |
| 39 | + new RulesContextProvider({}), | |
| 40 | + ]; | |
| 41 | + | |
| 42 | + // Add from config | |
| 43 | + if (configContext) { | |
| 44 | + for (const config of configContext) { | |
| 45 | + const cls = contextProviderClassFromName(config.provider) as any; | |
| 46 | + if ( | |
| 47 | + !cls && | |
| 48 | + !defaultProviders.find((p) => p.description.title === config.provider) | |
| 49 | + ) { | |
| 50 | + errors.push({ | |
| 51 | + fatal: false, | |
| 52 | + message: `Unknown context provider ${config.provider}`, | |
| 53 | + }); | |
| 54 | + continue; | |
| 55 | + } | |
| 56 | + providers.push( | |
| 57 | + new cls({ | |
| 58 | + name: config.name, | |
| 59 | + ...config.params, | |
| 60 | + }), | |
| 61 | + ); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + | |
| 65 | + // Add from defaults if not found in config | |
| 66 | + for (const defaultProvider of defaultProviders) { | |
| 67 | + if ( | |
| 68 | + !providers.find( | |
| 69 | + (p) => p.description.title === defaultProvider.description.title, | |
| 70 | + ) | |
| 71 | + ) { | |
| 72 | + providers.push(defaultProvider); | |
| 73 | + } | |
| 74 | + } | |
| 75 | + | |
| 76 | + if (hasDocs && !providers?.some((cp) => cp.description.title === "docs")) { | |
| 77 | + providers.push(new DocsContextProvider({})); | |
| 78 | + } | |
| 79 | + | |
| 80 | + // @problems and @terminal are not supported in jetbrains | |
| 81 | + const filteredProviders = providers.filter((pv) => { | |
| 82 | + if (ideType === "jetbrains") { | |
| 83 | + return ( | |
| 84 | + pv.description.title !== TerminalContextProvider.description.title && | |
| 85 | + pv.description.title !== ProblemsContextProvider.description.title | |
| 86 | + ); | |
| 87 | + } | |
| 88 | + return true; | |
| 89 | + }); | |
| 90 | + | |
| 91 | + return { | |
| 92 | + providers: filteredProviders, | |
| 93 | + errors, | |
| 94 | + }; | |
| 95 | +} |
added core/config/loadContextProviders.vitest.ts +590 −0
| @@ -0,0 +1,590 @@ | ||
| 1 | +import { beforeEach, describe, expect, it, MockedFunction, vi } from "vitest"; | |
| 2 | +import { contextProviderClassFromName } from "../context/providers"; | |
| 3 | +import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider"; | |
| 4 | +import DiffContextProvider from "../context/providers/DiffContextProvider"; | |
| 5 | +import FileContextProvider from "../context/providers/FileContextProvider"; | |
| 6 | +import ProblemsContextProvider from "../context/providers/ProblemsContextProvider"; | |
| 7 | +import RulesContextProvider from "../context/providers/RulesContextProvider"; | |
| 8 | +import TerminalContextProvider from "../context/providers/TerminalContextProvider"; | |
| 9 | +import { loadConfigContextProviders } from "./loadContextProviders"; | |
| 10 | + | |
| 11 | +// Mock the contextProviderClassFromName function | |
| 12 | +vi.mock("../context/providers", () => ({ | |
| 13 | + contextProviderClassFromName: vi.fn(), | |
| 14 | +})); | |
| 15 | + | |
| 16 | +// Mock all provider classes | |
| 17 | +vi.mock("../context/providers/CurrentFileContextProvider", () => ({ | |
| 18 | + default: vi.fn().mockImplementation((options) => ({ | |
| 19 | + description: { title: "current-file" }, | |
| 20 | + options, | |
| 21 | + })), | |
| 22 | +})); | |
| 23 | + | |
| 24 | +vi.mock("../context/providers/DiffContextProvider", () => ({ | |
| 25 | + default: vi.fn().mockImplementation((options) => ({ | |
| 26 | + description: { title: "diff" }, | |
| 27 | + options, | |
| 28 | + })), | |
| 29 | +})); | |
| 30 | + | |
| 31 | +vi.mock("../context/providers/FileContextProvider", () => ({ | |
| 32 | + default: vi.fn().mockImplementation((options) => ({ | |
| 33 | + description: { title: "file" }, | |
| 34 | + options, | |
| 35 | + })), | |
| 36 | +})); | |
| 37 | + | |
| 38 | +vi.mock("../context/providers/ProblemsContextProvider", () => { | |
| 39 | + const MockProblemsContextProvider = vi.fn().mockImplementation((options) => ({ | |
| 40 | + description: { title: "problems" }, | |
| 41 | + options, | |
| 42 | + })); | |
| 43 | + (MockProblemsContextProvider as any).description = { title: "problems" }; | |
| 44 | + return { default: MockProblemsContextProvider }; | |
| 45 | +}); | |
| 46 | + | |
| 47 | +vi.mock("../context/providers/RulesContextProvider", () => ({ | |
| 48 | + default: vi.fn().mockImplementation((options) => ({ | |
| 49 | + description: { title: "rules" }, | |
| 50 | + options, | |
| 51 | + })), | |
| 52 | +})); | |
| 53 | + | |
| 54 | +vi.mock("../context/providers/TerminalContextProvider", () => { | |
| 55 | + const MockTerminalContextProvider = vi.fn().mockImplementation((options) => ({ | |
| 56 | + description: { title: "terminal" }, | |
| 57 | + options, | |
| 58 | + })); | |
| 59 | + (MockTerminalContextProvider as any).description = { title: "terminal" }; | |
| 60 | + return { default: MockTerminalContextProvider }; | |
| 61 | +}); | |
| 62 | + | |
| 63 | +const mockedContextProviderClassFromName = | |
| 64 | + contextProviderClassFromName as MockedFunction< | |
| 65 | + typeof contextProviderClassFromName | |
| 66 | + >; | |
| 67 | + | |
| 68 | +beforeEach(() => { | |
| 69 | + vi.clearAllMocks(); | |
| 70 | +}); | |
| 71 | + | |
| 72 | +describe("loadConfigContextProviders", () => { | |
| 73 | + describe("with empty or undefined config", () => { | |
| 74 | + it("should return only default providers when config is undefined", () => { | |
| 75 | + const result = loadConfigContextProviders(undefined, false, "vscode"); | |
| 76 | + | |
| 77 | + expect(result.errors).toEqual([]); | |
| 78 | + expect(result.providers).toHaveLength(6); | |
| 79 | + | |
| 80 | + // Verify all default providers are included | |
| 81 | + const providerTitles = result.providers.map((p) => p.description.title); | |
| 82 | + expect(providerTitles).toEqual( | |
| 83 | + expect.arrayContaining([ | |
| 84 | + "file", | |
| 85 | + "current-file", | |
| 86 | + "diff", | |
| 87 | + "terminal", | |
| 88 | + "problems", | |
| 89 | + "rules", | |
| 90 | + ]), | |
| 91 | + ); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should return only default providers when config is empty array", () => { | |
| 95 | + const result = loadConfigContextProviders([], false, "vscode"); | |
| 96 | + | |
| 97 | + expect(result.errors).toEqual([]); | |
| 98 | + expect(result.providers).toHaveLength(6); | |
| 99 | + | |
| 100 | + const providerTitles = result.providers.map((p) => p.description.title); | |
| 101 | + expect(providerTitles).toEqual( | |
| 102 | + expect.arrayContaining([ | |
| 103 | + "file", | |
| 104 | + "current-file", | |
| 105 | + "diff", | |
| 106 | + "terminal", | |
| 107 | + "problems", | |
| 108 | + "rules", | |
| 109 | + ]), | |
| 110 | + ); | |
| 111 | + }); | |
| 112 | + | |
| 113 | + it("should exclude problems and terminal in jetbrains", () => { | |
| 114 | + const result = loadConfigContextProviders([], false, "jetbrains"); | |
| 115 | + | |
| 116 | + expect(result.errors).toEqual([]); | |
| 117 | + expect(result.providers).toHaveLength(4); | |
| 118 | + | |
| 119 | + const providerTitles = result.providers.map((p) => p.description.title); | |
| 120 | + expect(providerTitles).toEqual( | |
| 121 | + expect.arrayContaining(["file", "current-file", "diff", "rules"]), | |
| 122 | + ); | |
| 123 | + }); | |
| 124 | + }); | |
| 125 | + | |
| 126 | + it("should return default + docs when has docs is true", () => { | |
| 127 | + const result = loadConfigContextProviders([], true, "vscode"); | |
| 128 | + | |
| 129 | + expect(result.errors).toEqual([]); | |
| 130 | + expect(result.providers).toHaveLength(7); | |
| 131 | + | |
| 132 | + const providerTitles = result.providers.map((p) => p.description.title); | |
| 133 | + expect(providerTitles).toEqual( | |
| 134 | + expect.arrayContaining([ | |
| 135 | + "file", | |
| 136 | + "current-file", | |
| 137 | + "diff", | |
| 138 | + "terminal", | |
| 139 | + "problems", | |
| 140 | + "rules", | |
| 141 | + "docs", | |
| 142 | + ]), | |
| 143 | + ); | |
| 144 | + }); | |
| 145 | +}); | |
| 146 | + | |
| 147 | +describe("with valid config", () => { | |
| 148 | + it("should load providers from config with correct parameters", () => { | |
| 149 | + const mockProvider = vi.fn().mockImplementation((options) => ({ | |
| 150 | + description: { title: "custom-provider" }, | |
| 151 | + options, | |
| 152 | + })) as any; | |
| 153 | + | |
| 154 | + mockedContextProviderClassFromName.mockReturnValue(mockProvider); | |
| 155 | + | |
| 156 | + const config = [ | |
| 157 | + { | |
| 158 | + provider: "custom-provider", | |
| 159 | + name: "my-custom-provider", | |
| 160 | + params: { | |
| 161 | + apiKey: "test-key", | |
| 162 | + baseUrl: "https://api.example.com", | |
| 163 | + }, | |
| 164 | + }, | |
| 165 | + ]; | |
| 166 | + | |
| 167 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 168 | + | |
| 169 | + expect(result.errors).toEqual([]); | |
| 170 | + expect(mockedContextProviderClassFromName).toHaveBeenCalledWith( | |
| 171 | + "custom-provider", | |
| 172 | + ); | |
| 173 | + expect(mockProvider).toHaveBeenCalledWith({ | |
| 174 | + name: "my-custom-provider", | |
| 175 | + apiKey: "test-key", | |
| 176 | + baseUrl: "https://api.example.com", | |
| 177 | + }); | |
| 178 | + | |
| 179 | + // Should have custom provider + all defaults | |
| 180 | + expect(result.providers).toHaveLength(7); | |
| 181 | + | |
| 182 | + const customProvider = result.providers.find( | |
| 183 | + (p) => p.description.title === "custom-provider", | |
| 184 | + ); | |
| 185 | + expect(customProvider).toBeDefined(); | |
| 186 | + expect((customProvider as any)?.options).toEqual({ | |
| 187 | + name: "my-custom-provider", | |
| 188 | + apiKey: "test-key", | |
| 189 | + baseUrl: "https://api.example.com", | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + it("should handle multiple providers in config", () => { | |
| 194 | + const mockProvider1 = vi.fn().mockImplementation((options) => ({ | |
| 195 | + description: { title: "provider-1" }, | |
| 196 | + options, | |
| 197 | + })) as any; | |
| 198 | + | |
| 199 | + const mockProvider2 = vi.fn().mockImplementation((options) => ({ | |
| 200 | + description: { title: "provider-2" }, | |
| 201 | + options, | |
| 202 | + })) as any; | |
| 203 | + | |
| 204 | + mockedContextProviderClassFromName | |
| 205 | + .mockReturnValueOnce(mockProvider1) | |
| 206 | + .mockReturnValueOnce(mockProvider2); | |
| 207 | + | |
| 208 | + const config = [ | |
| 209 | + { | |
| 210 | + provider: "provider-1", | |
| 211 | + name: "first-provider", | |
| 212 | + params: { setting1: "value1" }, | |
| 213 | + }, | |
| 214 | + { | |
| 215 | + provider: "provider-2", | |
| 216 | + name: "second-provider", | |
| 217 | + params: { setting2: "value2" }, | |
| 218 | + }, | |
| 219 | + ]; | |
| 220 | + | |
| 221 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 222 | + | |
| 223 | + expect(result.errors).toEqual([]); | |
| 224 | + expect(result.providers).toHaveLength(8); // 2 custom + 6 defaults | |
| 225 | + | |
| 226 | + expect(mockProvider1).toHaveBeenCalledWith({ | |
| 227 | + name: "first-provider", | |
| 228 | + setting1: "value1", | |
| 229 | + }); | |
| 230 | + | |
| 231 | + expect(mockProvider2).toHaveBeenCalledWith({ | |
| 232 | + name: "second-provider", | |
| 233 | + setting2: "value2", | |
| 234 | + }); | |
| 235 | + }); | |
| 236 | + | |
| 237 | + it("should handle config with empty params", () => { | |
| 238 | + const mockProvider = vi.fn().mockImplementation((options) => ({ | |
| 239 | + description: { title: "no-params-provider" }, | |
| 240 | + options, | |
| 241 | + })) as any; | |
| 242 | + | |
| 243 | + mockedContextProviderClassFromName.mockReturnValue(mockProvider); | |
| 244 | + | |
| 245 | + const config = [ | |
| 246 | + { | |
| 247 | + provider: "no-params-provider", | |
| 248 | + name: "simple-provider", | |
| 249 | + params: {}, | |
| 250 | + }, | |
| 251 | + ]; | |
| 252 | + | |
| 253 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 254 | + | |
| 255 | + expect(result.errors).toEqual([]); | |
| 256 | + expect(mockProvider).toHaveBeenCalledWith({ | |
| 257 | + name: "simple-provider", | |
| 258 | + }); | |
| 259 | + }); | |
| 260 | + | |
| 261 | + it("should handle config without params property", () => { | |
| 262 | + const mockProvider = vi.fn().mockImplementation((options) => ({ | |
| 263 | + description: { title: "provider-without-params" }, | |
| 264 | + options, | |
| 265 | + })) as any; | |
| 266 | + | |
| 267 | + mockedContextProviderClassFromName.mockReturnValue(mockProvider); | |
| 268 | + | |
| 269 | + const config = [ | |
| 270 | + { | |
| 271 | + provider: "provider-without-params", | |
| 272 | + name: "minimal-provider", | |
| 273 | + } as any, // Cast to bypass type checking for test | |
| 274 | + ]; | |
| 275 | + | |
| 276 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 277 | + | |
| 278 | + expect(result.errors).toEqual([]); | |
| 279 | + expect(mockProvider).toHaveBeenCalledWith({ | |
| 280 | + name: "minimal-provider", | |
| 281 | + }); | |
| 282 | + }); | |
| 283 | +}); | |
| 284 | + | |
| 285 | +describe("error handling", () => { | |
| 286 | + it("should add error for unknown provider", () => { | |
| 287 | + mockedContextProviderClassFromName.mockReturnValue(undefined); | |
| 288 | + | |
| 289 | + const config = [ | |
| 290 | + { | |
| 291 | + provider: "unknown-provider", | |
| 292 | + name: "test-provider", | |
| 293 | + params: {}, | |
| 294 | + }, | |
| 295 | + ]; | |
| 296 | + | |
| 297 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 298 | + | |
| 299 | + expect(result.errors).toEqual([ | |
| 300 | + { | |
| 301 | + fatal: false, | |
| 302 | + message: "Unknown context provider unknown-provider", | |
| 303 | + }, | |
| 304 | + ]); | |
| 305 | + | |
| 306 | + // Should still have default providers | |
| 307 | + expect(result.providers).toHaveLength(6); | |
| 308 | + expect(mockedContextProviderClassFromName).toHaveBeenCalledWith( | |
| 309 | + "unknown-provider", | |
| 310 | + ); | |
| 311 | + }); | |
| 312 | + | |
| 313 | + it("should handle multiple unknown providers", () => { | |
| 314 | + mockedContextProviderClassFromName.mockReturnValue(undefined); | |
| 315 | + | |
| 316 | + const config = [ | |
| 317 | + { | |
| 318 | + provider: "unknown-1", | |
| 319 | + name: "test-1", | |
| 320 | + params: {}, | |
| 321 | + }, | |
| 322 | + { | |
| 323 | + provider: "unknown-2", | |
| 324 | + name: "test-2", | |
| 325 | + params: {}, | |
| 326 | + }, | |
| 327 | + ]; | |
| 328 | + | |
| 329 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 330 | + | |
| 331 | + expect(result.errors).toEqual([ | |
| 332 | + { | |
| 333 | + fatal: false, | |
| 334 | + message: "Unknown context provider unknown-1", | |
| 335 | + }, | |
| 336 | + { | |
| 337 | + fatal: false, | |
| 338 | + message: "Unknown context provider unknown-2", | |
| 339 | + }, | |
| 340 | + ]); | |
| 341 | + | |
| 342 | + expect(result.providers).toHaveLength(6); // Only defaults | |
| 343 | + }); | |
| 344 | + | |
| 345 | + it("should handle mix of valid and invalid providers", () => { | |
| 346 | + const mockValidProvider = vi.fn().mockImplementation((options) => ({ | |
| 347 | + description: { title: "valid-provider" }, | |
| 348 | + options, | |
| 349 | + })) as any; | |
| 350 | + | |
| 351 | + mockedContextProviderClassFromName | |
| 352 | + .mockReturnValueOnce(mockValidProvider) | |
| 353 | + .mockReturnValueOnce(undefined); | |
| 354 | + | |
| 355 | + const config = [ | |
| 356 | + { | |
| 357 | + provider: "valid-provider", | |
| 358 | + name: "valid", | |
| 359 | + params: { key: "value" }, | |
| 360 | + }, | |
| 361 | + { | |
| 362 | + provider: "invalid-provider", | |
| 363 | + name: "invalid", | |
| 364 | + params: {}, | |
| 365 | + }, | |
| 366 | + ]; | |
| 367 | + | |
| 368 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 369 | + | |
| 370 | + expect(result.errors).toEqual([ | |
| 371 | + { | |
| 372 | + fatal: false, | |
| 373 | + message: "Unknown context provider invalid-provider", | |
| 374 | + }, | |
| 375 | + ]); | |
| 376 | + | |
| 377 | + // Should have valid provider + defaults | |
| 378 | + expect(result.providers).toHaveLength(7); | |
| 379 | + expect(mockValidProvider).toHaveBeenCalledWith({ | |
| 380 | + name: "valid", | |
| 381 | + key: "value", | |
| 382 | + }); | |
| 383 | + }); | |
| 384 | +}); | |
| 385 | + | |
| 386 | +describe("default provider merging", () => { | |
| 387 | + it("should not duplicate providers when config matches defaults", () => { | |
| 388 | + // Mock FileContextProvider to be returned by contextProviderClassFromName | |
| 389 | + mockedContextProviderClassFromName.mockReturnValue(FileContextProvider); | |
| 390 | + | |
| 391 | + const config = [ | |
| 392 | + { | |
| 393 | + provider: "file", | |
| 394 | + name: "custom-file-provider", | |
| 395 | + params: { maxFiles: 100 }, | |
| 396 | + }, | |
| 397 | + ]; | |
| 398 | + | |
| 399 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 400 | + | |
| 401 | + expect(result.errors).toEqual([]); | |
| 402 | + | |
| 403 | + // Should have configured file provider + other defaults (not duplicate file) | |
| 404 | + expect(result.providers).toHaveLength(6); | |
| 405 | + | |
| 406 | + const fileProviders = result.providers.filter( | |
| 407 | + (p) => p.description.title === "file", | |
| 408 | + ); | |
| 409 | + expect(fileProviders).toHaveLength(1); | |
| 410 | + | |
| 411 | + // The configured one should be used (with custom params) | |
| 412 | + expect(FileContextProvider).toHaveBeenCalledWith({ | |
| 413 | + name: "custom-file-provider", | |
| 414 | + maxFiles: 100, | |
| 415 | + }); | |
| 416 | + }); | |
| 417 | + | |
| 418 | + it("should add default providers not present in config", () => { | |
| 419 | + const mockCustomProvider = vi.fn().mockImplementation((options) => ({ | |
| 420 | + description: { title: "custom-only" }, | |
| 421 | + options, | |
| 422 | + })) as any; | |
| 423 | + | |
| 424 | + mockedContextProviderClassFromName.mockReturnValue(mockCustomProvider); | |
| 425 | + | |
| 426 | + const config = [ | |
| 427 | + { | |
| 428 | + provider: "custom-only", | |
| 429 | + name: "custom", | |
| 430 | + params: {}, | |
| 431 | + }, | |
| 432 | + ]; | |
| 433 | + | |
| 434 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 435 | + | |
| 436 | + expect(result.errors).toEqual([]); | |
| 437 | + expect(result.providers).toHaveLength(7); // 1 custom + 6 defaults | |
| 438 | + | |
| 439 | + // All defaults should be present | |
| 440 | + const providerTitles = result.providers.map((p) => p.description.title); | |
| 441 | + expect(providerTitles).toEqual( | |
| 442 | + expect.arrayContaining([ | |
| 443 | + "custom-only", | |
| 444 | + "file", | |
| 445 | + "current-file", | |
| 446 | + "diff", | |
| 447 | + "terminal", | |
| 448 | + "problems", | |
| 449 | + "rules", | |
| 450 | + ]), | |
| 451 | + ); | |
| 452 | + }); | |
| 453 | + | |
| 454 | + it("should preserve order with configured providers first", () => { | |
| 455 | + const mockProvider = vi.fn().mockImplementation((options) => ({ | |
| 456 | + description: { title: "custom-provider" }, | |
| 457 | + options, | |
| 458 | + })) as any; | |
| 459 | + | |
| 460 | + mockedContextProviderClassFromName.mockReturnValue(mockProvider); | |
| 461 | + | |
| 462 | + const config = [ | |
| 463 | + { | |
| 464 | + provider: "custom-provider", | |
| 465 | + name: "custom", | |
| 466 | + params: {}, | |
| 467 | + }, | |
| 468 | + ]; | |
| 469 | + | |
| 470 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 471 | + | |
| 472 | + expect(result.providers[0].description.title).toBe("custom-provider"); | |
| 473 | + | |
| 474 | + // Rest should be defaults in their original order | |
| 475 | + const defaultTitles = result.providers | |
| 476 | + .slice(1) | |
| 477 | + .map((p) => p.description.title); | |
| 478 | + expect(defaultTitles).toEqual([ | |
| 479 | + "file", | |
| 480 | + "current-file", | |
| 481 | + "diff", | |
| 482 | + "terminal", | |
| 483 | + "problems", | |
| 484 | + "rules", | |
| 485 | + ]); | |
| 486 | + }); | |
| 487 | +}); | |
| 488 | + | |
| 489 | +describe("edge cases", () => { | |
| 490 | + it("should handle provider constructor throwing error", () => { | |
| 491 | + const mockProvider = vi.fn().mockImplementation(() => { | |
| 492 | + throw new Error("Provider construction failed"); | |
| 493 | + }) as any; | |
| 494 | + | |
| 495 | + mockedContextProviderClassFromName.mockReturnValue(mockProvider); | |
| 496 | + | |
| 497 | + const config = [ | |
| 498 | + { | |
| 499 | + provider: "failing-provider", | |
| 500 | + name: "failing", | |
| 501 | + params: {}, | |
| 502 | + }, | |
| 503 | + ]; | |
| 504 | + | |
| 505 | + expect(() => loadConfigContextProviders(config, false, "vscode")).toThrow( | |
| 506 | + "Provider construction failed", | |
| 507 | + ); | |
| 508 | + }); | |
| 509 | + | |
| 510 | + it("should handle null provider class", () => { | |
| 511 | + mockedContextProviderClassFromName.mockReturnValue(undefined); | |
| 512 | + | |
| 513 | + const config = [ | |
| 514 | + { | |
| 515 | + provider: "null-provider", | |
| 516 | + name: "null", | |
| 517 | + params: {}, | |
| 518 | + }, | |
| 519 | + ]; | |
| 520 | + | |
| 521 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 522 | + | |
| 523 | + expect(result.errors).toEqual([ | |
| 524 | + { | |
| 525 | + fatal: false, | |
| 526 | + message: "Unknown context provider null-provider", | |
| 527 | + }, | |
| 528 | + ]); | |
| 529 | + }); | |
| 530 | + | |
| 531 | + it("should handle provider with same title as default but different implementation", () => { | |
| 532 | + // Mock a provider with same title as a default | |
| 533 | + const mockFileProvider = vi.fn().mockImplementation((options) => ({ | |
| 534 | + description: { title: "file" }, // Same title as FileContextProvider | |
| 535 | + options, | |
| 536 | + customProperty: "custom-implementation", | |
| 537 | + })) as any; | |
| 538 | + | |
| 539 | + mockedContextProviderClassFromName.mockReturnValue(mockFileProvider); | |
| 540 | + | |
| 541 | + const config = [ | |
| 542 | + { | |
| 543 | + provider: "custom-file", | |
| 544 | + name: "my-file-provider", | |
| 545 | + params: { customParam: "value" }, | |
| 546 | + }, | |
| 547 | + ]; | |
| 548 | + | |
| 549 | + const result = loadConfigContextProviders(config, false, "vscode"); | |
| 550 | + | |
| 551 | + expect(result.errors).toEqual([]); | |
| 552 | + | |
| 553 | + // Should not duplicate - custom implementation should be used | |
| 554 | + const fileProviders = result.providers.filter( | |
| 555 | + (p) => p.description.title === "file", | |
| 556 | + ); | |
| 557 | + expect(fileProviders).toHaveLength(1); | |
| 558 | + | |
| 559 | + const fileProvider = fileProviders[0] as any; | |
| 560 | + expect(fileProvider.customProperty).toBe("custom-implementation"); | |
| 561 | + expect(fileProvider.options).toEqual({ | |
| 562 | + name: "my-file-provider", | |
| 563 | + customParam: "value", | |
| 564 | + }); | |
| 565 | + }); | |
| 566 | +}); | |
| 567 | + | |
| 568 | +describe("provider instantiation", () => { | |
| 569 | + it("should call default provider constructors with empty options", () => { | |
| 570 | + loadConfigContextProviders([], false, "vscode"); | |
| 571 | + | |
| 572 | + expect(FileContextProvider).toHaveBeenCalledWith({}); | |
| 573 | + expect(CurrentFileContextProvider).toHaveBeenCalledWith({}); | |
| 574 | + expect(DiffContextProvider).toHaveBeenCalledWith({}); | |
| 575 | + expect(TerminalContextProvider).toHaveBeenCalledWith({}); | |
| 576 | + expect(ProblemsContextProvider).toHaveBeenCalledWith({}); | |
| 577 | + expect(RulesContextProvider).toHaveBeenCalledWith({}); | |
| 578 | + }); | |
| 579 | + | |
| 580 | + it("should call provider constructors exactly once per provider", () => { | |
| 581 | + loadConfigContextProviders([], false, "vscode"); | |
| 582 | + | |
| 583 | + expect(FileContextProvider).toHaveBeenCalledTimes(1); | |
| 584 | + expect(CurrentFileContextProvider).toHaveBeenCalledTimes(1); | |
| 585 | + expect(DiffContextProvider).toHaveBeenCalledTimes(1); | |
| 586 | + expect(TerminalContextProvider).toHaveBeenCalledTimes(1); | |
| 587 | + expect(ProblemsContextProvider).toHaveBeenCalledTimes(1); | |
| 588 | + expect(RulesContextProvider).toHaveBeenCalledTimes(1); | |
| 589 | + }); | |
| 590 | +}); |
modified core/config/loadLocalAssistants.ts +9 −5
| @@ -10,16 +10,16 @@ | ||
| 10 | 10 | import { localPathToUri } from "../util/pathToUri"; |
| 11 | 11 | import { joinPathsToUri } from "../util/uri"; |
| 12 | 12 | |
| 13 | -export const ASSISTANTS = "assistants"; | |
| 14 | -export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; | |
| 15 | - | |
| 16 | 13 | export function isLocalDefinitionFile(uri: string): boolean { |
| 17 | 14 | if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { |
| 18 | 15 | return false; |
| 19 | 16 | } |
| 20 | 17 | |
| 21 | 18 | const normalizedUri = URI.normalize(uri); |
| 22 | - return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); | |
| 19 | + return ( | |
| 20 | + normalizedUri.includes(`/.continue/agents/`) || | |
| 21 | + normalizedUri.includes(`/.continue/assistants/`) | |
| 22 | + ); | |
| 23 | 23 | } |
| 24 | 24 | |
| 25 | 25 | async function getDefinitionFilesInDir( |
| @@ -35,7 +35,11 @@ | ||
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | const overrideDefaultIgnores = ignore() |
| 38 | - .add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml")) | |
| 38 | + .add( | |
| 39 | + DEFAULT_IGNORE_FILETYPES.filter( | |
| 40 | + (t) => t !== "config.yaml" && t !== "config.yml", | |
| 41 | + ), | |
| 42 | + ) | |
| 39 | 43 | .add(DEFAULT_IGNORE_DIRS); |
| 40 | 44 | |
| 41 | 45 | const uris = await walkDir(dir, ide, { |
modified core/config/loadLocalAssistants.vitest.ts +263 −9
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | getAllDotContinueDefinitionFiles, |
| 7 | 7 | LoadAssistantFilesOptions, |
| 8 | 8 | } from "./loadLocalAssistants"; |
| 9 | -describe("getAllDotContinueDefinitionFiles with fileExtType option", () => { | |
| 9 | +describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", () => { | |
| 10 | 10 | beforeEach(() => { |
| 11 | 11 | setUpTestDir(); |
| 12 | 12 | walkDirCache.invalidate(); |
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | [".continue/assistants/assistant2.yml", "yaml content 2"], |
| 19 | 19 | [".continue/assistants/assistant3.md", "markdown content 1"], |
| 20 | 20 | [".continue/assistants/assistant4.txt", "txt content"], |
| 21 | + [".continue/assistants/config.yaml", "txt content"], | |
| 22 | + [".continue/assistants/config.yml", "txt content"], | |
| 21 | 23 | ]); |
| 22 | 24 | }); |
| 23 | 25 | |
| @@ -38,9 +40,14 @@ | ||
| 38 | 40 | options, |
| 39 | 41 | "assistants", |
| 40 | 42 | ); |
| 41 | - expect(result).toHaveLength(2); | |
| 43 | + expect(result).toHaveLength(4); | |
| 42 | 44 | expect(result.map((f) => f.path.split("/").pop())).toEqual( |
| 43 | - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 45 | + expect.arrayContaining([ | |
| 46 | + "assistant1.yaml", | |
| 47 | + "assistant2.yml", | |
| 48 | + "config.yaml", | |
| 49 | + "config.yml", | |
| 50 | + ]), | |
| 44 | 51 | ); |
| 45 | 52 | expect(result.map((f) => f.path.split("/").pop())).not.toContain( |
| 46 | 53 | "assistant3.md", |
| @@ -69,6 +76,12 @@ | ||
| 69 | 76 | expect(result.map((f) => f.path.split("/").pop())).not.toContain( |
| 70 | 77 | "assistant2.yml", |
| 71 | 78 | ); |
| 79 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 80 | + "config.yml", | |
| 81 | + ); | |
| 82 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 83 | + "config.yaml", | |
| 84 | + ); | |
| 72 | 85 | }); |
| 73 | 86 | |
| 74 | 87 | it("should return all supported files when fileExtType is not specified", async () => { |
| @@ -83,11 +96,13 @@ | ||
| 83 | 96 | options, |
| 84 | 97 | "assistants", |
| 85 | 98 | ); |
| 86 | - expect(result).toHaveLength(3); | |
| 99 | + expect(result).toHaveLength(5); | |
| 87 | 100 | expect(result.map((f) => f.path.split("/").pop())).toEqual( |
| 88 | 101 | expect.arrayContaining([ |
| 89 | 102 | "assistant1.yaml", |
| 90 | 103 | "assistant2.yml", |
| 104 | + "config.yml", | |
| 105 | + "config.yaml", | |
| 91 | 106 | "assistant3.md", |
| 92 | 107 | ]), |
| 93 | 108 | ); |
| @@ -124,9 +139,14 @@ | ||
| 124 | 139 | workspaceOnOptions, |
| 125 | 140 | "assistants", |
| 126 | 141 | ); |
| 127 | - expect(workspaceResult).toHaveLength(2); | |
| 142 | + expect(workspaceResult).toHaveLength(4); | |
| 128 | 143 | expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( |
| 129 | - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 144 | + expect.arrayContaining([ | |
| 145 | + "assistant1.yaml", | |
| 146 | + "assistant2.yml", | |
| 147 | + "config.yaml", | |
| 148 | + "config.yml", | |
| 149 | + ]), | |
| 130 | 150 | ); |
| 131 | 151 | }); |
| 132 | 152 | |
| @@ -187,7 +207,7 @@ | ||
| 187 | 207 | options, |
| 188 | 208 | "assistants", |
| 189 | 209 | ); |
| 190 | - expect(result).toHaveLength(2); | |
| 210 | + expect(result).toHaveLength(4); | |
| 191 | 211 | const yamlFile = result.find((f) => f.path.includes("assistant1.yaml")); |
| 192 | 212 | expect(yamlFile?.content).toBe("yaml content 1"); |
| 193 | 213 | }); |
| @@ -212,9 +232,14 @@ | ||
| 212 | 232 | "assistants", |
| 213 | 233 | ); |
| 214 | 234 | // Should only get lowercase extensions (current implementation) |
| 215 | - expect(yamlResult).toHaveLength(2); | |
| 235 | + expect(yamlResult).toHaveLength(4); | |
| 216 | 236 | expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( |
| 217 | - expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), | |
| 237 | + expect.arrayContaining([ | |
| 238 | + "assistant1.yaml", | |
| 239 | + "assistant2.yml", | |
| 240 | + "config.yaml", | |
| 241 | + "config.yml", | |
| 242 | + ]), | |
| 218 | 243 | ); |
| 219 | 244 | expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( |
| 220 | 245 | "assistant5.YAML", |
| @@ -240,3 +265,232 @@ | ||
| 240 | 265 | ); |
| 241 | 266 | }); |
| 242 | 267 | }); |
| 268 | + | |
| 269 | +describe("AGENTS getAllDotContinueDefinitionFiles with fileExtType option", () => { | |
| 270 | + beforeEach(() => { | |
| 271 | + setUpTestDir(); | |
| 272 | + walkDirCache.invalidate(); | |
| 273 | + | |
| 274 | + // Add test files to the test directory | |
| 275 | + addToTestDir([ | |
| 276 | + ".continue/agents/", | |
| 277 | + [".continue/agents/agent1.yaml", "yaml content 1"], | |
| 278 | + [".continue/agents/agent2.yml", "yaml content 2"], | |
| 279 | + [".continue/agents/agent3.md", "markdown content 1"], | |
| 280 | + [".continue/agents/agent4.txt", "txt content"], | |
| 281 | + ]); | |
| 282 | + }); | |
| 283 | + | |
| 284 | + afterEach(() => { | |
| 285 | + tearDownTestDir(); | |
| 286 | + walkDirCache.invalidate(); | |
| 287 | + }); | |
| 288 | + | |
| 289 | + it("should return only YAML files when fileExtType is 'yaml'", async () => { | |
| 290 | + const options: LoadAssistantFilesOptions = { | |
| 291 | + includeGlobal: false, // Only test workspace for simplicity | |
| 292 | + includeWorkspace: true, | |
| 293 | + fileExtType: "yaml", | |
| 294 | + }; | |
| 295 | + | |
| 296 | + const result = await getAllDotContinueDefinitionFiles( | |
| 297 | + testIde, | |
| 298 | + options, | |
| 299 | + "agents", | |
| 300 | + ); | |
| 301 | + expect(result).toHaveLength(2); | |
| 302 | + expect(result.map((f) => f.path.split("/").pop())).toEqual( | |
| 303 | + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), | |
| 304 | + ); | |
| 305 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 306 | + "agent3.md", | |
| 307 | + ); | |
| 308 | + }); | |
| 309 | + | |
| 310 | + it("should return only Markdown files when fileExtType is 'markdown'", async () => { | |
| 311 | + const options: LoadAssistantFilesOptions = { | |
| 312 | + includeGlobal: false, | |
| 313 | + includeWorkspace: true, | |
| 314 | + fileExtType: "markdown", | |
| 315 | + }; | |
| 316 | + | |
| 317 | + const result = await getAllDotContinueDefinitionFiles( | |
| 318 | + testIde, | |
| 319 | + options, | |
| 320 | + "agents", | |
| 321 | + ); | |
| 322 | + expect(result).toHaveLength(1); | |
| 323 | + expect(result.map((f) => f.path.split("/").pop())).toEqual(["agent3.md"]); | |
| 324 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 325 | + "agent1.yaml", | |
| 326 | + ); | |
| 327 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 328 | + "agent2.yml", | |
| 329 | + ); | |
| 330 | + }); | |
| 331 | + | |
| 332 | + it("should return all supported files when fileExtType is not specified", async () => { | |
| 333 | + const options: LoadAssistantFilesOptions = { | |
| 334 | + includeGlobal: false, | |
| 335 | + includeWorkspace: true, | |
| 336 | + // fileExtType not specified | |
| 337 | + }; | |
| 338 | + | |
| 339 | + const result = await getAllDotContinueDefinitionFiles( | |
| 340 | + testIde, | |
| 341 | + options, | |
| 342 | + "agents", | |
| 343 | + ); | |
| 344 | + expect(result).toHaveLength(3); | |
| 345 | + expect(result.map((f) => f.path.split("/").pop())).toEqual( | |
| 346 | + expect.arrayContaining(["agent1.yaml", "agent2.yml", "agent3.md"]), | |
| 347 | + ); | |
| 348 | + // Should not include .txt files | |
| 349 | + expect(result.map((f) => f.path.split("/").pop())).not.toContain( | |
| 350 | + "agent4.txt", | |
| 351 | + ); | |
| 352 | + }); | |
| 353 | + | |
| 354 | + it("should respect includeWorkspace option with fileExtType", async () => { | |
| 355 | + // Test with includeWorkspace: false | |
| 356 | + const workspaceOffOptions: LoadAssistantFilesOptions = { | |
| 357 | + includeGlobal: false, | |
| 358 | + includeWorkspace: false, | |
| 359 | + fileExtType: "yaml", | |
| 360 | + }; | |
| 361 | + | |
| 362 | + const noWorkspaceResult = await getAllDotContinueDefinitionFiles( | |
| 363 | + testIde, | |
| 364 | + workspaceOffOptions, | |
| 365 | + "agents", | |
| 366 | + ); | |
| 367 | + expect(noWorkspaceResult).toHaveLength(0); | |
| 368 | + | |
| 369 | + // Test with includeWorkspace: true | |
| 370 | + const workspaceOnOptions: LoadAssistantFilesOptions = { | |
| 371 | + includeGlobal: false, | |
| 372 | + includeWorkspace: true, | |
| 373 | + fileExtType: "yaml", | |
| 374 | + }; | |
| 375 | + | |
| 376 | + const workspaceResult = await getAllDotContinueDefinitionFiles( | |
| 377 | + testIde, | |
| 378 | + workspaceOnOptions, | |
| 379 | + "agents", | |
| 380 | + ); | |
| 381 | + expect(workspaceResult).toHaveLength(2); | |
| 382 | + expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( | |
| 383 | + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), | |
| 384 | + ); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + it("should return empty array when no files match the specified extension type", async () => { | |
| 388 | + // Create a test directory with only non-matching files | |
| 389 | + tearDownTestDir(); | |
| 390 | + walkDirCache.invalidate(); | |
| 391 | + setUpTestDir(); | |
| 392 | + addToTestDir([ | |
| 393 | + ".continue/agents/", | |
| 394 | + [".continue/agents/nonmatch1.txt", "txt content"], | |
| 395 | + [".continue/agents/nonmatch2.json", "json content"], | |
| 396 | + ]); | |
| 397 | + | |
| 398 | + const options: LoadAssistantFilesOptions = { | |
| 399 | + includeGlobal: false, | |
| 400 | + includeWorkspace: true, | |
| 401 | + | |
| 402 | + fileExtType: "yaml", | |
| 403 | + }; | |
| 404 | + | |
| 405 | + const result = await getAllDotContinueDefinitionFiles( | |
| 406 | + testIde, | |
| 407 | + options, | |
| 408 | + "agents", | |
| 409 | + ); | |
| 410 | + expect(result).toHaveLength(0); | |
| 411 | + }); | |
| 412 | + | |
| 413 | + it("should handle directories that don't exist", async () => { | |
| 414 | + // Create a clean test directory without the agents folder | |
| 415 | + tearDownTestDir(); | |
| 416 | + setUpTestDir(); | |
| 417 | + | |
| 418 | + const options: LoadAssistantFilesOptions = { | |
| 419 | + includeGlobal: false, | |
| 420 | + includeWorkspace: true, | |
| 421 | + fileExtType: "yaml", | |
| 422 | + }; | |
| 423 | + | |
| 424 | + const result = await getAllDotContinueDefinitionFiles( | |
| 425 | + testIde, | |
| 426 | + options, | |
| 427 | + "agents", | |
| 428 | + ); | |
| 429 | + expect(result).toHaveLength(0); | |
| 430 | + }); | |
| 431 | + | |
| 432 | + it("should return correct file content", async () => { | |
| 433 | + const options: LoadAssistantFilesOptions = { | |
| 434 | + includeGlobal: false, | |
| 435 | + includeWorkspace: true, | |
| 436 | + fileExtType: "yaml", | |
| 437 | + }; | |
| 438 | + | |
| 439 | + const result = await getAllDotContinueDefinitionFiles( | |
| 440 | + testIde, | |
| 441 | + options, | |
| 442 | + "agents", | |
| 443 | + ); | |
| 444 | + expect(result).toHaveLength(2); | |
| 445 | + const yamlFile = result.find((f) => f.path.includes("agent1.yaml")); | |
| 446 | + expect(yamlFile?.content).toBe("yaml content 1"); | |
| 447 | + }); | |
| 448 | + | |
| 449 | + it("should filter by file extension case sensitively", async () => { | |
| 450 | + // Add files with uppercase extensions | |
| 451 | + addToTestDir([ | |
| 452 | + [".continue/agents/agent5.YAML", "uppercase yaml"], | |
| 453 | + [".continue/agents/agent6.YML", "uppercase yml"], | |
| 454 | + [".continue/agents/agent7.MD", "uppercase md"], | |
| 455 | + ]); | |
| 456 | + | |
| 457 | + const yamlOptions: LoadAssistantFilesOptions = { | |
| 458 | + includeGlobal: false, | |
| 459 | + includeWorkspace: true, | |
| 460 | + fileExtType: "yaml", | |
| 461 | + }; | |
| 462 | + | |
| 463 | + const yamlResult = await getAllDotContinueDefinitionFiles( | |
| 464 | + testIde, | |
| 465 | + yamlOptions, | |
| 466 | + "agents", | |
| 467 | + ); | |
| 468 | + // Should only get lowercase extensions (current implementation) | |
| 469 | + expect(yamlResult).toHaveLength(2); | |
| 470 | + expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( | |
| 471 | + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), | |
| 472 | + ); | |
| 473 | + expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( | |
| 474 | + "agent5.YAML", | |
| 475 | + ); | |
| 476 | + | |
| 477 | + const markdownOptions: LoadAssistantFilesOptions = { | |
| 478 | + includeGlobal: false, | |
| 479 | + includeWorkspace: true, | |
| 480 | + fileExtType: "markdown", | |
| 481 | + }; | |
| 482 | + | |
| 483 | + const markdownResult = await getAllDotContinueDefinitionFiles( | |
| 484 | + testIde, | |
| 485 | + markdownOptions, | |
| 486 | + "agents", | |
| 487 | + ); | |
| 488 | + expect(markdownResult).toHaveLength(1); | |
| 489 | + expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([ | |
| 490 | + "agent3.md", | |
| 491 | + ]); | |
| 492 | + expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain( | |
| 493 | + "agent7.MD", | |
| 494 | + ); | |
| 495 | + }); | |
| 496 | +}); |
modified core/config/profile/LocalProfileLoader.ts +3 −5
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; |
| 2 | 2 | |
| 3 | 3 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 4 | -import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; | |
| 4 | +import { ContinueConfig, IDE, ILLMLogger } from "../../index.js"; | |
| 5 | 5 | import { ProfileDescription } from "../ProfileLifecycleManager.js"; |
| 6 | 6 | |
| 7 | 7 | import { getPrimaryConfigFilePath } from "../../util/paths.js"; |
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | |
| 16 | 16 | constructor( |
| 17 | 17 | private ide: IDE, |
| 18 | - private ideSettingsPromise: Promise<IdeSettings>, | |
| 19 | 18 | private controlPlaneClient: ControlPlaneClient, |
| 20 | 19 | private llmLogger: ILLMLogger, |
| 21 | 20 | private overrideAssistantFile?: |
| @@ -33,7 +32,7 @@ | ||
| 33 | 32 | iconUrl: "", |
| 34 | 33 | title: overrideAssistantFile?.path |
| 35 | 34 | ? getUriPathBasename(overrideAssistantFile.path) |
| 36 | - : "Local Assistant", | |
| 35 | + : "Local Agent", | |
| 37 | 36 | errors: undefined, |
| 38 | 37 | uri: |
| 39 | 38 | overrideAssistantFile?.path ?? |
| @@ -48,7 +47,7 @@ | ||
| 48 | 47 | ); |
| 49 | 48 | this.description.title = parsedAssistant.name; |
| 50 | 49 | } catch (e) { |
| 51 | - console.error("Failed to parse assistant file: ", e); | |
| 50 | + console.error("Failed to parse agent file: ", e); | |
| 52 | 51 | } |
| 53 | 52 | } |
| 54 | 53 | } |
| @@ -57,7 +56,6 @@ | ||
| 57 | 56 | async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> { |
| 58 | 57 | const result = await doLoadConfig({ |
| 59 | 58 | ide: this.ide, |
| 60 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 61 | 59 | controlPlaneClient: this.controlPlaneClient, |
| 62 | 60 | llmLogger: this.llmLogger, |
| 63 | 61 | profileId: this.description.id, |
modified core/config/profile/PlatformProfileLoader.ts +2 −10
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 4 | 4 | import { getControlPlaneEnv } from "../../control-plane/env.js"; |
| 5 | -import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; | |
| 5 | +import { ContinueConfig, IDE, ILLMLogger } from "../../index.js"; | |
| 6 | 6 | import { ProfileDescription } from "../ProfileLifecycleManager.js"; |
| 7 | 7 | |
| 8 | 8 | import doLoadConfig from "./doLoadConfig.js"; |
| @@ -28,7 +28,6 @@ | ||
| 28 | 28 | private readonly versionSlug: string; |
| 29 | 29 | private readonly controlPlaneClient: ControlPlaneClient; |
| 30 | 30 | private readonly ide: IDE; |
| 31 | - private ideSettingsPromise: Promise<IdeSettings>; | |
| 32 | 31 | private llmLogger: ILLMLogger; |
| 33 | 32 | readonly description: ProfileDescription; |
| 34 | 33 | private readonly orgScopeId: string | null; |
| @@ -41,7 +40,6 @@ | ||
| 41 | 40 | versionSlug, |
| 42 | 41 | controlPlaneClient, |
| 43 | 42 | ide, |
| 44 | - ideSettingsPromise, | |
| 45 | 43 | llmLogger, |
| 46 | 44 | description, |
| 47 | 45 | orgScopeId, |
| @@ -53,7 +51,6 @@ | ||
| 53 | 51 | versionSlug: string; |
| 54 | 52 | controlPlaneClient: ControlPlaneClient; |
| 55 | 53 | ide: IDE; |
| 56 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 57 | 54 | llmLogger: ILLMLogger; |
| 58 | 55 | description: ProfileDescription; |
| 59 | 56 | orgScopeId: string | null; |
| @@ -65,7 +62,6 @@ | ||
| 65 | 62 | this.versionSlug = versionSlug; |
| 66 | 63 | this.controlPlaneClient = controlPlaneClient; |
| 67 | 64 | this.ide = ide; |
| 68 | - this.ideSettingsPromise = ideSettingsPromise; | |
| 69 | 65 | this.llmLogger = llmLogger; |
| 70 | 66 | this.description = description; |
| 71 | 67 | this.orgScopeId = orgScopeId; |
| @@ -79,7 +75,6 @@ | ||
| 79 | 75 | versionSlug, |
| 80 | 76 | controlPlaneClient, |
| 81 | 77 | ide, |
| 82 | - ideSettingsPromise, | |
| 83 | 78 | llmLogger, |
| 84 | 79 | rawYaml, |
| 85 | 80 | orgScopeId, |
| @@ -91,12 +86,11 @@ | ||
| 91 | 86 | versionSlug: string; |
| 92 | 87 | controlPlaneClient: ControlPlaneClient; |
| 93 | 88 | ide: IDE; |
| 94 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 95 | 89 | llmLogger: ILLMLogger; |
| 96 | 90 | rawYaml: string; |
| 97 | 91 | orgScopeId: string | null; |
| 98 | 92 | }): Promise<PlatformProfileLoader> { |
| 99 | - const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); | |
| 93 | + const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings()); | |
| 100 | 94 | |
| 101 | 95 | const description: ProfileDescription = { |
| 102 | 96 | id: `${ownerSlug}/${packageSlug}`, |
| @@ -121,7 +115,6 @@ | ||
| 121 | 115 | versionSlug, |
| 122 | 116 | controlPlaneClient, |
| 123 | 117 | ide, |
| 124 | - ideSettingsPromise, | |
| 125 | 118 | llmLogger, |
| 126 | 119 | description, |
| 127 | 120 | orgScopeId, |
| @@ -139,7 +132,6 @@ | ||
| 139 | 132 | |
| 140 | 133 | const results = await doLoadConfig({ |
| 141 | 134 | ide: this.ide, |
| 142 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 143 | 135 | controlPlaneClient: this.controlPlaneClient, |
| 144 | 136 | llmLogger: this.llmLogger, |
| 145 | 137 | overrideConfigYaml: this.configResult.config, |
modified core/config/profile/doLoadConfig.ts +20 −23
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | import { |
| 12 | 12 | ContinueConfig, |
| 13 | 13 | IDE, |
| 14 | - IdeSettings, | |
| 15 | 14 | ILLMLogger, |
| 16 | 15 | RuleWithSource, |
| 17 | 16 | SerializedContinueConfig, |
| @@ -20,9 +19,8 @@ | ||
| 20 | 19 | } from "../../"; |
| 21 | 20 | import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand"; |
| 22 | 21 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 23 | -import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider"; | |
| 22 | +import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider"; | |
| 24 | 23 | import MCPContextProvider from "../../context/providers/MCPContextProvider"; |
| 25 | -import RulesContextProvider from "../../context/providers/RulesContextProvider"; | |
| 26 | 24 | import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; |
| 27 | 25 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 28 | 26 | import { getControlPlaneEnv } from "../../control-plane/env.js"; |
| @@ -71,7 +69,6 @@ | ||
| 71 | 69 | } |
| 72 | 70 | export default async function doLoadConfig(options: { |
| 73 | 71 | ide: IDE; |
| 74 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 75 | 72 | controlPlaneClient: ControlPlaneClient; |
| 76 | 73 | llmLogger: ILLMLogger; |
| 77 | 74 | overrideConfigJson?: SerializedContinueConfig; |
| @@ -83,7 +80,6 @@ | ||
| 83 | 80 | }): Promise<ConfigResult<ContinueConfig>> { |
| 84 | 81 | const { |
| 85 | 82 | ide, |
| 86 | - ideSettingsPromise, | |
| 87 | 83 | controlPlaneClient, |
| 88 | 84 | llmLogger, |
| 89 | 85 | overrideConfigJson, |
| @@ -96,8 +92,9 @@ | ||
| 96 | 92 | |
| 97 | 93 | const ideInfo = await ide.getIdeInfo(); |
| 98 | 94 | const uniqueId = await ide.getUniqueId(); |
| 99 | - const ideSettings = await ideSettingsPromise; | |
| 95 | + const ideSettings = await ide.getIdeSettings(); | |
| 100 | 96 | const workOsAccessToken = await controlPlaneClient.getAccessToken(); |
| 97 | + const isSignedIn = await controlPlaneClient.isSignedIn(); | |
| 101 | 98 | |
| 102 | 99 | // Migrations for old config files |
| 103 | 100 | // Removes |
| @@ -157,17 +154,13 @@ | ||
| 157 | 154 | const { rules, errors: rulesErrors } = await loadRules(ide); |
| 158 | 155 | errors.push(...rulesErrors); |
| 159 | 156 | newConfig.rules.unshift(...rules); |
| 160 | - newConfig.contextProviders.push(new RulesContextProvider({})); | |
| 161 | - | |
| 162 | - // Add current file as context if setting is enabled | |
| 163 | - if ( | |
| 164 | - newConfig.experimental?.useCurrentFileAsContext === true && | |
| 165 | - !newConfig.contextProviders.find( | |
| 166 | - (c) => | |
| 167 | - c.description.title === CurrentFileContextProvider.description.title, | |
| 168 | - ) | |
| 169 | - ) { | |
| 170 | - newConfig.contextProviders.push(new CurrentFileContextProvider({})); | |
| 157 | + | |
| 158 | + const proxyContextProvider = newConfig.contextProviders?.find( | |
| 159 | + (cp) => cp.description.title === "continue-proxy", | |
| 160 | + ); | |
| 161 | + if (proxyContextProvider) { | |
| 162 | + (proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken = | |
| 163 | + workOsAccessToken; | |
| 171 | 164 | } |
| 172 | 165 | |
| 173 | 166 | // Show deprecation warnings for providers |
| @@ -194,7 +187,6 @@ | ||
| 194 | 187 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 195 | 188 | const mcpServerStatuses = mcpManager.getStatuses(); |
| 196 | 189 | |
| 197 | - // Slightly hacky just need connection's client to make slash command for now | |
| 198 | 190 | const serializableStatuses = mcpServerStatuses.map((server) => { |
| 199 | 191 | const { client, ...rest } = server; |
| 200 | 192 | return rest; |
| @@ -285,6 +277,9 @@ | ||
| 285 | 277 | rules: newConfig.rules, |
| 286 | 278 | enableExperimentalTools: |
| 287 | 279 | newConfig.experimental?.enableExperimentalTools ?? false, |
| 280 | + isSignedIn, | |
| 281 | + isRemote: await ide.isWorkspaceRemote(), | |
| 282 | + modelName: newConfig.selectedModelByRole.chat?.model, | |
| 288 | 283 | }), |
| 289 | 284 | ); |
| 290 | 285 | |
| @@ -333,12 +328,14 @@ | ||
| 333 | 328 | } |
| 334 | 329 | } |
| 335 | 330 | |
| 336 | - if ( | |
| 337 | - PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === | |
| 338 | - false | |
| 339 | - ) { | |
| 331 | + // Org policies | |
| 332 | + const policy = PolicySingleton.getInstance().policy?.policy; | |
| 333 | + if (policy?.allowAnonymousTelemetry === false) { | |
| 340 | 334 | newConfig.allowAnonymousTelemetry = false; |
| 341 | 335 | } |
| 336 | + if (policy?.allowCodebaseIndexing === false) { | |
| 337 | + newConfig.disableIndexing = true; | |
| 338 | + } | |
| 342 | 339 | |
| 343 | 340 | // Setup telemetry only after (and if) we know it is enabled |
| 344 | 341 | await Telemetry.setup( |
| @@ -373,7 +370,7 @@ | ||
| 373 | 370 | const useOnPremProxy = |
| 374 | 371 | controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; |
| 375 | 372 | |
| 376 | - const env = await getControlPlaneEnv(ideSettingsPromise); | |
| 373 | + const env = await getControlPlaneEnv(Promise.resolve(ideSettings)); | |
| 377 | 374 | let controlPlaneProxyUrl: string = useOnPremProxy |
| 378 | 375 | ? controlPlane?.proxyUrl |
| 379 | 376 | : env.DEFAULT_CONTROL_PLANE_PROXY_URL; |
modified core/config/sharedConfig.ts +6 −0
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | displayRawMarkdown: z.boolean(), |
| 33 | 33 | showChatScrollbar: z.boolean(), |
| 34 | 34 | autoAcceptEditToolDiffs: z.boolean(), |
| 35 | + continueAfterToolRejection: z.boolean(), | |
| 35 | 36 | |
| 36 | 37 | // `tabAutocompleteOptions` in `ContinueConfig` |
| 37 | 38 | useAutocompleteCache: z.boolean(), |
| @@ -158,6 +159,11 @@ | ||
| 158 | 159 | configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs; |
| 159 | 160 | } |
| 160 | 161 | |
| 162 | + if (sharedConfig.continueAfterToolRejection !== undefined) { | |
| 163 | + configCopy.ui.continueAfterToolRejection = | |
| 164 | + sharedConfig.continueAfterToolRejection; | |
| 165 | + } | |
| 166 | + | |
| 161 | 167 | configCopy.experimental = { |
| 162 | 168 | ...configCopy.experimental, |
| 163 | 169 | }; |
deleted core/config/shouldAutoEnableSystemMessageTools.ts +0 −31
| @@ -1,31 +0,0 @@ | ||
| 1 | -import { ModelDescription } from "../index.d"; | |
| 2 | - | |
| 3 | -/** | |
| 4 | - * Determines if system message tools should be auto-enabled for the given model. | |
| 5 | - * This is used to automatically enable system message tools for certain provider/model combinations | |
| 6 | - * where we have a strong preference, taking priority over user manual settings. | |
| 7 | - * | |
| 8 | - * System message tools are an alternative to native tool calling where tool definitions and calls | |
| 9 | - * are embedded in the system message as text rather than using the provider's native tool calling API. | |
| 10 | - * This can be beneficial for providers/models that don't support native tool calling or have | |
| 11 | - * poor tool calling performance. | |
| 12 | - * | |
| 13 | - * Current auto-enable rules: | |
| 14 | - * - OpenRouter provider: true for all models except those containing "claude" (since Claude models | |
| 15 | - * generally have good native tool calling support) | |
| 16 | - * - All other providers: undefined (no auto-preference, use manual setting) | |
| 17 | - * | |
| 18 | - * @param model The model description to check | |
| 19 | - * @returns true to force enable, false to force disable, undefined for no auto-preference | |
| 20 | - */ | |
| 21 | -export function shouldAutoEnableSystemMessageTools( | |
| 22 | - model: ModelDescription, | |
| 23 | -): boolean | undefined { | |
| 24 | - // Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling | |
| 25 | - if (model.provider === "openrouter") { | |
| 26 | - return !model.model.toLowerCase().includes("claude"); | |
| 27 | - } | |
| 28 | - | |
| 29 | - // No auto-preference for all other providers - use manual setting | |
| 30 | - return undefined; | |
| 31 | -} |
deleted core/config/shouldAutoEnableSystemMessageTools.vitest.ts +0 −85
| @@ -1,85 +0,0 @@ | ||
| 1 | -import { describe, expect, test } from "vitest"; | |
| 2 | -import { ModelDescription } from "../index.d"; | |
| 3 | -import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools"; | |
| 4 | - | |
| 5 | -describe("shouldAutoEnableSystemMessageTools", () => { | |
| 6 | - const createModel = (provider: string, model: string): ModelDescription => ({ | |
| 7 | - title: "Test Model", | |
| 8 | - provider, | |
| 9 | - underlyingProviderName: provider, | |
| 10 | - model, | |
| 11 | - }); | |
| 12 | - | |
| 13 | - test("should return true for OpenRouter models that don't contain 'claude'", () => { | |
| 14 | - expect( | |
| 15 | - shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")), | |
| 16 | - ).toBe(true); | |
| 17 | - expect( | |
| 18 | - shouldAutoEnableSystemMessageTools( | |
| 19 | - createModel("openrouter", "llama-3.3-70b-instruct"), | |
| 20 | - ), | |
| 21 | - ).toBe(true); | |
| 22 | - expect( | |
| 23 | - shouldAutoEnableSystemMessageTools( | |
| 24 | - createModel("openrouter", "qwen/qwen-2.5-72b-instruct"), | |
| 25 | - ), | |
| 26 | - ).toBe(true); | |
| 27 | - }); | |
| 28 | - | |
| 29 | - test("should return false for OpenRouter Claude models", () => { | |
| 30 | - expect( | |
| 31 | - shouldAutoEnableSystemMessageTools( | |
| 32 | - createModel("openrouter", "anthropic/claude-3-sonnet"), | |
| 33 | - ), | |
| 34 | - ).toBe(false); | |
| 35 | - expect( | |
| 36 | - shouldAutoEnableSystemMessageTools( | |
| 37 | - createModel("openrouter", "anthropic/claude-3.5-sonnet"), | |
| 38 | - ), | |
| 39 | - ).toBe(false); | |
| 40 | - expect( | |
| 41 | - shouldAutoEnableSystemMessageTools( | |
| 42 | - createModel("openrouter", "claude-3-haiku"), | |
| 43 | - ), | |
| 44 | - ).toBe(false); | |
| 45 | - }); | |
| 46 | - | |
| 47 | - test("should return undefined for all other providers", () => { | |
| 48 | - expect( | |
| 49 | - shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")), | |
| 50 | - ).toBe(undefined); | |
| 51 | - expect( | |
| 52 | - shouldAutoEnableSystemMessageTools( | |
| 53 | - createModel("anthropic", "claude-3.5-sonnet"), | |
| 54 | - ), | |
| 55 | - ).toBe(undefined); | |
| 56 | - expect( | |
| 57 | - shouldAutoEnableSystemMessageTools( | |
| 58 | - createModel("groq", "llama-3.3-70b-versatile"), | |
| 59 | - ), | |
| 60 | - ).toBe(undefined); | |
| 61 | - expect( | |
| 62 | - shouldAutoEnableSystemMessageTools( | |
| 63 | - createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"), | |
| 64 | - ), | |
| 65 | - ).toBe(undefined); | |
| 66 | - }); | |
| 67 | - | |
| 68 | - test("should be case insensitive for 'claude' detection", () => { | |
| 69 | - expect( | |
| 70 | - shouldAutoEnableSystemMessageTools( | |
| 71 | - createModel("openrouter", "CLAUDE-models"), | |
| 72 | - ), | |
| 73 | - ).toBe(false); | |
| 74 | - expect( | |
| 75 | - shouldAutoEnableSystemMessageTools( | |
| 76 | - createModel("openrouter", "Claude-3.5"), | |
| 77 | - ), | |
| 78 | - ).toBe(false); | |
| 79 | - expect( | |
| 80 | - shouldAutoEnableSystemMessageTools( | |
| 81 | - createModel("openrouter", "some-model-Claude"), | |
| 82 | - ), | |
| 83 | - ).toBe(false); | |
| 84 | - }); | |
| 85 | -}); |
modified core/config/types.ts +3 −5
| @@ -280,11 +280,6 @@ | ||
| 280 | 280 | replacement: string; |
| 281 | 281 | } |
| 282 | 282 | |
| 283 | - export interface ContinueError { | |
| 284 | - title: string; | |
| 285 | - message: string; | |
| 286 | - } | |
| 287 | - | |
| 288 | 283 | export interface CompletionOptions extends BaseCompletionOptions { |
| 289 | 284 | model: string; |
| 290 | 285 | } |
| @@ -692,6 +687,8 @@ | ||
| 692 | 687 | |
| 693 | 688 | openUrl(url: string): Promise<void>; |
| 694 | 689 | |
| 690 | + getExternalUri?(uri: string): Promise<string>; | |
| 691 | + | |
| 695 | 692 | runCommand(command: string): Promise<void>; |
| 696 | 693 | |
| 697 | 694 | saveFile(filepath: string): Promise<void>; |
| @@ -1061,6 +1058,7 @@ | ||
| 1061 | 1058 | filepath?: string; |
| 1062 | 1059 | fileContent?: string; |
| 1063 | 1060 | originalFileContent?: string; |
| 1061 | + autoFormattingDiff?: string; | |
| 1064 | 1062 | } |
| 1065 | 1063 | |
| 1066 | 1064 | export interface RangeInFileWithContents { |
modified core/config/yaml/default.ts +2 −2
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | export const defaultConfigYaml: AssistantUnrolled = { |
| 5 | 5 | models: [], |
| 6 | 6 | context: [], |
| 7 | - name: "Local Assistant", | |
| 7 | + name: "Local Agent", | |
| 8 | 8 | version: "1.0.0", |
| 9 | 9 | schema: "v1", |
| 10 | 10 | }; |
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | export const defaultConfigYamlJetBrains: AssistantUnrolled = { |
| 13 | 13 | models: [], |
| 14 | 14 | context: [], |
| 15 | - name: "Local Assistant", | |
| 15 | + name: "Local Agent", | |
| 16 | 16 | version: "1.0.0", |
| 17 | 17 | schema: "v1", |
| 18 | 18 | }; |
modified core/config/yaml/loadYaml.ts +64 −80
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | ConfigResult, |
| 5 | 5 | ConfigValidationError, |
| 6 | 6 | isAssistantUnrolledNonNullable, |
| 7 | + mergeConfigYamlRequestOptions, | |
| 7 | 8 | mergeUnrolledAssistants, |
| 8 | 9 | ModelRole, |
| 9 | 10 | PackageIdentifier, |
| @@ -14,18 +15,8 @@ | ||
| 14 | 15 | } from "@continuedev/config-yaml"; |
| 15 | 16 | import { dirname } from "node:path"; |
| 16 | 17 | |
| 17 | -import { | |
| 18 | - ContinueConfig, | |
| 19 | - IContextProvider, | |
| 20 | - IDE, | |
| 21 | - IdeInfo, | |
| 22 | - IdeSettings, | |
| 23 | - ILLMLogger, | |
| 24 | -} from "../.."; | |
| 18 | +import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../.."; | |
| 25 | 19 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 26 | -import DocsContextProvider from "../../context/providers/DocsContextProvider"; | |
| 27 | -import FileContextProvider from "../../context/providers/FileContextProvider"; | |
| 28 | -import { contextProviderClassFromName } from "../../context/providers/index"; | |
| 29 | 20 | import { ControlPlaneClient } from "../../control-plane/client"; |
| 30 | 21 | import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; |
| 31 | 22 | import { getAllPromptFiles } from "../../promptFiles/getPromptFiles"; |
| @@ -34,17 +25,17 @@ | ||
| 34 | 25 | |
| 35 | 26 | import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; |
| 36 | 27 | import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; |
| 28 | +import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; | |
| 37 | 29 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 38 | -import { getToolsForIde } from "../../tools"; | |
| 30 | +import { PolicySingleton } from "../../control-plane/PolicySingleton"; | |
| 31 | +import { getBaseToolDefinitions } from "../../tools"; | |
| 39 | 32 | import { getCleanUriPath } from "../../util/uri"; |
| 33 | +import { loadConfigContextProviders } from "../loadContextProviders"; | |
| 40 | 34 | import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; |
| 41 | 35 | import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks"; |
| 42 | 36 | import { LocalPlatformClient } from "./LocalPlatformClient"; |
| 43 | 37 | import { llmsFromModelConfig } from "./models"; |
| 44 | -import { | |
| 45 | - convertYamlMcpToContinueMcp, | |
| 46 | - convertYamlRuleToContinueRule, | |
| 47 | -} from "./yamlToContinueConfig"; | |
| 38 | +import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig"; | |
| 48 | 39 | |
| 49 | 40 | async function loadConfigYaml(options: { |
| 50 | 41 | overrideConfigYaml: AssistantUnrolled | undefined; |
| @@ -162,22 +153,21 @@ | ||
| 162 | 153 | }; |
| 163 | 154 | } |
| 164 | 155 | |
| 165 | -async function configYamlToContinueConfig(options: { | |
| 156 | +export async function configYamlToContinueConfig(options: { | |
| 166 | 157 | config: AssistantUnrolled; |
| 167 | 158 | ide: IDE; |
| 168 | - ideSettings: IdeSettings; | |
| 169 | 159 | ideInfo: IdeInfo; |
| 170 | 160 | uniqueId: string; |
| 171 | 161 | llmLogger: ILLMLogger; |
| 172 | 162 | workOsAccessToken: string | undefined; |
| 173 | 163 | }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { |
| 174 | - let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options; | |
| 164 | + let { config, ide, ideInfo, uniqueId, llmLogger } = options; | |
| 175 | 165 | |
| 176 | 166 | const localErrors: ConfigValidationError[] = []; |
| 177 | 167 | |
| 178 | 168 | const continueConfig: ContinueConfig = { |
| 179 | 169 | slashCommands: [], |
| 180 | - tools: await getToolsForIde(ide), | |
| 170 | + tools: getBaseToolDefinitions(), | |
| 181 | 171 | mcpServerStatuses: [], |
| 182 | 172 | contextProviders: [], |
| 183 | 173 | modelsByRole: { |
| @@ -199,6 +189,7 @@ | ||
| 199 | 189 | summarize: null, |
| 200 | 190 | }, |
| 201 | 191 | rules: [], |
| 192 | + requestOptions: { ...config.requestOptions }, | |
| 202 | 193 | }; |
| 203 | 194 | |
| 204 | 195 | // Right now, if there are any missing packages in the config, then we will just throw an error |
| @@ -216,10 +207,30 @@ | ||
| 216 | 207 | } |
| 217 | 208 | |
| 218 | 209 | for (const rule of config.rules ?? []) { |
| 219 | - continueConfig.rules.push(convertYamlRuleToContinueRule(rule)); | |
| 210 | + const convertedRule = convertYamlRuleToContinueRule(rule); | |
| 211 | + continueConfig.rules.push(convertedRule); | |
| 212 | + | |
| 213 | + // Convert invokable rules to slash commands | |
| 214 | + if (convertedRule.invokable) { | |
| 215 | + try { | |
| 216 | + const slashCommand = convertRuleBlockToSlashCommand(convertedRule); | |
| 217 | + continueConfig.slashCommands?.push(slashCommand); | |
| 218 | + } catch (e) { | |
| 219 | + localErrors.push({ | |
| 220 | + message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`, | |
| 221 | + fatal: false, | |
| 222 | + }); | |
| 223 | + } | |
| 224 | + } | |
| 220 | 225 | } |
| 221 | 226 | |
| 222 | - continueConfig.data = config.data; | |
| 227 | + continueConfig.data = config.data?.map((d) => ({ | |
| 228 | + ...d, | |
| 229 | + requestOptions: mergeConfigYamlRequestOptions( | |
| 230 | + d.requestOptions, | |
| 231 | + continueConfig.requestOptions, | |
| 232 | + ), | |
| 233 | + })); | |
| 223 | 234 | continueConfig.docs = config.docs?.map((doc) => ({ |
| 224 | 235 | title: doc.name, |
| 225 | 236 | startUrl: doc.startUrl, |
| @@ -243,12 +254,6 @@ | ||
| 243 | 254 | }); |
| 244 | 255 | }); |
| 245 | 256 | |
| 246 | - continueConfig.experimental = { | |
| 247 | - modelContextProtocolServers: config.mcpServers?.map( | |
| 248 | - convertYamlMcpToContinueMcp, | |
| 249 | - ), | |
| 250 | - }; | |
| 251 | - | |
| 252 | 257 | // Prompt files - |
| 253 | 258 | try { |
| 254 | 259 | const promptFiles = await getAllPromptFiles(ide, undefined, true); |
| @@ -300,9 +305,7 @@ | ||
| 300 | 305 | try { |
| 301 | 306 | const llms = await llmsFromModelConfig({ |
| 302 | 307 | model, |
| 303 | - ide, | |
| 304 | 308 | uniqueId, |
| 305 | - ideSettings, | |
| 306 | 309 | llmLogger, |
| 307 | 310 | config: continueConfig, |
| 308 | 311 | }); |
| @@ -376,60 +379,42 @@ | ||
| 376 | 379 | }); |
| 377 | 380 | } |
| 378 | 381 | |
| 379 | - // Context providers | |
| 380 | - const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})]; | |
| 381 | - | |
| 382 | - const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( | |
| 383 | - ({ description: { title } }) => title, | |
| 382 | + const { providers, errors: contextErrors } = loadConfigContextProviders( | |
| 383 | + config.context, | |
| 384 | + !!config.docs?.length, | |
| 385 | + ideInfo.ideType, | |
| 384 | 386 | ); |
| 385 | 387 | |
| 386 | - continueConfig.contextProviders = (config.context | |
| 387 | - ?.map((context) => { | |
| 388 | - const cls = contextProviderClassFromName(context.provider) as any; | |
| 389 | - if (!cls) { | |
| 390 | - if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) { | |
| 391 | - localErrors.push({ | |
| 392 | - fatal: false, | |
| 393 | - message: `Unknown context provider ${context.provider}`, | |
| 394 | - }); | |
| 395 | - } | |
| 396 | - return undefined; | |
| 397 | - } | |
| 398 | - const instance: IContextProvider = new cls({ | |
| 399 | - name: context.name, | |
| 400 | - ...context.params, | |
| 401 | - }); | |
| 402 | - return instance; | |
| 403 | - }) | |
| 404 | - .filter((p) => !!p) ?? []) as IContextProvider[]; | |
| 405 | - continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS); | |
| 406 | - | |
| 407 | - if ( | |
| 408 | - continueConfig.docs?.length && | |
| 409 | - !continueConfig.contextProviders?.some( | |
| 410 | - (cp) => cp.description.title === "docs", | |
| 411 | - ) | |
| 412 | - ) { | |
| 413 | - continueConfig.contextProviders.push(new DocsContextProvider({})); | |
| 414 | - } | |
| 388 | + continueConfig.contextProviders = providers; | |
| 389 | + localErrors.push(...contextErrors); | |
| 415 | 390 | |
| 416 | 391 | // Trigger MCP server refreshes (Config is reloaded again once connected!) |
| 417 | 392 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 418 | - mcpManager.setConnections( | |
| 419 | - (config.mcpServers ?? []).map((server) => ({ | |
| 420 | - id: server.name, | |
| 421 | - name: server.name, | |
| 422 | - sourceFile: server.sourceFile, | |
| 423 | - transport: { | |
| 424 | - type: "stdio", | |
| 425 | - args: [], | |
| 426 | - ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 427 | - }, | |
| 428 | - timeout: server.connectionTimeout, | |
| 429 | - })), | |
| 430 | - false, | |
| 431 | - { ide }, | |
| 432 | - ); | |
| 393 | + | |
| 394 | + const orgPolicy = PolicySingleton.getInstance().policy; | |
| 395 | + if (orgPolicy?.policy?.allowMcpServers === false) { | |
| 396 | + await mcpManager.shutdown(); | |
| 397 | + } else { | |
| 398 | + mcpManager.setConnections( | |
| 399 | + (config.mcpServers ?? []).map((server) => ({ | |
| 400 | + id: server.name, | |
| 401 | + name: server.name, | |
| 402 | + sourceFile: server.sourceFile, | |
| 403 | + transport: { | |
| 404 | + type: "stdio", | |
| 405 | + args: [], | |
| 406 | + requestOptions: mergeConfigYamlRequestOptions( | |
| 407 | + server.requestOptions, | |
| 408 | + config.requestOptions, | |
| 409 | + ), | |
| 410 | + ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 411 | + }, | |
| 412 | + timeout: server.connectionTimeout, | |
| 413 | + })), | |
| 414 | + false, | |
| 415 | + { ide }, | |
| 416 | + ); | |
| 417 | + } | |
| 433 | 418 | |
| 434 | 419 | return { config: continueConfig, errors: localErrors }; |
| 435 | 420 | } |
| @@ -480,7 +465,6 @@ | ||
| 480 | 465 | await configYamlToContinueConfig({ |
| 481 | 466 | config: configYamlResult.config, |
| 482 | 467 | ide, |
| 483 | - ideSettings, | |
| 484 | 468 | ideInfo, |
| 485 | 469 | uniqueId, |
| 486 | 470 | llmLogger, |
modified core/config/yaml/loadYaml.vitest.ts +7 −7
| @@ -1,14 +1,14 @@ | ||
| 1 | -import { describe, it, expect } from "vitest"; | |
| 2 | 1 | import { |
| 3 | - validateConfigYaml, | |
| 4 | 2 | AssistantUnrolledNonNullable, |
| 3 | + validateConfigYaml, | |
| 5 | 4 | } from "@continuedev/config-yaml"; |
| 5 | +import { describe, expect, it } from "vitest"; | |
| 6 | 6 | |
| 7 | 7 | describe("MCP Server cwd configuration", () => { |
| 8 | 8 | describe("YAML schema validation", () => { |
| 9 | 9 | it("should accept valid MCP server with cwd", () => { |
| 10 | 10 | const config: AssistantUnrolledNonNullable = { |
| 11 | - name: "test-assistant", | |
| 11 | + name: "test-agent", | |
| 12 | 12 | version: "1.0.0", |
| 13 | 13 | mcpServers: [ |
| 14 | 14 | { |
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | |
| 29 | 29 | it("should accept MCP server without cwd", () => { |
| 30 | 30 | const config: AssistantUnrolledNonNullable = { |
| 31 | - name: "test-assistant", | |
| 31 | + name: "test-agent", | |
| 32 | 32 | version: "1.0.0", |
| 33 | 33 | mcpServers: [ |
| 34 | 34 | { |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | |
| 46 | 46 | it("should accept relative paths in cwd", () => { |
| 47 | 47 | const config: AssistantUnrolledNonNullable = { |
| 48 | - name: "test-assistant", | |
| 48 | + name: "test-agent", | |
| 49 | 49 | version: "1.0.0", |
| 50 | 50 | mcpServers: [ |
| 51 | 51 | { |
| @@ -63,7 +63,7 @@ | ||
| 63 | 63 | |
| 64 | 64 | it("should accept empty string cwd", () => { |
| 65 | 65 | const config: AssistantUnrolledNonNullable = { |
| 66 | - name: "test-assistant", | |
| 66 | + name: "test-agent", | |
| 67 | 67 | version: "1.0.0", |
| 68 | 68 | mcpServers: [ |
| 69 | 69 | { |
| @@ -115,7 +115,7 @@ | ||
| 115 | 115 | |
| 116 | 116 | configs.forEach(({ name, server }) => { |
| 117 | 117 | const config: AssistantUnrolledNonNullable = { |
| 118 | - name: "test-assistant", | |
| 118 | + name: "test-agent", | |
| 119 | 119 | version: "1.0.0", |
| 120 | 120 | mcpServers: [server], |
| 121 | 121 | }; |
modified core/config/yaml/models.ts +15 −23
| @@ -1,12 +1,9 @@ | ||
| 1 | -import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | - | |
| 3 | 1 | import { |
| 4 | - ContinueConfig, | |
| 5 | - IDE, | |
| 6 | - IdeSettings, | |
| 7 | - ILLMLogger, | |
| 8 | - LLMOptions, | |
| 9 | -} from "../.."; | |
| 2 | + mergeConfigYamlRequestOptions, | |
| 3 | + ModelConfig, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 5 | + | |
| 6 | +import { ContinueConfig, ILLMLogger, LLMOptions } from "../.."; | |
| 10 | 7 | import { BaseLLM } from "../../llm"; |
| 11 | 8 | import { LLMClasses } from "../../llm/llms"; |
| 12 | 9 | |
| @@ -29,15 +26,15 @@ | ||
| 29 | 26 | async function modelConfigToBaseLLM({ |
| 30 | 27 | model, |
| 31 | 28 | uniqueId, |
| 32 | - ideSettings, | |
| 33 | 29 | llmLogger, |
| 34 | 30 | config, |
| 31 | + isFromAutoDetect, | |
| 35 | 32 | }: { |
| 36 | 33 | model: ModelConfig; |
| 37 | 34 | uniqueId: string; |
| 38 | - ideSettings: IdeSettings; | |
| 39 | 35 | llmLogger: ILLMLogger; |
| 40 | 36 | config: ContinueConfig; |
| 37 | + isFromAutoDetect?: boolean; | |
| 41 | 38 | }): Promise<BaseLLM | undefined> { |
| 42 | 39 | const cls = getModelClass(model); |
| 43 | 40 | |
| @@ -47,6 +44,11 @@ | ||
| 47 | 44 | |
| 48 | 45 | const { capabilities, ...rest } = model; |
| 49 | 46 | |
| 47 | + const mergedRequestOptions = mergeConfigYamlRequestOptions( | |
| 48 | + rest.requestOptions, | |
| 49 | + config.requestOptions, | |
| 50 | + ); | |
| 51 | + | |
| 50 | 52 | let options: LLMOptions = { |
| 51 | 53 | ...rest, |
| 52 | 54 | contextLength: model.defaultCompletionOptions?.contextLength, |
| @@ -71,6 +73,8 @@ | ||
| 71 | 73 | nextEdit: model.capabilities?.includes("next_edit"), |
| 72 | 74 | }, |
| 73 | 75 | autocompleteOptions: model.autocompleteOptions, |
| 76 | + isFromAutoDetect, | |
| 77 | + requestOptions: mergedRequestOptions, | |
| 74 | 78 | }; |
| 75 | 79 | |
| 76 | 80 | // Model capabilities - need to be undefined if not found |
| @@ -151,17 +155,13 @@ | ||
| 151 | 155 | async function autodetectModels({ |
| 152 | 156 | llm, |
| 153 | 157 | model, |
| 154 | - ide, | |
| 155 | 158 | uniqueId, |
| 156 | - ideSettings, | |
| 157 | 159 | llmLogger, |
| 158 | 160 | config, |
| 159 | 161 | }: { |
| 160 | 162 | llm: BaseLLM; |
| 161 | 163 | model: ModelConfig; |
| 162 | - ide: IDE; | |
| 163 | 164 | uniqueId: string; |
| 164 | - ideSettings: IdeSettings; | |
| 165 | 165 | llmLogger: ILLMLogger; |
| 166 | 166 | config: ContinueConfig; |
| 167 | 167 | }): Promise<BaseLLM[]> { |
| @@ -173,7 +173,6 @@ | ||
| 173 | 173 | if (modelName === AUTODETECT) { |
| 174 | 174 | return undefined; |
| 175 | 175 | } |
| 176 | - | |
| 177 | 176 | return await modelConfigToBaseLLM({ |
| 178 | 177 | model: { |
| 179 | 178 | ...model, |
| @@ -181,9 +180,9 @@ | ||
| 181 | 180 | name: modelName, |
| 182 | 181 | }, |
| 183 | 182 | uniqueId, |
| 184 | - ideSettings, | |
| 185 | 183 | llmLogger, |
| 186 | 184 | config, |
| 185 | + isFromAutoDetect: true, | |
| 187 | 186 | }); |
| 188 | 187 | }), |
| 189 | 188 | ); |
| @@ -196,23 +195,18 @@ | ||
| 196 | 195 | |
| 197 | 196 | export async function llmsFromModelConfig({ |
| 198 | 197 | model, |
| 199 | - ide, | |
| 200 | 198 | uniqueId, |
| 201 | - ideSettings, | |
| 202 | 199 | llmLogger, |
| 203 | 200 | config, |
| 204 | 201 | }: { |
| 205 | 202 | model: ModelConfig; |
| 206 | - ide: IDE; | |
| 207 | 203 | uniqueId: string; |
| 208 | - ideSettings: IdeSettings; | |
| 209 | 204 | llmLogger: ILLMLogger; |
| 210 | 205 | config: ContinueConfig; |
| 211 | 206 | }): Promise<BaseLLM[]> { |
| 212 | 207 | const baseLlm = await modelConfigToBaseLLM({ |
| 213 | 208 | model, |
| 214 | 209 | uniqueId, |
| 215 | - ideSettings, | |
| 216 | 210 | llmLogger, |
| 217 | 211 | config, |
| 218 | 212 | }); |
| @@ -224,9 +218,7 @@ | ||
| 224 | 218 | const models = await autodetectModels({ |
| 225 | 219 | llm: baseLlm, |
| 226 | 220 | model, |
| 227 | - ide, | |
| 228 | 221 | uniqueId, |
| 229 | - ideSettings, | |
| 230 | 222 | llmLogger, |
| 231 | 223 | config, |
| 232 | 224 | }); |
added core/config/yaml/models.vitest.ts +355 −0
| @@ -0,0 +1,355 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | + | |
| 4 | +import { ContinueConfig, ILLMLogger } from "../.."; | |
| 5 | +import { llmsFromModelConfig } from "./models"; | |
| 6 | + | |
| 7 | +// Mock the LLM classes | |
| 8 | +vi.mock("../../llm/llms", () => ({ | |
| 9 | + LLMClasses: [ | |
| 10 | + class MockOpenAI { | |
| 11 | + static providerName = "openai"; | |
| 12 | + static defaultOptions = { | |
| 13 | + completionOptions: { | |
| 14 | + maxTokens: 2048, | |
| 15 | + }, | |
| 16 | + }; | |
| 17 | + | |
| 18 | + constructor(options: any) { | |
| 19 | + Object.assign(this, options); | |
| 20 | + } | |
| 21 | + | |
| 22 | + async listModels() { | |
| 23 | + return ["gpt-4", "gpt-3.5-turbo"]; | |
| 24 | + } | |
| 25 | + }, | |
| 26 | + class MockAnthropic { | |
| 27 | + static providerName = "anthropic"; | |
| 28 | + static defaultOptions = { | |
| 29 | + completionOptions: { | |
| 30 | + maxTokens: 4096, | |
| 31 | + }, | |
| 32 | + }; | |
| 33 | + | |
| 34 | + constructor(options: any) { | |
| 35 | + Object.assign(this, options); | |
| 36 | + } | |
| 37 | + | |
| 38 | + async listModels() { | |
| 39 | + return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"]; | |
| 40 | + } | |
| 41 | + }, | |
| 42 | + ], | |
| 43 | +})); | |
| 44 | + | |
| 45 | +describe("llmsFromModelConfig requestOptions merging", () => { | |
| 46 | + let mockLLMLogger: ILLMLogger; | |
| 47 | + let mockConfig: ContinueConfig; | |
| 48 | + | |
| 49 | + beforeEach(() => { | |
| 50 | + mockLLMLogger = { log: vi.fn() } as any; | |
| 51 | + mockConfig = { | |
| 52 | + requestOptions: { | |
| 53 | + timeout: 30000, | |
| 54 | + headers: { | |
| 55 | + "User-Agent": "Continue/1.0.0", | |
| 56 | + }, | |
| 57 | + proxy: "global-proxy", | |
| 58 | + }, | |
| 59 | + contextProviders: [], | |
| 60 | + mcpServerStatuses: [], | |
| 61 | + rules: [], | |
| 62 | + selectedModelByRole: { | |
| 63 | + apply: null, | |
| 64 | + autocomplete: null, | |
| 65 | + chat: null, | |
| 66 | + edit: null, | |
| 67 | + embed: null, | |
| 68 | + rerank: null, | |
| 69 | + summarize: null, | |
| 70 | + }, | |
| 71 | + modelsByRole: { | |
| 72 | + apply: [], | |
| 73 | + autocomplete: [], | |
| 74 | + chat: [], | |
| 75 | + edit: [], | |
| 76 | + embed: [], | |
| 77 | + rerank: [], | |
| 78 | + summarize: [], | |
| 79 | + }, | |
| 80 | + slashCommands: [], | |
| 81 | + tools: [], | |
| 82 | + allowAnonymousTelemetry: false, | |
| 83 | + } as ContinueConfig; | |
| 84 | + vi.clearAllMocks(); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("should merge model requestOptions with config requestOptions", async () => { | |
| 88 | + const model: ModelConfig = { | |
| 89 | + name: "test-openai", | |
| 90 | + provider: "openai", | |
| 91 | + model: "gpt-4", | |
| 92 | + requestOptions: { | |
| 93 | + timeout: 60000, | |
| 94 | + headers: { | |
| 95 | + Authorization: "Bearer token123", | |
| 96 | + }, | |
| 97 | + proxy: "model-proxy", | |
| 98 | + }, | |
| 99 | + }; | |
| 100 | + | |
| 101 | + const result = await llmsFromModelConfig({ | |
| 102 | + model, | |
| 103 | + uniqueId: "test-id", | |
| 104 | + llmLogger: mockLLMLogger, | |
| 105 | + config: mockConfig, | |
| 106 | + }); | |
| 107 | + | |
| 108 | + expect(result).toHaveLength(1); | |
| 109 | + const llm = result[0]; | |
| 110 | + | |
| 111 | + // The LLM should have merged requestOptions | |
| 112 | + expect(llm.requestOptions).toEqual({ | |
| 113 | + timeout: 60000, // model-specific takes precedence | |
| 114 | + headers: { | |
| 115 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 116 | + Authorization: "Bearer token123", // from model | |
| 117 | + }, | |
| 118 | + proxy: "model-proxy", // model-specific takes precedence | |
| 119 | + }); | |
| 120 | + }); | |
| 121 | + | |
| 122 | + it("should use config requestOptions when model has no requestOptions", async () => { | |
| 123 | + const model: ModelConfig = { | |
| 124 | + name: "test-openai", | |
| 125 | + provider: "openai", | |
| 126 | + model: "gpt-4", | |
| 127 | + // no requestOptions | |
| 128 | + }; | |
| 129 | + | |
| 130 | + const result = await llmsFromModelConfig({ | |
| 131 | + model, | |
| 132 | + uniqueId: "test-id", | |
| 133 | + llmLogger: mockLLMLogger, | |
| 134 | + config: mockConfig, | |
| 135 | + }); | |
| 136 | + | |
| 137 | + expect(result).toHaveLength(1); | |
| 138 | + const llm = result[0]; | |
| 139 | + | |
| 140 | + // The LLM should have config requestOptions | |
| 141 | + expect(llm.requestOptions).toEqual(mockConfig.requestOptions); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should use model requestOptions when config has no requestOptions", async () => { | |
| 145 | + const model: ModelConfig = { | |
| 146 | + name: "test-openai", | |
| 147 | + provider: "openai", | |
| 148 | + model: "gpt-4", | |
| 149 | + requestOptions: { | |
| 150 | + timeout: 45000, | |
| 151 | + headers: { | |
| 152 | + "API-Key": "secret", | |
| 153 | + }, | |
| 154 | + }, | |
| 155 | + }; | |
| 156 | + | |
| 157 | + const configWithoutOptions = { ...mockConfig }; | |
| 158 | + delete configWithoutOptions.requestOptions; | |
| 159 | + | |
| 160 | + const result = await llmsFromModelConfig({ | |
| 161 | + model, | |
| 162 | + uniqueId: "test-id", | |
| 163 | + llmLogger: mockLLMLogger, | |
| 164 | + config: configWithoutOptions, | |
| 165 | + }); | |
| 166 | + | |
| 167 | + expect(result).toHaveLength(1); | |
| 168 | + const llm = result[0]; | |
| 169 | + | |
| 170 | + // The LLM should have model requestOptions | |
| 171 | + expect(llm.requestOptions).toEqual(model.requestOptions); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + it("should handle empty headers correctly in merge", async () => { | |
| 175 | + const model: ModelConfig = { | |
| 176 | + name: "test-openai", | |
| 177 | + provider: "openai", | |
| 178 | + model: "gpt-4", | |
| 179 | + requestOptions: { | |
| 180 | + timeout: 60000, | |
| 181 | + headers: {}, | |
| 182 | + }, | |
| 183 | + }; | |
| 184 | + | |
| 185 | + const configWithEmptyHeaders = { | |
| 186 | + ...mockConfig, | |
| 187 | + requestOptions: { | |
| 188 | + ...mockConfig.requestOptions!, | |
| 189 | + headers: {}, | |
| 190 | + }, | |
| 191 | + }; | |
| 192 | + | |
| 193 | + const result = await llmsFromModelConfig({ | |
| 194 | + model, | |
| 195 | + uniqueId: "test-id", | |
| 196 | + llmLogger: mockLLMLogger, | |
| 197 | + config: configWithEmptyHeaders, | |
| 198 | + }); | |
| 199 | + | |
| 200 | + expect(result).toHaveLength(1); | |
| 201 | + const llm = result[0]; | |
| 202 | + | |
| 203 | + // When headers merge to empty object, they should be undefined | |
| 204 | + expect(llm.requestOptions).toEqual({ | |
| 205 | + timeout: 60000, | |
| 206 | + proxy: "global-proxy", | |
| 207 | + headers: undefined, | |
| 208 | + }); | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should handle autodetect models with merged requestOptions", async () => { | |
| 212 | + const model: ModelConfig = { | |
| 213 | + name: "autodetect-openai", | |
| 214 | + provider: "openai", | |
| 215 | + model: "AUTODETECT", | |
| 216 | + requestOptions: { | |
| 217 | + timeout: 120000, | |
| 218 | + headers: { | |
| 219 | + "X-Custom": "autodetect", | |
| 220 | + }, | |
| 221 | + }, | |
| 222 | + }; | |
| 223 | + | |
| 224 | + const result = await llmsFromModelConfig({ | |
| 225 | + model, | |
| 226 | + uniqueId: "test-id", | |
| 227 | + llmLogger: mockLLMLogger, | |
| 228 | + config: mockConfig, | |
| 229 | + }); | |
| 230 | + | |
| 231 | + // Should return multiple models from listModels() | |
| 232 | + expect(result.length).toBeGreaterThan(0); | |
| 233 | + | |
| 234 | + // Each detected model should have the merged requestOptions | |
| 235 | + result.forEach((llm) => { | |
| 236 | + expect(llm.requestOptions).toEqual({ | |
| 237 | + timeout: 120000, // model-specific takes precedence | |
| 238 | + headers: { | |
| 239 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 240 | + "X-Custom": "autodetect", // from model | |
| 241 | + }, | |
| 242 | + proxy: "global-proxy", // from global request options | |
| 243 | + }); | |
| 244 | + }); | |
| 245 | + }); | |
| 246 | + | |
| 247 | + it("should handle unknown provider gracefully", async () => { | |
| 248 | + const model: ModelConfig = { | |
| 249 | + name: "unknown-provider", | |
| 250 | + provider: "unknown", | |
| 251 | + model: "unknown-model", | |
| 252 | + requestOptions: { | |
| 253 | + timeout: 60000, | |
| 254 | + }, | |
| 255 | + }; | |
| 256 | + | |
| 257 | + const result = await llmsFromModelConfig({ | |
| 258 | + model, | |
| 259 | + uniqueId: "test-id", | |
| 260 | + llmLogger: mockLLMLogger, | |
| 261 | + config: mockConfig, | |
| 262 | + }); | |
| 263 | + | |
| 264 | + // Should return empty array for unknown provider | |
| 265 | + expect(result).toHaveLength(0); | |
| 266 | + }); | |
| 267 | + | |
| 268 | + it("should preserve other model properties while merging requestOptions", async () => { | |
| 269 | + const model: ModelConfig = { | |
| 270 | + name: "test-anthropic", | |
| 271 | + provider: "anthropic", | |
| 272 | + model: "claude-3-5-sonnet-20241022", | |
| 273 | + roles: ["chat", "summarize"], | |
| 274 | + capabilities: ["tool_use", "image_input"], | |
| 275 | + defaultCompletionOptions: { | |
| 276 | + temperature: 0.7, | |
| 277 | + maxTokens: 1000, | |
| 278 | + }, | |
| 279 | + requestOptions: { | |
| 280 | + timeout: 90000, | |
| 281 | + }, | |
| 282 | + }; | |
| 283 | + | |
| 284 | + const result = await llmsFromModelConfig({ | |
| 285 | + model, | |
| 286 | + uniqueId: "test-id", | |
| 287 | + llmLogger: mockLLMLogger, | |
| 288 | + config: mockConfig, | |
| 289 | + }); | |
| 290 | + | |
| 291 | + expect(result).toHaveLength(1); | |
| 292 | + const llm = result[0]; | |
| 293 | + | |
| 294 | + // Should preserve model properties | |
| 295 | + expect(llm.title).toBe("test-anthropic"); | |
| 296 | + expect(llm.completionOptions?.temperature).toBe(0.7); | |
| 297 | + expect(llm.completionOptions?.maxTokens).toBe(1000); | |
| 298 | + expect(llm.capabilities?.tools).toBe(true); | |
| 299 | + expect(llm.capabilities?.uploadImage).toBe(true); | |
| 300 | + | |
| 301 | + // Should have merged requestOptions | |
| 302 | + expect(llm.requestOptions).toEqual({ | |
| 303 | + timeout: 90000, | |
| 304 | + headers: { | |
| 305 | + "User-Agent": "Continue/1.0.0", | |
| 306 | + }, | |
| 307 | + proxy: "global-proxy", | |
| 308 | + }); | |
| 309 | + }); | |
| 310 | + | |
| 311 | + it("should handle complex header merging scenarios", async () => { | |
| 312 | + const model: ModelConfig = { | |
| 313 | + name: "complex-headers", | |
| 314 | + provider: "openai", | |
| 315 | + model: "gpt-4", | |
| 316 | + requestOptions: { | |
| 317 | + headers: { | |
| 318 | + Authorization: "Bearer model-token", | |
| 319 | + Accept: "application/json", // Should override config Accept | |
| 320 | + "X-Model-Specific": "true", | |
| 321 | + }, | |
| 322 | + }, | |
| 323 | + }; | |
| 324 | + | |
| 325 | + const configWithMoreHeaders = { | |
| 326 | + ...mockConfig, | |
| 327 | + requestOptions: { | |
| 328 | + ...mockConfig.requestOptions!, | |
| 329 | + headers: { | |
| 330 | + ...mockConfig.requestOptions!.headers, | |
| 331 | + Accept: "text/plain", // Should be overridden by model | |
| 332 | + "Cache-Control": "no-cache", | |
| 333 | + }, | |
| 334 | + }, | |
| 335 | + }; | |
| 336 | + | |
| 337 | + const result = await llmsFromModelConfig({ | |
| 338 | + model, | |
| 339 | + uniqueId: "test-id", | |
| 340 | + llmLogger: mockLLMLogger, | |
| 341 | + config: configWithMoreHeaders, | |
| 342 | + }); | |
| 343 | + | |
| 344 | + expect(result).toHaveLength(1); | |
| 345 | + const llm = result[0]; | |
| 346 | + | |
| 347 | + expect(llm.requestOptions?.headers).toEqual({ | |
| 348 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 349 | + "Cache-Control": "no-cache", // from global request options | |
| 350 | + Authorization: "Bearer model-token", // from model | |
| 351 | + Accept: "application/json", // from model (overrides config) | |
| 352 | + "X-Model-Specific": "true", // from model | |
| 353 | + }); | |
| 354 | + }); | |
| 355 | +}); |
modified core/config/yaml/yamlToContinueConfig.ts +2 −0
| @@ -13,8 +13,10 @@ | ||
| 13 | 13 | rule: rule.rule, |
| 14 | 14 | globs: rule.globs, |
| 15 | 15 | name: rule.name, |
| 16 | + description: rule.description, | |
| 16 | 17 | ruleFile: rule.sourceFile, |
| 17 | 18 | alwaysApply: rule.alwaysApply, |
| 19 | + invokable: rule.invokable ?? false, | |
| 18 | 20 | }; |
| 19 | 21 | } |
| 20 | 22 | } |
modified core/context/mcp/MCPConnection.ts +36 −9
| @@ -1,6 +1,4 @@ | ||
| 1 | 1 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; |
| 2 | -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; | |
| 3 | - | |
| 4 | 2 | import { |
| 5 | 3 | SSEClientTransport, |
| 6 | 4 | SseError, |
| @@ -8,7 +6,8 @@ | ||
| 8 | 6 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; |
| 9 | 7 | import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; |
| 10 | 8 | import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; |
| 11 | - | |
| 9 | +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; | |
| 10 | +import { Agent as HttpsAgent } from "https"; | |
| 12 | 11 | import { |
| 13 | 12 | IDE, |
| 14 | 13 | MCPConnectionStatus, |
| @@ -53,6 +52,7 @@ | ||
| 53 | 52 | public status: MCPConnectionStatus = "not-connected"; |
| 54 | 53 | public isProtectedResource = false; |
| 55 | 54 | public errors: string[] = []; |
| 55 | + public infos: string[] = []; | |
| 56 | 56 | public prompts: MCPPrompt[] = []; |
| 57 | 57 | public tools: MCPTool[] = []; |
| 58 | 58 | public resources: MCPResource[] = []; |
| @@ -94,6 +94,7 @@ | ||
| 94 | 94 | return { |
| 95 | 95 | ...this.options, |
| 96 | 96 | errors: this.errors, |
| 97 | + infos: this.infos, | |
| 97 | 98 | prompts: this.prompts, |
| 98 | 99 | resources: this.resources, |
| 99 | 100 | resourceTemplates: this.resourceTemplates, |
| @@ -123,6 +124,7 @@ | ||
| 123 | 124 | this.resources = []; |
| 124 | 125 | this.resourceTemplates = []; |
| 125 | 126 | this.errors = []; |
| 127 | + this.infos = []; | |
| 126 | 128 | this.stdioOutput = { stdout: "", stderr: "" }; |
| 127 | 129 | |
| 128 | 130 | this.abortController.abort(); |
| @@ -281,6 +283,16 @@ | ||
| 281 | 283 | if (msg.includes("spawn") && msg.includes("enoent")) { |
| 282 | 284 | const command = msg.split(" ")[1]; |
| 283 | 285 | errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`; |
| 286 | + if (["uv", "uvx"].includes(command)) { | |
| 287 | + this.infos.push( | |
| 288 | + 'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>', | |
| 289 | + ); | |
| 290 | + } | |
| 291 | + if (["node", "npx"].includes(command)) { | |
| 292 | + this.infos.push( | |
| 293 | + 'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>', | |
| 294 | + ); | |
| 295 | + } | |
| 284 | 296 | } else { |
| 285 | 297 | errorMessage += "Error: " + error.message; |
| 286 | 298 | } |
| @@ -393,6 +405,11 @@ | ||
| 393 | 405 | case "websocket": |
| 394 | 406 | return new WebSocketClientTransport(new URL(options.transport.url)); |
| 395 | 407 | case "sse": |
| 408 | + const sseAgent = | |
| 409 | + options.transport.requestOptions?.verifySsl === false | |
| 410 | + ? new HttpsAgent({ rejectUnauthorized: false }) | |
| 411 | + : undefined; | |
| 412 | + | |
| 396 | 413 | return new SSEClientTransport(new URL(options.transport.url), { |
| 397 | 414 | eventSourceInit: { |
| 398 | 415 | fetch: (input, init) => |
| @@ -404,17 +421,27 @@ | ||
| 404 | 421 | | Record<string, string> |
| 405 | 422 | | undefined), |
| 406 | 423 | }, |
| 424 | + ...(sseAgent && { agent: sseAgent }), | |
| 407 | 425 | }), |
| 408 | 426 | }, |
| 409 | - requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 427 | + requestInit: { | |
| 428 | + headers: options.transport.requestOptions?.headers, | |
| 429 | + ...(sseAgent && { agent: sseAgent }), | |
| 430 | + }, | |
| 410 | 431 | }); |
| 411 | 432 | case "streamable-http": |
| 412 | - return new StreamableHTTPClientTransport( | |
| 413 | - new URL(options.transport.url), | |
| 414 | - { | |
| 415 | - requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 433 | + const { url, requestOptions } = options.transport; | |
| 434 | + const streamableAgent = | |
| 435 | + requestOptions?.verifySsl === false | |
| 436 | + ? new HttpsAgent({ rejectUnauthorized: false }) | |
| 437 | + : undefined; | |
| 438 | + | |
| 439 | + return new StreamableHTTPClientTransport(new URL(url), { | |
| 440 | + requestInit: { | |
| 441 | + headers: requestOptions?.headers, | |
| 442 | + ...(streamableAgent && { agent: streamableAgent }), | |
| 416 | 443 | }, |
| 417 | - ); | |
| 444 | + }); | |
| 418 | 445 | default: |
| 419 | 446 | throw new Error( |
| 420 | 447 | `Unsupported transport type: ${(options.transport as any).type}`, |
modified core/context/mcp/MCPConnection.vitest.ts +1 −0
| @@ -142,6 +142,7 @@ | ||
| 142 | 142 | expect(status).toEqual({ |
| 143 | 143 | ...options, |
| 144 | 144 | errors: [], |
| 145 | + infos: [], | |
| 145 | 146 | isProtectedResource: false, |
| 146 | 147 | prompts: [], |
| 147 | 148 | resources: [], |
modified core/context/mcp/MCPManagerSingleton.ts +15 −0
| @@ -48,6 +48,21 @@ | ||
| 48 | 48 | this.connections.delete(id); |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | + async shutdown() { | |
| 52 | + if (this.connections.size > 0) { | |
| 53 | + await Promise.allSettled( | |
| 54 | + Array.from(this.connections.entries()).map(([id, connection]) => { | |
| 55 | + try { | |
| 56 | + connection.abortController.abort(); | |
| 57 | + void connection.client.close(); | |
| 58 | + } finally { | |
| 59 | + this.connections.delete(id); | |
| 60 | + } | |
| 61 | + }), | |
| 62 | + ); | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 51 | 66 | setConnections( |
| 52 | 67 | servers: MCPOptions[], |
| 53 | 68 | forceRefresh: boolean, |
modified core/context/mcp/MCPOauth.ts +193 −63
| @@ -12,65 +12,121 @@ | ||
| 12 | 12 | |
| 13 | 13 | import http from "http"; |
| 14 | 14 | import url from "url"; |
| 15 | +import crypto from "crypto"; | |
| 15 | 16 | import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; |
| 16 | 17 | |
| 17 | -let authenticatingMCPContext = null as { | |
| 18 | - authenticatingServer: MCPServerStatus; | |
| 19 | - ide: IDE; | |
| 20 | -} | null; | |
| 18 | +// Use a Map to support concurrent authentications for different servers | |
| 19 | +const authenticatingContexts = new Map< | |
| 20 | + string, | |
| 21 | + { | |
| 22 | + authenticatingServer: MCPServerStatus; | |
| 23 | + ide: IDE; | |
| 24 | + state?: string; | |
| 25 | + } | |
| 26 | +>(); | |
| 27 | + | |
| 28 | +// Map state parameters to server URLs for OAuth callback matching | |
| 29 | +const stateToServerUrl = new Map<string, string>(); | |
| 21 | 30 | |
| 22 | 31 | const PORT = 3000; |
| 23 | 32 | |
| 24 | -const server = http.createServer((req, res) => { | |
| 25 | - try { | |
| 26 | - if (!req.url) { | |
| 27 | - throw new Error("no url found"); | |
| 28 | - } | |
| 33 | +let serverInstance: http.Server | null = null; | |
| 29 | 34 | |
| 30 | - const parsedUrl = url.parse(req.url, true); | |
| 31 | - if (!parsedUrl.query["code"]) { | |
| 32 | - throw new Error("no query params found"); | |
| 33 | - } | |
| 35 | +const createServerForOAuth = () => | |
| 36 | + http.createServer((req, res) => { | |
| 37 | + try { | |
| 38 | + if (!req.url) { | |
| 39 | + throw new Error("no url found"); | |
| 40 | + } | |
| 41 | + | |
| 42 | + const parsedUrl = url.parse(req.url, true); | |
| 43 | + if (!parsedUrl.query["code"]) { | |
| 44 | + throw new Error("no query params found"); | |
| 45 | + } | |
| 34 | 46 | |
| 35 | - void handleMCPOauthCode(parsedUrl.query["code"] as string); | |
| 47 | + const code = parsedUrl.query["code"] as string; | |
| 48 | + const state = parsedUrl.query["state"] as string | undefined; | |
| 36 | 49 | |
| 37 | - const html = ` | |
| 50 | + void handleMCPOauthCode(code, state); | |
| 51 | + | |
| 52 | + const html = ` | |
| 38 | 53 | <!DOCTYPE html> |
| 39 | 54 | <html> |
| 40 | 55 | <head><title>Authentication Complete</title></head> |
| 41 | 56 | <body>Authentication Complete. You can close this page now.</body> |
| 42 | 57 | </html>`; |
| 43 | 58 | |
| 44 | - res.writeHead(200, { | |
| 45 | - "Content-Type": "text/html", | |
| 46 | - }); | |
| 47 | - res.end(html); | |
| 48 | - } catch (error) { | |
| 49 | - res.writeHead(400, { "Content-Type": "text/plain" }); | |
| 50 | - res.end(`Unexpected redirect error: ${(error as Error).message}`); | |
| 51 | - } | |
| 52 | -}); | |
| 59 | + res.writeHead(200, { | |
| 60 | + "Content-Type": "text/html", | |
| 61 | + }); | |
| 62 | + res.end(html); | |
| 63 | + } catch (error) { | |
| 64 | + res.writeHead(400, { "Content-Type": "text/plain" }); | |
| 65 | + res.end(`Unexpected redirect error: ${(error as Error).message}`); | |
| 66 | + } | |
| 67 | + }); | |
| 53 | 68 | |
| 54 | 69 | type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; |
| 55 | 70 | type MCPOauthStorageKey = keyof MCPOauthStorage; |
| 56 | 71 | |
| 57 | 72 | class MCPConnectionOauthProvider implements OAuthClientProvider { |
| 58 | 73 | private globalContext: GlobalContext; |
| 74 | + private _redirectUrl: string; | |
| 75 | + private _redirectUrlInitialized: Promise<void>; | |
| 59 | 76 | |
| 60 | 77 | constructor( |
| 61 | 78 | public oauthServerUrl: string, |
| 62 | 79 | private ide: IDE, |
| 63 | 80 | ) { |
| 64 | 81 | this.globalContext = new GlobalContext(); |
| 82 | + // Set default redirect URL immediately for synchronous access | |
| 83 | + this._redirectUrl = `http://localhost:${PORT}`; | |
| 84 | + // Initialize actual redirect URL asynchronously | |
| 85 | + this._redirectUrlInitialized = this._initializeRedirectUrl(); | |
| 86 | + } | |
| 87 | + | |
| 88 | + private async _initializeRedirectUrl(): Promise<void> { | |
| 89 | + try { | |
| 90 | + // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI | |
| 91 | + if (this.ide.getExternalUri) { | |
| 92 | + const localUri = `http://localhost:${PORT}`; | |
| 93 | + const externalUri = await this.ide.getExternalUri(localUri); | |
| 94 | + this._redirectUrl = externalUri; | |
| 95 | + } | |
| 96 | + // Otherwise keep the default localhost URL | |
| 97 | + } catch (error) { | |
| 98 | + console.error("Failed to initialize redirect URL:", error); | |
| 99 | + // Keep default URL on error | |
| 100 | + } | |
| 65 | 101 | } |
| 66 | 102 | |
| 67 | 103 | get redirectUrl() { |
| 68 | - return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server? | |
| 104 | + // Always return a valid URL, even if initialization is pending | |
| 105 | + return this._redirectUrl; | |
| 106 | + } | |
| 107 | + | |
| 108 | + getRedirectUrlWithState(state: string): string { | |
| 109 | + // Add state parameter to redirect URL | |
| 110 | + const urlObj = new URL(this._redirectUrl); | |
| 111 | + urlObj.searchParams.set("state", state); | |
| 112 | + return urlObj.toString(); | |
| 113 | + } | |
| 114 | + | |
| 115 | + async ensureRedirectUrl(): Promise<string> { | |
| 116 | + // Wait for initialization to complete before returning | |
| 117 | + await this._redirectUrlInitialized; | |
| 118 | + return this._redirectUrl; | |
| 69 | 119 | } |
| 70 | 120 | |
| 71 | 121 | get clientMetadata() { |
| 122 | + // Generate state parameter if needed | |
| 123 | + const state = authenticatingContexts.get(this.oauthServerUrl)?.state; | |
| 124 | + const redirectUri = state | |
| 125 | + ? this.getRedirectUrlWithState(state) | |
| 126 | + : this.redirectUrl; | |
| 127 | + | |
| 72 | 128 | return { |
| 73 | - redirect_uris: [this.redirectUrl], | |
| 129 | + redirect_uris: [redirectUri], | |
| 74 | 130 | token_endpoint_auth_method: "none", |
| 75 | 131 | grant_types: ["authorization_code", "refresh_token"], |
| 76 | 132 | response_types: ["code"], |
| @@ -151,14 +207,28 @@ | ||
| 151 | 207 | } |
| 152 | 208 | |
| 153 | 209 | async redirectToAuthorization(authorizationUrl: URL) { |
| 154 | - if (!server.listening) { | |
| 155 | - server.listen(PORT, () => { | |
| 156 | - console.debug( | |
| 157 | - `Server started for MCP Oauth process at http://localhost:${PORT}/`, | |
| 158 | - ); | |
| 159 | - }); | |
| 210 | + // Ensure redirect URL is initialized before proceeding | |
| 211 | + await this.ensureRedirectUrl(); | |
| 212 | + | |
| 213 | + // Only create and start local server if using localhost redirect | |
| 214 | + // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism | |
| 215 | + if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) { | |
| 216 | + if (!serverInstance) { | |
| 217 | + serverInstance = createServerForOAuth(); | |
| 218 | + } | |
| 219 | + if (!serverInstance.listening) { | |
| 220 | + await new Promise<void>((resolve, reject) => { | |
| 221 | + serverInstance!.listen(PORT, () => { | |
| 222 | + console.debug( | |
| 223 | + `Server started for MCP Oauth process at http://localhost:${PORT}/`, | |
| 224 | + ); | |
| 225 | + resolve(); | |
| 226 | + }); | |
| 227 | + serverInstance!.on("error", reject); | |
| 228 | + }); | |
| 229 | + } | |
| 160 | 230 | } |
| 161 | - void this.ide.openUrl(authorizationUrl.toString()); | |
| 231 | + await this.ide.openUrl(authorizationUrl.toString()); | |
| 162 | 232 | } |
| 163 | 233 | } |
| 164 | 234 | |
| @@ -175,49 +245,109 @@ | ||
| 175 | 245 | export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { |
| 176 | 246 | const mcpServerUrl = (mcpServer.transport as SSEOptions).url; |
| 177 | 247 | const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); |
| 178 | - authenticatingMCPContext = { | |
| 248 | + // Ensure redirect URL is ready before starting auth | |
| 249 | + await authProvider.ensureRedirectUrl(); | |
| 250 | + | |
| 251 | + // Generate a unique state parameter for this auth flow | |
| 252 | + const state = crypto.randomUUID(); | |
| 253 | + | |
| 254 | + // Store context for this specific server with state | |
| 255 | + authenticatingContexts.set(mcpServerUrl, { | |
| 179 | 256 | authenticatingServer: mcpServer, |
| 180 | 257 | ide, |
| 181 | - }; | |
| 182 | - return await auth(authProvider, { | |
| 183 | - serverUrl: mcpServerUrl, | |
| 258 | + state, | |
| 184 | 259 | }); |
| 260 | + | |
| 261 | + // Map state to server URL for callback matching | |
| 262 | + stateToServerUrl.set(state, mcpServerUrl); | |
| 263 | + | |
| 264 | + try { | |
| 265 | + return await auth(authProvider, { | |
| 266 | + serverUrl: mcpServerUrl, | |
| 267 | + }); | |
| 268 | + } catch (error) { | |
| 269 | + // Clean up on error | |
| 270 | + authenticatingContexts.delete(mcpServerUrl); | |
| 271 | + stateToServerUrl.delete(state); | |
| 272 | + throw error; | |
| 273 | + } | |
| 185 | 274 | } |
| 186 | 275 | |
| 187 | 276 | /** |
| 188 | 277 | * handle the authentication code received from the oauth redirect |
| 189 | 278 | */ |
| 190 | -async function handleMCPOauthCode(authorizationCode: string) { | |
| 191 | - if (!authenticatingMCPContext) { | |
| 192 | - return; | |
| 279 | +async function handleMCPOauthCode(authorizationCode: string, state?: string) { | |
| 280 | + let serverUrl: string | undefined; | |
| 281 | + let context: | |
| 282 | + | { authenticatingServer: MCPServerStatus; ide: IDE; state?: string } | |
| 283 | + | undefined; | |
| 284 | + | |
| 285 | + if (state) { | |
| 286 | + // Use state parameter to find the correct server | |
| 287 | + serverUrl = stateToServerUrl.get(state); | |
| 288 | + if (serverUrl) { | |
| 289 | + context = authenticatingContexts.get(serverUrl); | |
| 290 | + } | |
| 291 | + } else { | |
| 292 | + // Fallback: if no state or single context, use the first one | |
| 293 | + const contexts = Array.from(authenticatingContexts.entries()); | |
| 294 | + if (contexts.length === 1) { | |
| 295 | + [serverUrl, context] = contexts[0]; | |
| 296 | + } | |
| 193 | 297 | } |
| 194 | - const { ide, authenticatingServer } = authenticatingMCPContext; | |
| 195 | - const serverUrl = (authenticatingServer.transport as SSEOptions).url; | |
| 196 | 298 | |
| 197 | - if (!serverUrl) { | |
| 198 | - void ide.showToast("error", "No MCP server url found for authentication"); | |
| 299 | + if (!context || !serverUrl) { | |
| 300 | + console.error("No matching authenticating context found for state:", state); | |
| 199 | 301 | return; |
| 200 | 302 | } |
| 201 | - if (!authorizationCode) { | |
| 202 | - void ide.showToast( | |
| 203 | - "error", | |
| 204 | - `No MCP authorization code found for ${serverUrl}`, | |
| 205 | - ); | |
| 206 | - return; | |
| 207 | - } | |
| 208 | - server.close(() => console.debug("Server for MCP Oauth process was closed")); | |
| 209 | - const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); | |
| 210 | - const authStatus = await auth(authProvider, { | |
| 211 | - serverUrl, | |
| 212 | - authorizationCode, | |
| 213 | - }); | |
| 214 | - if (authStatus === "AUTHORIZED") { | |
| 215 | - const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports | |
| 216 | - await MCPManagerSingleton.getInstance().refreshConnection( | |
| 217 | - authenticatingServer.id, | |
| 218 | - ); | |
| 303 | + | |
| 304 | + const { ide, authenticatingServer } = context; | |
| 305 | + | |
| 306 | + try { | |
| 307 | + if (!serverUrl) { | |
| 308 | + throw new Error("No MCP server url found for authentication"); | |
| 309 | + } | |
| 310 | + if (!authorizationCode) { | |
| 311 | + throw new Error(`No MCP authorization code found for ${serverUrl}`); | |
| 312 | + } | |
| 313 | + | |
| 314 | + // Close the server before processing auth | |
| 315 | + if (serverInstance) { | |
| 316 | + await new Promise<void>((resolve) => { | |
| 317 | + serverInstance!.close(() => { | |
| 318 | + console.debug("Server for MCP Oauth process was closed"); | |
| 319 | + serverInstance = null; | |
| 320 | + resolve(); | |
| 321 | + }); | |
| 322 | + }); | |
| 323 | + } | |
| 324 | + | |
| 325 | + const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); | |
| 326 | + await authProvider.ensureRedirectUrl(); | |
| 327 | + const authStatus = await auth(authProvider, { | |
| 328 | + serverUrl, | |
| 329 | + authorizationCode, | |
| 330 | + }); | |
| 331 | + | |
| 332 | + if (authStatus === "AUTHORIZED") { | |
| 333 | + const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports | |
| 334 | + await MCPManagerSingleton.getInstance().refreshConnection( | |
| 335 | + authenticatingServer.id, | |
| 336 | + ); | |
| 337 | + } | |
| 338 | + } catch (error) { | |
| 339 | + const errorMessage = error instanceof Error ? error.message : String(error); | |
| 340 | + console.error("OAuth authorization failed:", errorMessage); | |
| 341 | + if (context?.ide) { | |
| 342 | + await context.ide.showToast("error", `OAuth failed: ${errorMessage}`); | |
| 343 | + } | |
| 344 | + } finally { | |
| 345 | + // Always clean up the context and state mapping | |
| 346 | + authenticatingContexts.delete(serverUrl); | |
| 347 | + if (state) { | |
| 348 | + stateToServerUrl.delete(state); | |
| 349 | + } | |
| 219 | 350 | } |
| 220 | - authenticatingMCPContext = null; | |
| 221 | 351 | } |
| 222 | 352 | |
| 223 | 353 | export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { |
modified core/context/mcp/MCPOauth.vitest.ts +149 −0
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | mockIde = { |
| 34 | 34 | openUrl: vi.fn(), |
| 35 | 35 | showToast: vi.fn(), |
| 36 | + getExternalUri: vi.fn((uri) => Promise.resolve(uri)), | |
| 36 | 37 | }; |
| 37 | 38 | |
| 38 | 39 | mockMcpServer = { |
| @@ -178,4 +179,152 @@ | ||
| 178 | 179 | }); |
| 179 | 180 | }); |
| 180 | 181 | }); |
| 182 | + | |
| 183 | + describe("redirect URL handling", () => { | |
| 184 | + test("should use getExternalUri when available for VS Code", async () => { | |
| 185 | + const vscodeIde = { | |
| 186 | + ...mockIde, | |
| 187 | + getExternalUri: vi.fn((uri) => | |
| 188 | + Promise.resolve("https://vscode.dev/redirect"), | |
| 189 | + ), | |
| 190 | + }; | |
| 191 | + | |
| 192 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 193 | + const mockAuth = vi.mocked(auth); | |
| 194 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 195 | + | |
| 196 | + await performAuth(mockMcpServer, vscodeIde); | |
| 197 | + | |
| 198 | + expect(vscodeIde.getExternalUri).toHaveBeenCalledWith( | |
| 199 | + "http://localhost:3000", | |
| 200 | + ); | |
| 201 | + }); | |
| 202 | + | |
| 203 | + test("should fallback to localhost when getExternalUri is not available", async () => { | |
| 204 | + const ideWithoutExternalUri = { | |
| 205 | + openUrl: vi.fn(() => Promise.resolve()), | |
| 206 | + showToast: vi.fn(() => Promise.resolve()), | |
| 207 | + }; | |
| 208 | + | |
| 209 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 210 | + const mockAuth = vi.mocked(auth); | |
| 211 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 212 | + | |
| 213 | + await performAuth(mockMcpServer, ideWithoutExternalUri as any); | |
| 214 | + | |
| 215 | + // Should still work without getExternalUri | |
| 216 | + expect(mockAuth).toHaveBeenCalled(); | |
| 217 | + }); | |
| 218 | + | |
| 219 | + test("should handle getExternalUri errors gracefully", async () => { | |
| 220 | + const errorIde = { | |
| 221 | + ...mockIde, | |
| 222 | + getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))), | |
| 223 | + }; | |
| 224 | + | |
| 225 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 226 | + const mockAuth = vi.mocked(auth); | |
| 227 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 228 | + | |
| 229 | + // Should not throw, should fallback to localhost | |
| 230 | + await performAuth(mockMcpServer, errorIde); | |
| 231 | + | |
| 232 | + expect(mockAuth).toHaveBeenCalled(); | |
| 233 | + }); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + describe("concurrent authentication", () => { | |
| 237 | + test("should handle multiple concurrent auth flows", async () => { | |
| 238 | + const server1 = { | |
| 239 | + id: "server-1", | |
| 240 | + transport: { type: "sse" as const, url: "https://server1.com" }, | |
| 241 | + status: "connected" as const, | |
| 242 | + errors: [], | |
| 243 | + isProtectedResource: false, | |
| 244 | + prompts: [], | |
| 245 | + tools: [], | |
| 246 | + resources: [], | |
| 247 | + resourceTemplates: [], | |
| 248 | + name: "server-1", | |
| 249 | + }; | |
| 250 | + const server2 = { | |
| 251 | + id: "server-2", | |
| 252 | + transport: { type: "sse" as const, url: "https://server2.com" }, | |
| 253 | + status: "connected" as const, | |
| 254 | + errors: [], | |
| 255 | + isProtectedResource: false, | |
| 256 | + prompts: [], | |
| 257 | + tools: [], | |
| 258 | + resources: [], | |
| 259 | + resourceTemplates: [], | |
| 260 | + name: "server-2", | |
| 261 | + }; | |
| 262 | + | |
| 263 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 264 | + const mockAuth = vi.mocked(auth); | |
| 265 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 266 | + | |
| 267 | + // Start two auth flows concurrently | |
| 268 | + const [result1, result2] = await Promise.all([ | |
| 269 | + performAuth(server1, mockIde), | |
| 270 | + performAuth(server2, mockIde), | |
| 271 | + ]); | |
| 272 | + | |
| 273 | + expect(result1).toBe("AUTHORIZED"); | |
| 274 | + expect(result2).toBe("AUTHORIZED"); | |
| 275 | + expect(mockAuth).toHaveBeenCalledTimes(2); | |
| 276 | + }); | |
| 277 | + }); | |
| 278 | + | |
| 279 | + describe("error handling", () => { | |
| 280 | + test("should clean up context on auth failure", async () => { | |
| 281 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 282 | + const mockAuth = vi.mocked(auth); | |
| 283 | + | |
| 284 | + // First successful call to set up the context | |
| 285 | + mockAuth.mockResolvedValueOnce("AUTHORIZED"); | |
| 286 | + await performAuth(mockMcpServer, mockIde); | |
| 287 | + | |
| 288 | + // Reset mock for the failure test | |
| 289 | + mockAuth.mockRejectedValueOnce(new Error("Auth failed")); | |
| 290 | + | |
| 291 | + // Second call that should fail and clean up | |
| 292 | + await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow( | |
| 293 | + "Auth failed", | |
| 294 | + ); | |
| 295 | + | |
| 296 | + // Verify auth was called twice | |
| 297 | + expect(mockAuth).toHaveBeenCalledTimes(2); | |
| 298 | + | |
| 299 | + // The context cleanup happens internally in performAuth's catch block | |
| 300 | + // We can verify it indirectly by checking that a subsequent auth call works | |
| 301 | + mockAuth.mockResolvedValueOnce("AUTHORIZED"); | |
| 302 | + const result = await performAuth(mockMcpServer, mockIde); | |
| 303 | + expect(result).toBe("AUTHORIZED"); | |
| 304 | + }); | |
| 305 | + | |
| 306 | + test("should handle missing server URL", async () => { | |
| 307 | + const invalidServer = { | |
| 308 | + id: "invalid", | |
| 309 | + transport: { type: "sse" as const, url: "" }, | |
| 310 | + status: "connected" as const, | |
| 311 | + errors: [], | |
| 312 | + isProtectedResource: false, | |
| 313 | + prompts: [], | |
| 314 | + tools: [], | |
| 315 | + resources: [], | |
| 316 | + resourceTemplates: [], | |
| 317 | + name: "invalid", | |
| 318 | + }; | |
| 319 | + | |
| 320 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 321 | + const mockAuth = vi.mocked(auth); | |
| 322 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 323 | + | |
| 324 | + await performAuth(invalidServer, mockIde); | |
| 325 | + | |
| 326 | + // Should still attempt auth with empty URL | |
| 327 | + expect(mockAuth).toHaveBeenCalled(); | |
| 328 | + }); | |
| 329 | + }); | |
| 181 | 330 | }); |
modified core/context/providers/CodeContextProvider.ts +1 −1
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | displayTitle: "Code", |
| 17 | 17 | description: "Type to search", |
| 18 | 18 | type: "submenu", |
| 19 | - dependsOnIndexing: true, | |
| 19 | + dependsOnIndexing: ["chunk", "codeSnippets"], | |
| 20 | 20 | }; |
| 21 | 21 | |
| 22 | 22 | async getContextItems( |
deleted core/context/providers/CodeHighlightsContextProvider.ts +0 −68
| @@ -1,68 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - ContextItem, | |
| 3 | - ContextProviderDescription, | |
| 4 | - ContextProviderExtras, | |
| 5 | -} from "../../index.js"; | |
| 6 | -import { BaseContextProvider } from "../index.js"; | |
| 7 | - | |
| 8 | -const HIGHLIGHTS_TOKEN_BUDGET = 2000; | |
| 9 | - | |
| 10 | -class CodeHighlightsContextProvider extends BaseContextProvider { | |
| 11 | - static description: ContextProviderDescription = { | |
| 12 | - title: "highlights", | |
| 13 | - displayTitle: "Highlights", | |
| 14 | - description: "Code highlights from open files", | |
| 15 | - type: "normal", | |
| 16 | - renderInlineAs: "", | |
| 17 | - }; | |
| 18 | - | |
| 19 | - async getContextItems( | |
| 20 | - query: string, | |
| 21 | - extras: ContextProviderExtras, | |
| 22 | - ): Promise<ContextItem[]> { | |
| 23 | - // const { getHighlightsThatFit } = await import( | |
| 24 | - // "llm-code-highlighter/src/index.continue.js" | |
| 25 | - // ); | |
| 26 | - const ide = extras.ide; | |
| 27 | - const openFiles = await ide.getOpenFiles(); | |
| 28 | - // const allFiles: { name: string; absPath: string; content: string }[] = | |
| 29 | - // await Promise.all( | |
| 30 | - // openFiles.map(async (filepath: string) => { | |
| 31 | - // return { | |
| 32 | - // name: getBasename(filepath), | |
| 33 | - // absPath: filepath, | |
| 34 | - // content: `${await ide.readFile(filepath)}`, | |
| 35 | - // }; | |
| 36 | - // }), | |
| 37 | - // ); | |
| 38 | - // const contextSizer = { | |
| 39 | - // fits(content: string): boolean { | |
| 40 | - // return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET; | |
| 41 | - // }, | |
| 42 | - // }; | |
| 43 | - // const repoMap = await getHighlightsThatFit( | |
| 44 | - // contextSizer, | |
| 45 | - // [], | |
| 46 | - // allFiles | |
| 47 | - // .filter((file) => file.content.length > 0) | |
| 48 | - // .map((file) => { | |
| 49 | - // return { | |
| 50 | - // relPath: file.name, | |
| 51 | - // code: file.content, | |
| 52 | - // }; | |
| 53 | - // }), | |
| 54 | - // ); | |
| 55 | - // return [ | |
| 56 | - // { | |
| 57 | - // content: repoMap ? repoMap : "", | |
| 58 | - // name: "Code Highlights", | |
| 59 | - // description: "Code highlights from open files", | |
| 60 | - // }, | |
| 61 | - // ]; | |
| 62 | - return []; | |
| 63 | - } | |
| 64 | - | |
| 65 | - async load(): Promise<void> {} | |
| 66 | -} | |
| 67 | - | |
| 68 | -export default CodeHighlightsContextProvider; |
deleted core/context/providers/CodeOutlineContextProvider.ts +0 −56
| @@ -1,56 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - ContextItem, | |
| 3 | - ContextProviderDescription, | |
| 4 | - ContextProviderExtras, | |
| 5 | -} from "../../index.js"; | |
| 6 | -import { BaseContextProvider } from "../index.js"; | |
| 7 | - | |
| 8 | -class CodeOutlineContextProvider extends BaseContextProvider { | |
| 9 | - static description: ContextProviderDescription = { | |
| 10 | - title: "outline", | |
| 11 | - displayTitle: "Outline", | |
| 12 | - description: "Definition lines only (from open files)", | |
| 13 | - type: "normal", | |
| 14 | - renderInlineAs: "", | |
| 15 | - }; | |
| 16 | - | |
| 17 | - async getContextItems( | |
| 18 | - query: string, | |
| 19 | - extras: ContextProviderExtras, | |
| 20 | - ): Promise<ContextItem[]> { | |
| 21 | - const ide = extras.ide; | |
| 22 | - const openFiles = await ide.getOpenFiles(); | |
| 23 | - // const allFiles: { name: string; absPath: string; content: string }[] = | |
| 24 | - // await Promise.all( | |
| 25 | - // openFiles.map(async (filepath: string) => { | |
| 26 | - // return { | |
| 27 | - // name: getBasename(filepath), | |
| 28 | - // absPath: filepath, | |
| 29 | - // content: `${await ide.readFile(filepath)}`, | |
| 30 | - // }; | |
| 31 | - // }), | |
| 32 | - // ); | |
| 33 | - // const outlines = await getOutlines( | |
| 34 | - // allFiles | |
| 35 | - // .filter((file) => file.content.length > 0) | |
| 36 | - // .map((file) => { | |
| 37 | - // return { | |
| 38 | - // relPath: file.name, | |
| 39 | - // code: file.content, | |
| 40 | - // }; | |
| 41 | - // }) | |
| 42 | - // ); | |
| 43 | - // return [ | |
| 44 | - // { | |
| 45 | - // content: outlines ? outlines : "", | |
| 46 | - // name: "Code Outline", | |
| 47 | - // description: "Definition lines only (from open files)", | |
| 48 | - // }, | |
| 49 | - // ]; | |
| 50 | - return []; | |
| 51 | - } | |
| 52 | - | |
| 53 | - async load(): Promise<void> {} | |
| 54 | -} | |
| 55 | - | |
| 56 | -export default CodeOutlineContextProvider; |
modified core/context/providers/CodebaseContextProvider.ts +1 −0
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | description: "Automatically find relevant files", |
| 14 | 14 | type: "normal", |
| 15 | 15 | renderInlineAs: "", |
| 16 | + dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"], | |
| 16 | 17 | }; |
| 17 | 18 | |
| 18 | 19 | async getContextItems( |
modified core/context/providers/DatabaseContextProvider.ts +4 −0
| @@ -18,6 +18,10 @@ | ||
| 18 | 18 | renderInlineAs: "", |
| 19 | 19 | }; |
| 20 | 20 | |
| 21 | + get deprecationMessage() { | |
| 22 | + return "The database context provider is deprecated and may be removed in a later version. Please consider using a database MCP server like postgres-mcp (https://hub.continue.dev/anthropic/postgres-mcp) instead."; | |
| 23 | + } | |
| 24 | + | |
| 21 | 25 | async getContextItems( |
| 22 | 26 | query: string, |
| 23 | 27 | extras: ContextProviderExtras, |
modified core/context/providers/DiscordContextProvider.ts +5 −1
| @@ -3,8 +3,8 @@ | ||
| 3 | 3 | ContextProviderDescription, |
| 4 | 4 | ContextProviderExtras, |
| 5 | 5 | ContextSubmenuItem, |
| 6 | - LoadSubmenuItemsArgs, | |
| 7 | 6 | FetchFunction, |
| 7 | + LoadSubmenuItemsArgs, | |
| 8 | 8 | } from "../../index.js"; |
| 9 | 9 | import { BaseContextProvider } from "../index.js"; |
| 10 | 10 | |
| @@ -43,6 +43,10 @@ | ||
| 43 | 43 | return `${this.baseUrl}${path}`; |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | + get deprecationMessage() { | |
| 47 | + return "The Discord context provider is now deprecated and may be removed in a later version. Please consider using the Discord MCP (hub.docker.com/r/mcp/mcp-discord) instead."; | |
| 48 | + } | |
| 49 | + | |
| 46 | 50 | async fetchMessages( |
| 47 | 51 | channelId: string, |
| 48 | 52 | fetch: FetchFunction, |
modified core/context/providers/FileContextProvider.ts +1 −0
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | ContextSubmenuItem, |
| 7 | 7 | LoadSubmenuItemsArgs, |
| 8 | 8 | } from "../../"; |
| 9 | +import { isSecurityConcern } from "../../indexing/ignore"; | |
| 9 | 10 | import { walkDirs } from "../../indexing/walkDir"; |
| 10 | 11 | import { |
| 11 | 12 | getShortestUniqueRelativeUriPaths, |
modified core/context/providers/FolderContextProvider.ts +1 −1
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | displayTitle: "Folder", |
| 20 | 20 | description: "Type to search", |
| 21 | 21 | type: "submenu", |
| 22 | - dependsOnIndexing: true, | |
| 22 | + dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"], | |
| 23 | 23 | }; |
| 24 | 24 | |
| 25 | 25 | async getContextItems( |
modified core/context/providers/GitCommitContextProvider.ts +4 −0
| @@ -44,6 +44,10 @@ | ||
| 44 | 44 | type: "submenu", |
| 45 | 45 | }; |
| 46 | 46 | |
| 47 | + get deprecationMessage() { | |
| 48 | + return "The git commits context provider is now deprecated and may be removed in a later version. Please consider using the Git MCP (https://hub.continue.dev/docker/mcp-git) instead."; | |
| 49 | + } | |
| 50 | + | |
| 47 | 51 | async getContextItems( |
| 48 | 52 | query: string, |
| 49 | 53 | extras: ContextProviderExtras, |
modified core/context/providers/GitHubIssuesContextProvider.ts +4 −0
| @@ -15,6 +15,10 @@ | ||
| 15 | 15 | type: "submenu", |
| 16 | 16 | }; |
| 17 | 17 | |
| 18 | + get deprecationMessage() { | |
| 19 | + return "The GitHub issues context provider is now deprecated and will be removed in a later version. Please consider using the GitHub MCP server (https://hub.continue.dev/anthropic/github-mcp) instead."; | |
| 20 | + } | |
| 21 | + | |
| 18 | 22 | async getContextItems( |
| 19 | 23 | query: string, |
| 20 | 24 | extras: ContextProviderExtras, |
modified core/context/providers/GitLabMergeRequestContextProvider.ts +4 −0
| @@ -76,6 +76,10 @@ | ||
| 76 | 76 | type: "normal", |
| 77 | 77 | }; |
| 78 | 78 | |
| 79 | + get deprecationMessage() { | |
| 80 | + return "The Gitlab Merge Request context provider is now deprecated and will be removed in a later version. Please consider using the GitLab MCP (https://hub.continue.dev/docker/mcp-gitlab) instead."; | |
| 81 | + } | |
| 82 | + | |
| 79 | 83 | private async getApi(): Promise<AxiosInstance> { |
| 80 | 84 | const { default: Axios } = await import("axios"); |
| 81 | 85 |
modified core/context/providers/GoogleContextProvider.ts +4 −0
| @@ -20,6 +20,10 @@ | ||
| 20 | 20 | this._serperApiKey = options.serperApiKey; |
| 21 | 21 | } |
| 22 | 22 | |
| 23 | + get deprecationMessage() { | |
| 24 | + return "The Google context provider is now deprecated and will be removed in a later version. Please consider using github.com/jae-jae/g-search-mcp instead."; | |
| 25 | + } | |
| 26 | + | |
| 23 | 27 | async getContextItems( |
| 24 | 28 | query: string, |
| 25 | 29 | extras: ContextProviderExtras, |
modified core/context/providers/GreptileContextProvider.ts +4 −0
| @@ -17,6 +17,10 @@ | ||
| 17 | 17 | type: "query", |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | + get deprecationMessage() { | |
| 21 | + return "The Greptile context provider is now deprecated and will be removed in a later version. Please consider viewing their docs at greptile.com/docs/code-review-bot/auto-resolve-with-mcp for resolving greptile queries."; | |
| 22 | + } | |
| 23 | + | |
| 20 | 24 | async getContextItems( |
| 21 | 25 | query: string, |
| 22 | 26 | extras: ContextProviderExtras, |
modified core/context/providers/JiraIssuesContextProvider/index.ts +4 −0
| @@ -17,6 +17,10 @@ | ||
| 17 | 17 | type: "submenu", |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | + get deprecationMessage() { | |
| 21 | + return "The Jira issues context provider is now deprecated and will be removed in a later version. Please consider using the official Atlassian MCP server atlassian.com/platform/remote-mcp-server."; | |
| 22 | + } | |
| 23 | + | |
| 20 | 24 | private getApi() { |
| 21 | 25 | return new JiraClient({ |
| 22 | 26 | domain: this.options.domain, |
modified core/context/providers/OpenFilesContextProvider.ts +15 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ContextProviderDescription, |
| 4 | 4 | ContextProviderExtras, |
| 5 | 5 | } from "../../index.js"; |
| 6 | +import { isSecurityConcern } from "../../indexing/ignore.js"; | |
| 6 | 7 | import { getUriDescription } from "../../util/uri.js"; |
| 7 | 8 | import { BaseContextProvider } from "../index.js"; |
| 8 | 9 | |
| @@ -27,10 +28,23 @@ | ||
| 27 | 28 | |
| 28 | 29 | return await Promise.all( |
| 29 | 30 | openFiles.map(async (filepath: string) => { |
| 30 | - const content = await ide.readFile(filepath); | |
| 31 | 31 | const { relativePathOrBasename, last2Parts, baseName } = |
| 32 | 32 | getUriDescription(filepath, workspaceDirs); |
| 33 | 33 | |
| 34 | + if (isSecurityConcern(filepath)) { | |
| 35 | + return { | |
| 36 | + description: last2Parts, | |
| 37 | + content: | |
| 38 | + "Content redacted, this file cannot be viewed for security reasons", | |
| 39 | + name: baseName, | |
| 40 | + uri: { | |
| 41 | + type: "file", | |
| 42 | + value: filepath, | |
| 43 | + }, | |
| 44 | + }; | |
| 45 | + } | |
| 46 | + const content = await ide.readFile(filepath); | |
| 47 | + | |
| 34 | 48 | return { |
| 35 | 49 | description: last2Parts, |
| 36 | 50 | content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, |
modified core/context/providers/ProblemsContextProvider.ts +2 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ContextProviderDescription, |
| 4 | 4 | ContextProviderExtras, |
| 5 | 5 | } from "../../index.js"; |
| 6 | +import { isSecurityConcern } from "../../indexing/ignore.js"; | |
| 6 | 7 | import { getUriDescription } from "../../util/uri.js"; |
| 7 | 8 | import { BaseContextProvider } from "../index.js"; |
| 8 | 9 | |
| @@ -40,7 +41,7 @@ | ||
| 40 | 41 | return { |
| 41 | 42 | description: "Problems in current file", |
| 42 | 43 | content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, |
| 43 | - name: `Warning in ${baseName}`, | |
| 44 | + name: `Warnings in ${baseName}`, | |
| 44 | 45 | }; |
| 45 | 46 | }), |
| 46 | 47 | ); |
modified core/context/providers/_context-providers.vitest.ts +0 −2
| @@ -28,11 +28,9 @@ | ||
| 28 | 28 | ): Promise<ContextProviderExtras> { |
| 29 | 29 | setUpTestDir(); |
| 30 | 30 | const ide = new FileSystemIde(TEST_DIR); |
| 31 | - const ideSettingsPromise = ide.getIdeSettings(); | |
| 32 | 31 | const llmLogger = new LLMLogger(); |
| 33 | 32 | const configHandler = new ConfigHandler( |
| 34 | 33 | ide, |
| 35 | - ideSettingsPromise, | |
| 36 | 34 | llmLogger, |
| 37 | 35 | Promise.resolve(undefined), |
| 38 | 36 | ); |
modified core/context/providers/index.ts +2 −6
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import { BaseContextProvider } from "../"; |
| 2 | 2 | import { ContextProviderName } from "../../"; |
| 3 | -import { Telemetry } from "../../util/posthog"; | |
| 4 | 3 | |
| 5 | 4 | import ClipboardContextProvider from "./ClipboardContextProvider"; |
| 6 | 5 | import CodebaseContextProvider from "./CodebaseContextProvider"; |
| @@ -12,6 +11,7 @@ | ||
| 12 | 11 | import DiffContextProvider from "./DiffContextProvider"; |
| 13 | 12 | import DiscordContextProvider from "./DiscordContextProvider"; |
| 14 | 13 | import DocsContextProvider from "./DocsContextProvider"; |
| 14 | +import FileContextProvider from "./FileContextProvider"; | |
| 15 | 15 | import FileTreeContextProvider from "./FileTreeContextProvider"; |
| 16 | 16 | import FolderContextProvider from "./FolderContextProvider"; |
| 17 | 17 | import GitCommitContextProvider from "./GitCommitContextProvider"; |
| @@ -41,6 +41,7 @@ | ||
| 41 | 41 | * See this issue for details: https://github.com/continuedev/continue/issues/1365 |
| 42 | 42 | */ |
| 43 | 43 | export const Providers: (typeof BaseContextProvider)[] = [ |
| 44 | + FileContextProvider, | |
| 44 | 45 | DiffContextProvider, |
| 45 | 46 | FileTreeContextProvider, |
| 46 | 47 | GitHubIssuesContextProvider, |
| @@ -78,10 +79,5 @@ | ||
| 78 | 79 | ): typeof BaseContextProvider | undefined { |
| 79 | 80 | const provider = Providers.find((cls) => cls.description.title === name); |
| 80 | 81 | |
| 81 | - void Telemetry.capture("context_provider_load", { | |
| 82 | - providerName: name, | |
| 83 | - found: !!provider, // also capture those which user expected to be present | |
| 84 | - }); | |
| 85 | - | |
| 86 | 82 | return provider; |
| 87 | 83 | } |
modified core/context/retrieval/retrieval.ts +1 −1
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | const nFinal = |
| 38 | 38 | options?.nFinal ?? |
| 39 | 39 | Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2); |
| 40 | - const useReranking = !!extras.reranker; | |
| 40 | + const useReranking = options?.useReranking ?? !!extras.reranker; | |
| 41 | 41 | const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal; |
| 42 | 42 | |
| 43 | 43 | const branches = (await Promise.race([ |
modified core/control-plane/client.ts +142 −6
| @@ -11,10 +11,19 @@ | ||
| 11 | 11 | import fetch, { RequestInit, Response } from "node-fetch"; |
| 12 | 12 | |
| 13 | 13 | import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; |
| 14 | -import { IdeInfo, IdeSettings, ModelDescription } from "../index.js"; | |
| 14 | +import { | |
| 15 | + IDE, | |
| 16 | + ModelDescription, | |
| 17 | + Session, | |
| 18 | + BaseSessionMetadata, | |
| 19 | +} from "../index.js"; | |
| 15 | 20 | import { Logger } from "../util/Logger.js"; |
| 16 | 21 | |
| 17 | -import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js"; | |
| 22 | +import { | |
| 23 | + ControlPlaneSessionInfo, | |
| 24 | + HubSessionInfo, | |
| 25 | + isOnPremSession, | |
| 26 | +} from "./AuthTypes.js"; | |
| 18 | 27 | import { getControlPlaneEnv } from "./env.js"; |
| 19 | 28 | |
| 20 | 29 | export interface PolicyResponse { |
| @@ -41,11 +50,15 @@ | ||
| 41 | 50 | export const TRIAL_PROXY_URL = |
| 42 | 51 | "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; |
| 43 | 52 | |
| 53 | +export interface RemoteSessionMetadata extends BaseSessionMetadata { | |
| 54 | + isRemote: true; | |
| 55 | + remoteId: string; | |
| 56 | +} | |
| 57 | + | |
| 44 | 58 | export class ControlPlaneClient { |
| 45 | 59 | constructor( |
| 46 | 60 | readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, |
| 47 | - private readonly ideSettingsPromise: Promise<IdeSettings>, | |
| 48 | - private readonly ideInfoPromise: Promise<IdeInfo>, | |
| 61 | + private readonly ide: IDE, | |
| 49 | 62 | ) {} |
| 50 | 63 | |
| 51 | 64 | async resolveFQSNs( |
| @@ -90,9 +103,9 @@ | ||
| 90 | 103 | throw new Error("No access token"); |
| 91 | 104 | } |
| 92 | 105 | |
| 93 | - const env = await getControlPlaneEnv(this.ideSettingsPromise); | |
| 106 | + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); | |
| 94 | 107 | const url = new URL(path, env.CONTROL_PLANE_URL).toString(); |
| 95 | - const ideInfo = await this.ideInfoPromise; | |
| 108 | + const ideInfo = await this.ide.getIdeInfo(); | |
| 96 | 109 | |
| 97 | 110 | const resp = await fetch(url, { |
| 98 | 111 | ...init, |
| @@ -304,4 +317,127 @@ | ||
| 304 | 317 | return null; |
| 305 | 318 | } |
| 306 | 319 | } |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Check if remote sessions should be enabled based on feature flags | |
| 323 | + * Requires: PostHog feature flag AND @continue.dev email | |
| 324 | + */ | |
| 325 | + public async shouldEnableRemoteSessions(): Promise<boolean> { | |
| 326 | + // Check if user is signed in | |
| 327 | + if (!(await this.isSignedIn())) { | |
| 328 | + return false; | |
| 329 | + } | |
| 330 | + | |
| 331 | + // Check if user has @continue.dev email | |
| 332 | + try { | |
| 333 | + const sessionInfo = await this.sessionInfoPromise; | |
| 334 | + if (isOnPremSession(sessionInfo) || !sessionInfo) { | |
| 335 | + return false; | |
| 336 | + } | |
| 337 | + | |
| 338 | + const hubSession = sessionInfo as HubSessionInfo; | |
| 339 | + const email = hubSession.account?.id; | |
| 340 | + | |
| 341 | + return email ? email.includes("@continue.dev") : false; | |
| 342 | + } catch (e) { | |
| 343 | + Logger.error(e, { | |
| 344 | + context: "control_plane_check_remote_sessions_enabled", | |
| 345 | + }); | |
| 346 | + return false; | |
| 347 | + } | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Get current user's session info | |
| 352 | + */ | |
| 353 | + public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> { | |
| 354 | + return await this.sessionInfoPromise; | |
| 355 | + } | |
| 356 | + | |
| 357 | + /** | |
| 358 | + * Fetch remote agents/sessions from the control plane | |
| 359 | + * Currently restricted to @continue.dev emails for internal use | |
| 360 | + */ | |
| 361 | + public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> { | |
| 362 | + if (!(await this.isSignedIn())) { | |
| 363 | + return []; | |
| 364 | + } | |
| 365 | + | |
| 366 | + try { | |
| 367 | + // Note: This endpoint is currently restricted to internal @continue.dev users | |
| 368 | + // In the future, this may be expanded to support broader remote session access | |
| 369 | + const resp = await this.requestAndHandleError("agents/devboxes", { | |
| 370 | + method: "GET", | |
| 371 | + }); | |
| 372 | + | |
| 373 | + const agents = (await resp.json()) as any[]; | |
| 374 | + | |
| 375 | + return agents.map( | |
| 376 | + (agent: any): RemoteSessionMetadata => ({ | |
| 377 | + sessionId: `remote-${agent.id}`, | |
| 378 | + title: agent.name || "Remote Agent", | |
| 379 | + dateCreated: new Date(agent.create_time_ms).toISOString(), | |
| 380 | + workspaceDirectory: "", | |
| 381 | + isRemote: true, | |
| 382 | + remoteId: agent.id, | |
| 383 | + }), | |
| 384 | + ); | |
| 385 | + } catch (e) { | |
| 386 | + // Log error but don't throw - remote sessions are optional | |
| 387 | + Logger.error(e, { | |
| 388 | + context: "control_plane_list_remote_sessions", | |
| 389 | + }); | |
| 390 | + return []; | |
| 391 | + } | |
| 392 | + } | |
| 393 | + | |
| 394 | + public async loadRemoteSession(remoteId: string): Promise<Session> { | |
| 395 | + if (!(await this.isSignedIn())) { | |
| 396 | + throw new Error("Not signed in to load remote session"); | |
| 397 | + } | |
| 398 | + | |
| 399 | + try { | |
| 400 | + // First get the tunnel URL for the remote agent | |
| 401 | + const tunnelResp = await this.requestAndHandleError( | |
| 402 | + `agents/devboxes/${remoteId}/tunnel`, | |
| 403 | + { | |
| 404 | + method: "POST", | |
| 405 | + }, | |
| 406 | + ); | |
| 407 | + | |
| 408 | + const tunnelData = (await tunnelResp.json()) as { url?: string }; | |
| 409 | + const tunnelUrl = tunnelData.url; | |
| 410 | + | |
| 411 | + if (!tunnelUrl) { | |
| 412 | + throw new Error(`Failed to get tunnel URL for agent ${remoteId}`); | |
| 413 | + } | |
| 414 | + | |
| 415 | + // Now fetch the session state from the remote agent's /state endpoint | |
| 416 | + const stateResponse = await fetch(`${tunnelUrl}/state`); | |
| 417 | + if (!stateResponse.ok) { | |
| 418 | + throw new Error( | |
| 419 | + `Failed to fetch state from remote agent: ${stateResponse.statusText}`, | |
| 420 | + ); | |
| 421 | + } | |
| 422 | + | |
| 423 | + const remoteState = (await stateResponse.json()) as { session?: Session }; | |
| 424 | + | |
| 425 | + // The remote state contains a session property with the full session data | |
| 426 | + if (!remoteState.session) { | |
| 427 | + throw new Error( | |
| 428 | + "Remote agent returned invalid state - no session found", | |
| 429 | + ); | |
| 430 | + } | |
| 431 | + | |
| 432 | + return remoteState.session; | |
| 433 | + } catch (e) { | |
| 434 | + Logger.error(e, { | |
| 435 | + context: "control_plane_load_remote_session", | |
| 436 | + remoteId, | |
| 437 | + }); | |
| 438 | + throw new Error( | |
| 439 | + `Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`, | |
| 440 | + ); | |
| 441 | + } | |
| 442 | + } | |
| 307 | 443 | } |
modified core/core.ts +118 −35
| @@ -10,7 +10,6 @@ | ||
| 10 | 10 | import { ConfigHandler } from "./config/ConfigHandler"; |
| 11 | 11 | import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; |
| 12 | 12 | import { addModel, deleteModel } from "./config/util"; |
| 13 | -import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; | |
| 14 | 13 | import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; |
| 15 | 14 | import { getControlPlaneEnv } from "./control-plane/env"; |
| 16 | 15 | import { DevDataSqliteDb } from "./data/devdataSqlite"; |
| @@ -18,6 +17,7 @@ | ||
| 18 | 17 | import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; |
| 19 | 18 | import DocsService from "./indexing/docs/DocsService"; |
| 20 | 19 | import { countTokens } from "./llm/countTokens"; |
| 20 | +import Lemonade from "./llm/llms/Lemonade"; | |
| 21 | 21 | import Ollama from "./llm/llms/Ollama"; |
| 22 | 22 | import { EditAggregator } from "./nextEdit/context/aggregateEdits"; |
| 23 | 23 | import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; |
| @@ -30,8 +30,9 @@ | ||
| 30 | 30 | import { Telemetry } from "./util/posthog"; |
| 31 | 31 | import { |
| 32 | 32 | isProcessBackgrounded, |
| 33 | + killTerminalProcess, | |
| 33 | 34 | markProcessAsBackgrounded, |
| 34 | -} from "./util/processTerminalBackgroundStates"; | |
| 35 | +} from "./util/processTerminalStates"; | |
| 35 | 36 | import { getSymbolsForManyFiles } from "./util/treeSitter"; |
| 36 | 37 | import { TTS } from "./util/tts"; |
| 37 | 38 | |
| @@ -51,6 +52,7 @@ | ||
| 51 | 52 | import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; |
| 52 | 53 | import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; |
| 53 | 54 | import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand"; |
| 55 | +import { createNewAssistantFile } from "./config/createNewAssistantFile"; | |
| 54 | 56 | import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; |
| 55 | 57 | import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules"; |
| 56 | 58 | import { |
| @@ -139,7 +141,7 @@ | ||
| 139 | 141 | |
| 140 | 142 | const ideInfoPromise = messenger.request("getIdeInfo", undefined); |
| 141 | 143 | const ideSettingsPromise = messenger.request("getIdeSettings", undefined); |
| 142 | - const sessionInfoPromise = messenger.request( | |
| 144 | + const initialSessionInfoPromise = messenger.request( | |
| 143 | 145 | "getControlPlaneSessionInfo", |
| 144 | 146 | { |
| 145 | 147 | silent: true, |
| @@ -149,9 +151,8 @@ | ||
| 149 | 151 | |
| 150 | 152 | this.configHandler = new ConfigHandler( |
| 151 | 153 | this.ide, |
| 152 | - ideSettingsPromise, | |
| 153 | 154 | this.llmLogger, |
| 154 | - sessionInfoPromise, | |
| 155 | + initialSessionInfoPromise, | |
| 155 | 156 | ); |
| 156 | 157 | |
| 157 | 158 | this.docsService = DocsService.createSingleton( |
| @@ -176,6 +177,13 @@ | ||
| 176 | 177 | } |
| 177 | 178 | }; |
| 178 | 179 | |
| 180 | + this.codeBaseIndexer = new CodebaseIndexer( | |
| 181 | + this.configHandler, | |
| 182 | + this.ide, | |
| 183 | + this.messenger, | |
| 184 | + this.globalContext.get("indexingPaused"), | |
| 185 | + ); | |
| 186 | + | |
| 179 | 187 | this.configHandler.onConfigUpdate((result) => { |
| 180 | 188 | void (async () => { |
| 181 | 189 | const serializedResult = |
| @@ -188,6 +196,12 @@ | ||
| 188 | 196 | selectedOrgId: this.configHandler.currentOrg?.id ?? null, |
| 189 | 197 | }); |
| 190 | 198 | |
| 199 | + if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) { | |
| 200 | + await this.codeBaseIndexer.refreshCodebaseIndex( | |
| 201 | + await this.ide.getWorkspaceDirs(), | |
| 202 | + ); | |
| 203 | + } | |
| 204 | + | |
| 191 | 205 | // update additional submenu context providers registered via VSCode API |
| 192 | 206 | const additionalProviders = |
| 193 | 207 | this.configHandler.getAdditionalSubmenuContextProviders(); |
| @@ -199,13 +213,6 @@ | ||
| 199 | 213 | })(); |
| 200 | 214 | }); |
| 201 | 215 | |
| 202 | - this.codeBaseIndexer = new CodebaseIndexer( | |
| 203 | - this.configHandler, | |
| 204 | - this.ide, | |
| 205 | - this.messenger, | |
| 206 | - this.globalContext.get("indexingPaused"), | |
| 207 | - ); | |
| 208 | - | |
| 209 | 216 | // Dev Data Logger |
| 210 | 217 | const dataLogger = DataLogger.getInstance(); |
| 211 | 218 | dataLogger.core = this; |
| @@ -226,6 +233,17 @@ | ||
| 226 | 233 | return; |
| 227 | 234 | } |
| 228 | 235 | |
| 236 | + // Check for disableIndexing to prevent race condition | |
| 237 | + const { config } = await this.configHandler.loadConfig(); | |
| 238 | + if (!config || config.disableIndexing) { | |
| 239 | + void this.messenger.request("indexProgress", { | |
| 240 | + progress: 0, | |
| 241 | + desc: "Indexing is disabled", | |
| 242 | + status: "disabled", | |
| 243 | + }); | |
| 244 | + return; | |
| 245 | + } | |
| 246 | + | |
| 229 | 247 | void this.codeBaseIndexer.refreshCodebaseIndex(dirs); |
| 230 | 248 | }); |
| 231 | 249 | }); |
| @@ -308,8 +326,27 @@ | ||
| 308 | 326 | }); |
| 309 | 327 | |
| 310 | 328 | // History |
| 311 | - on("history/list", (msg) => { | |
| 312 | - return historyManager.list(msg.data); | |
| 329 | + on("history/list", async (msg) => { | |
| 330 | + const localSessions = historyManager.list(msg.data); | |
| 331 | + | |
| 332 | + // Check if remote sessions should be enabled based on feature flags | |
| 333 | + const shouldFetchRemote = | |
| 334 | + await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions(); | |
| 335 | + | |
| 336 | + // Get remote sessions from control plane if feature is enabled | |
| 337 | + const remoteSessions = shouldFetchRemote | |
| 338 | + ? await this.configHandler.controlPlaneClient.listRemoteSessions() | |
| 339 | + : []; | |
| 340 | + | |
| 341 | + // Combine and sort by date (most recent first) | |
| 342 | + const allSessions = [...localSessions, ...remoteSessions].sort( | |
| 343 | + (a, b) => | |
| 344 | + new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(), | |
| 345 | + ); | |
| 346 | + | |
| 347 | + // Apply limit if specified | |
| 348 | + const limit = msg.data?.limit ?? 100; | |
| 349 | + return allSessions.slice(0, limit); | |
| 313 | 350 | }); |
| 314 | 351 | |
| 315 | 352 | on("history/delete", (msg) => { |
| @@ -320,6 +357,12 @@ | ||
| 320 | 357 | return historyManager.load(msg.data.id); |
| 321 | 358 | }); |
| 322 | 359 | |
| 360 | + on("history/loadRemote", async (msg) => { | |
| 361 | + return this.configHandler.controlPlaneClient.loadRemoteSession( | |
| 362 | + msg.data.remoteId, | |
| 363 | + ); | |
| 364 | + }); | |
| 365 | + | |
| 323 | 366 | on("history/save", (msg) => { |
| 324 | 367 | historyManager.save(msg.data); |
| 325 | 368 | }); |
| @@ -362,6 +405,13 @@ | ||
| 362 | 405 | ); |
| 363 | 406 | }); |
| 364 | 407 | |
| 408 | + on("config/newAssistantFile", async (msg) => { | |
| 409 | + await createNewAssistantFile(this.ide, undefined); | |
| 410 | + await this.configHandler.reloadConfig( | |
| 411 | + "Assistant file created (config/newAssistantFile message)", | |
| 412 | + ); | |
| 413 | + }); | |
| 414 | + | |
| 365 | 415 | on("config/addLocalWorkspaceBlock", async (msg) => { |
| 366 | 416 | await createNewWorkspaceBlockFile(this.ide, msg.data.blockType); |
| 367 | 417 | await this.configHandler.reloadConfig( |
| @@ -669,6 +719,8 @@ | ||
| 669 | 719 | return queue.dequeueProcessed() || null; |
| 670 | 720 | }); |
| 671 | 721 | |
| 722 | + // NOTE: This is not used unless prefetch is used. | |
| 723 | + // At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching. | |
| 672 | 724 | on("nextEdit/queue/processOne", async (msg) => { |
| 673 | 725 | console.log("nextEdit/queue/processOne"); |
| 674 | 726 | const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data; |
| @@ -721,20 +773,13 @@ | ||
| 721 | 773 | data.fileUri ?? "current-file-stream", |
| 722 | 774 | ); // not super important since currently cancelling apply will cancel all streams it's one file at a time |
| 723 | 775 | |
| 724 | - return streamDiffLines({ | |
| 725 | - highlighted: data.highlighted, | |
| 726 | - prefix: data.prefix, | |
| 727 | - suffix: data.suffix, | |
| 776 | + return streamDiffLines( | |
| 777 | + data, | |
| 728 | 778 | llm, |
| 729 | - // rules included for edit, NOT apply | |
| 730 | - rulesToInclude: data.includeRulesInSystemMessage | |
| 731 | - ? config.rules | |
| 732 | - : undefined, | |
| 733 | - input: data.input, | |
| 734 | - language: data.language, | |
| 735 | - overridePrompt: undefined, | |
| 736 | 779 | abortController, |
| 737 | - }); | |
| 780 | + undefined, | |
| 781 | + data.includeRulesInSystemMessage ? config.rules : undefined, | |
| 782 | + ); | |
| 738 | 783 | }); |
| 739 | 784 | |
| 740 | 785 | on("cancelApply", async (msg) => { |
| @@ -967,6 +1012,10 @@ | ||
| 967 | 1012 | on("docs/getDetails", async (msg) => { |
| 968 | 1013 | return await this.docsService.getDetails(msg.data.startUrl); |
| 969 | 1014 | }); |
| 1015 | + on("docs/getIndexedPages", async (msg) => { | |
| 1016 | + const pages = await this.docsService.getIndexedPages(msg.data.startUrl); | |
| 1017 | + return Array.from(pages); | |
| 1018 | + }); | |
| 970 | 1019 | |
| 971 | 1020 | on("didChangeSelectedProfile", async (msg) => { |
| 972 | 1021 | if (msg.data.id) { |
| @@ -1004,6 +1053,37 @@ | ||
| 1004 | 1053 | this.handleToolCall(toolCall), |
| 1005 | 1054 | ); |
| 1006 | 1055 | |
| 1056 | + on( | |
| 1057 | + "tools/evaluatePolicy", | |
| 1058 | + async ({ data: { toolName, basePolicy, args } }) => { | |
| 1059 | + const { config } = await this.configHandler.loadConfig(); | |
| 1060 | + if (!config) { | |
| 1061 | + throw new Error("Config not loaded"); | |
| 1062 | + } | |
| 1063 | + | |
| 1064 | + const tool = config.tools.find((t) => t.function.name === toolName); | |
| 1065 | + if (!tool) { | |
| 1066 | + // Tool not found, return base policy | |
| 1067 | + return { policy: basePolicy }; | |
| 1068 | + } | |
| 1069 | + | |
| 1070 | + // Extract display value for specific tools | |
| 1071 | + let displayValue: string | undefined; | |
| 1072 | + if (toolName === "runTerminalCommand" && args.command) { | |
| 1073 | + displayValue = args.command as string; | |
| 1074 | + } | |
| 1075 | + | |
| 1076 | + // If tool has evaluateToolCallPolicy function, use it | |
| 1077 | + if (tool.evaluateToolCallPolicy) { | |
| 1078 | + const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); | |
| 1079 | + return { policy: evaluatedPolicy, displayValue }; | |
| 1080 | + } | |
| 1081 | + | |
| 1082 | + // Otherwise return base policy unchanged | |
| 1083 | + return { policy: basePolicy, displayValue }; | |
| 1084 | + }, | |
| 1085 | + ); | |
| 1086 | + | |
| 1007 | 1087 | on("isItemTooBig", async ({ data: { item } }) => { |
| 1008 | 1088 | return this.isItemTooBig(item); |
| 1009 | 1089 | }); |
| @@ -1021,6 +1101,10 @@ | ||
| 1021 | 1101 | }, |
| 1022 | 1102 | ); |
| 1023 | 1103 | |
| 1104 | + on("process/killTerminalProcess", async ({ data: { toolCallId } }) => { | |
| 1105 | + await killTerminalProcess(toolCallId); | |
| 1106 | + }); | |
| 1107 | + | |
| 1024 | 1108 | on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { |
| 1025 | 1109 | const isValid = setMdmLicenseKey(licenseKey); |
| 1026 | 1110 | return isValid; |
| @@ -1217,6 +1301,9 @@ | ||
| 1217 | 1301 | if (msg.data.title === "Ollama") { |
| 1218 | 1302 | const models = await new Ollama({ model: "" }).listModels(); |
| 1219 | 1303 | return models; |
| 1304 | + } else if (msg.data.title === "Lemonade") { | |
| 1305 | + const models = await new Lemonade({ model: "" }).listModels(); | |
| 1306 | + return models; | |
| 1220 | 1307 | } else { |
| 1221 | 1308 | return undefined; |
| 1222 | 1309 | } |
| @@ -1281,15 +1368,9 @@ | ||
| 1281 | 1368 | throw new Error("No chat model selected"); |
| 1282 | 1369 | } |
| 1283 | 1370 | |
| 1284 | - const provider = | |
| 1285 | - config.contextProviders?.find( | |
| 1286 | - (provider) => provider.description.title === name, | |
| 1287 | - ) ?? | |
| 1288 | - [ | |
| 1289 | - // user doesn't need these in their config.json for the shortcuts to work | |
| 1290 | - // option+enter | |
| 1291 | - new CurrentFileContextProvider({}), | |
| 1292 | - ].find((provider) => provider.description.title === name); | |
| 1371 | + const provider = config.contextProviders?.find( | |
| 1372 | + (provider) => provider.description.title === name, | |
| 1373 | + ); | |
| 1293 | 1374 | if (!provider) { |
| 1294 | 1375 | return []; |
| 1295 | 1376 | } |
| @@ -1308,6 +1389,8 @@ | ||
| 1308 | 1389 | selectedCode, |
| 1309 | 1390 | reranker: config.selectedModelByRole.rerank, |
| 1310 | 1391 | fetch: (url, init) => |
| 1392 | + // Important note: context providers fetch uses global request options not LLM request options | |
| 1393 | + // Because LLM calls are handled separately | |
| 1311 | 1394 | fetchwithRequestOptions(url, init, config.requestOptions), |
| 1312 | 1395 | isInAgentMode: msg.data.isInAgentMode, |
| 1313 | 1396 | }); |
modified core/edit/constants.ts +2 −0
| @@ -1,1 +1,3 @@ | ||
| 1 | 1 | export const EDIT_MODE_STREAM_ID = "edit-mode"; |
| 2 | + | |
| 3 | +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; |
modified core/edit/recursiveStream.ts +51 −4
| @@ -1,14 +1,20 @@ | ||
| 1 | -import { ChatMessage, ILLM, Prediction, PromptLog } from ".."; | |
| 1 | +import { | |
| 2 | + ChatMessage, | |
| 3 | + ILLM, | |
| 4 | + Prediction, | |
| 5 | + PromptLog, | |
| 6 | + type StreamDiffLinesType, | |
| 7 | +} from ".."; | |
| 2 | 8 | import { DEFAULT_MAX_TOKENS } from "../llm/constants"; |
| 3 | 9 | import { countTokens } from "../llm/countTokens"; |
| 4 | 10 | import { renderChatMessage } from "../util/messageContent"; |
| 11 | +import { APPLY_UNIQUE_TOKEN } from "./constants.js"; | |
| 5 | 12 | |
| 6 | 13 | const INFINITE_STREAM_SAFETY = 0.9; |
| 7 | 14 | |
| 8 | 15 | const DUD_PROMPT_LOG: PromptLog = { |
| 9 | 16 | modelTitle: "", |
| 10 | 17 | modelProvider: "", |
| 11 | - completionOptions: { model: "" }, | |
| 12 | 18 | prompt: "", |
| 13 | 19 | completion: "", |
| 14 | 20 | }; |
| @@ -18,6 +24,7 @@ | ||
| 18 | 24 | export async function* recursiveStream( |
| 19 | 25 | llm: ILLM, |
| 20 | 26 | abortController: AbortController, |
| 27 | + type: StreamDiffLinesType, | |
| 21 | 28 | prompt: ChatMessage[] | string, |
| 22 | 29 | prediction: Prediction | undefined, |
| 23 | 30 | currentBuffer = "", |
| @@ -29,8 +36,11 @@ | ||
| 29 | 36 | let buffer = currentBuffer; |
| 30 | 37 | // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries |
| 31 | 38 | |
| 39 | + const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm); | |
| 32 | 40 | if (typeof prompt === "string") { |
| 33 | - const generator = llm.streamComplete(prompt, abortController.signal, { | |
| 41 | + const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt; | |
| 42 | + | |
| 43 | + const generator = llm.streamComplete(finalPrompt, abortController.signal, { | |
| 34 | 44 | raw: true, |
| 35 | 45 | prediction: undefined, |
| 36 | 46 | reasoning: false, |
| @@ -63,7 +73,11 @@ | ||
| 63 | 73 | } |
| 64 | 74 | } |
| 65 | 75 | } else { |
| 66 | - const generator = llm.streamChat(prompt, abortController.signal, { | |
| 76 | + const promptMessages = injectApplyToken | |
| 77 | + ? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN) | |
| 78 | + : prompt; | |
| 79 | + | |
| 80 | + const generator = llm.streamChat(promptMessages, abortController.signal, { | |
| 67 | 81 | raw: true, |
| 68 | 82 | prediction: undefined, |
| 69 | 83 | reasoning: false, |
| @@ -105,3 +119,36 @@ | ||
| 105 | 119 | } |
| 106 | 120 | } |
| 107 | 121 | } |
| 122 | + | |
| 123 | +function shouldInjectApplyToken(llm: ILLM): boolean { | |
| 124 | + const model = llm.model?.toLowerCase() ?? ""; | |
| 125 | + return ( | |
| 126 | + llm.underlyingProviderName === "inception" && model.includes("mercury") | |
| 127 | + ); | |
| 128 | +} | |
| 129 | + | |
| 130 | +function appendTokenToLastMessage( | |
| 131 | + messages: ChatMessage[], | |
| 132 | + token: string, | |
| 133 | +): ChatMessage[] { | |
| 134 | + if (messages.length === 0) { | |
| 135 | + return messages; | |
| 136 | + } | |
| 137 | + | |
| 138 | + const lastMessage = messages[messages.length - 1]; | |
| 139 | + if (typeof lastMessage.content !== "string") { | |
| 140 | + return messages; | |
| 141 | + } | |
| 142 | + | |
| 143 | + if (lastMessage.content.endsWith(token)) { | |
| 144 | + return messages; | |
| 145 | + } | |
| 146 | + | |
| 147 | + const updatedMessages = [...messages]; | |
| 148 | + updatedMessages[updatedMessages.length - 1] = { | |
| 149 | + ...lastMessage, | |
| 150 | + content: lastMessage.content + token, | |
| 151 | + }; | |
| 152 | + | |
| 153 | + return updatedMessages; | |
| 154 | +} |
added core/edit/searchAndReplace/executeFindAndReplace.vitest.ts +252 −0
| @@ -0,0 +1,252 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { executeFindAndReplace } from "./performReplace"; | |
| 4 | + | |
| 5 | +describe("executeFindAndReplace", () => { | |
| 6 | + describe("normal cases", () => { | |
| 7 | + it("should replace single occurrence by default", () => { | |
| 8 | + const content = "Hello world\nThis is a test file\nGoodbye"; | |
| 9 | + const result = executeFindAndReplace(content, "Hello", "Hi", false); | |
| 10 | + | |
| 11 | + expect(result).toBe("Hi world\nThis is a test file\nGoodbye"); | |
| 12 | + }); | |
| 13 | + | |
| 14 | + it("should replace single occurrence when replaceAll is false", () => { | |
| 15 | + const content = "Hello world\nHello again"; | |
| 16 | + const result = executeFindAndReplace( | |
| 17 | + content, | |
| 18 | + "Hello world", | |
| 19 | + "Hi world", | |
| 20 | + false, | |
| 21 | + ); | |
| 22 | + | |
| 23 | + expect(result).toBe("Hi world\nHello again"); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + it("should replace all occurrences when replaceAll is true", () => { | |
| 27 | + const content = "Hello world\nHello again\nHello there"; | |
| 28 | + const result = executeFindAndReplace(content, "Hello", "Hi", true); | |
| 29 | + | |
| 30 | + expect(result).toBe("Hi world\nHi again\nHi there"); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + it("should handle empty new string (deletion)", () => { | |
| 34 | + const content = "Hello world"; | |
| 35 | + const result = executeFindAndReplace(content, "Hello ", "", false); | |
| 36 | + | |
| 37 | + expect(result).toBe("world"); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should handle empty old string replacement (insertion at start)", () => { | |
| 41 | + const content = ""; | |
| 42 | + const result = executeFindAndReplace(content, "", "Hello world", false); | |
| 43 | + | |
| 44 | + expect(result).toBe("Hello world"); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should preserve whitespace and indentation", () => { | |
| 48 | + const content = | |
| 49 | + "function test() {\n const value = 'old';\n return value;\n}"; | |
| 50 | + const result = executeFindAndReplace( | |
| 51 | + content, | |
| 52 | + " const value = 'old';", | |
| 53 | + " const value = 'new';", | |
| 54 | + false, | |
| 55 | + ); | |
| 56 | + | |
| 57 | + expect(result).toBe( | |
| 58 | + "function test() {\n const value = 'new';\n return value;\n}", | |
| 59 | + ); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + it("should handle multiline strings", () => { | |
| 63 | + const content = "line1\nline2\nline3"; | |
| 64 | + const result = executeFindAndReplace( | |
| 65 | + content, | |
| 66 | + "line1\nline2", | |
| 67 | + "newline1\nnewline2", | |
| 68 | + false, | |
| 69 | + ); | |
| 70 | + | |
| 71 | + expect(result).toBe("newline1\nnewline2\nline3"); | |
| 72 | + }); | |
| 73 | + }); | |
| 74 | + | |
| 75 | + describe("special character handling", () => { | |
| 76 | + it("should handle regex special characters in old string", () => { | |
| 77 | + const content = "const regex = /[a-z]+/g;"; | |
| 78 | + const result = executeFindAndReplace( | |
| 79 | + content, | |
| 80 | + "/[a-z]+/g", | |
| 81 | + "/[A-Z]+/g", | |
| 82 | + false, | |
| 83 | + ); | |
| 84 | + | |
| 85 | + expect(result).toBe("const regex = /[A-Z]+/g;"); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + it("should handle dollar signs in strings", () => { | |
| 89 | + const content = 'const text = "Hello $world"'; | |
| 90 | + const result = executeFindAndReplace( | |
| 91 | + content, | |
| 92 | + '"Hello $world"', | |
| 93 | + '"Hi $universe"', | |
| 94 | + false, | |
| 95 | + ); | |
| 96 | + | |
| 97 | + expect(result).toBe('const text = "Hi $universe"'); | |
| 98 | + }); | |
| 99 | + | |
| 100 | + it("should handle backslashes", () => { | |
| 101 | + const content = 'const path = "C:\\Users\\test"'; | |
| 102 | + const result = executeFindAndReplace( | |
| 103 | + content, | |
| 104 | + "C:\\Users\\test", | |
| 105 | + "D:\\Users\\test", | |
| 106 | + false, | |
| 107 | + ); | |
| 108 | + | |
| 109 | + expect(result).toBe('const path = "D:\\Users\\test"'); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should handle parentheses", () => { | |
| 113 | + const content = "function test() { return 'old'; }"; | |
| 114 | + const result = executeFindAndReplace( | |
| 115 | + content, | |
| 116 | + "() { return 'old'; }", | |
| 117 | + "() { return 'new'; }", | |
| 118 | + false, | |
| 119 | + ); | |
| 120 | + | |
| 121 | + expect(result).toBe("function test() { return 'new'; }"); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + it("should handle square brackets", () => { | |
| 125 | + const content = "const arr = [1, 2, 3];"; | |
| 126 | + const result = executeFindAndReplace( | |
| 127 | + content, | |
| 128 | + "[1, 2, 3]", | |
| 129 | + "[4, 5, 6]", | |
| 130 | + false, | |
| 131 | + ); | |
| 132 | + | |
| 133 | + expect(result).toBe("const arr = [4, 5, 6];"); | |
| 134 | + }); | |
| 135 | + }); | |
| 136 | + | |
| 137 | + describe("replaceAll behavior", () => { | |
| 138 | + it("should replace all occurrences including partial matches", () => { | |
| 139 | + const content = "test testing tested test"; | |
| 140 | + const result = executeFindAndReplace(content, "test", "exam", true); | |
| 141 | + | |
| 142 | + expect(result).toBe("exam examing examed exam"); | |
| 143 | + }); | |
| 144 | + | |
| 145 | + it("should replace all occurrences with empty string", () => { | |
| 146 | + const content = "remove this remove that remove everything"; | |
| 147 | + const result = executeFindAndReplace(content, "remove ", "", true); | |
| 148 | + | |
| 149 | + expect(result).toBe("this that everything"); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("should handle overlapping patterns correctly", () => { | |
| 153 | + const content = "aaaa"; | |
| 154 | + const result = executeFindAndReplace(content, "aa", "b", true); | |
| 155 | + | |
| 156 | + expect(result).toBe("bb"); | |
| 157 | + }); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + describe("error cases", () => { | |
| 161 | + it("should throw error when string not found", () => { | |
| 162 | + const content = "Hello world"; | |
| 163 | + | |
| 164 | + expect(() => { | |
| 165 | + executeFindAndReplace(content, "xyz", "abc", false); | |
| 166 | + }).toThrowError( | |
| 167 | + expect.objectContaining({ | |
| 168 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 169 | + }), | |
| 170 | + ); | |
| 171 | + }); | |
| 172 | + | |
| 173 | + it("should throw error with edit context when string not found", () => { | |
| 174 | + const content = "Hello world"; | |
| 175 | + | |
| 176 | + expect(() => { | |
| 177 | + executeFindAndReplace(content, "xyz", "abc", false, 2); | |
| 178 | + }).toThrowError( | |
| 179 | + expect.objectContaining({ | |
| 180 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 181 | + }), | |
| 182 | + ); | |
| 183 | + }); | |
| 184 | + | |
| 185 | + it("should throw error when multiple occurrences exist and replaceAll is false", () => { | |
| 186 | + const content = "Hello world\nHello again\nHello there"; | |
| 187 | + | |
| 188 | + expect(() => { | |
| 189 | + executeFindAndReplace(content, "Hello", "Hi", false); | |
| 190 | + }).toThrowError( | |
| 191 | + expect.objectContaining({ | |
| 192 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 193 | + }), | |
| 194 | + ); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should throw error with edit context for multiple occurrences", () => { | |
| 198 | + const content = "test test test"; | |
| 199 | + | |
| 200 | + expect(() => { | |
| 201 | + executeFindAndReplace(content, "test", "exam", false, 1); | |
| 202 | + }).toThrowError( | |
| 203 | + expect.objectContaining({ | |
| 204 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 205 | + }), | |
| 206 | + ); | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + describe("edge cases", () => { | |
| 211 | + it("should handle single character replacement", () => { | |
| 212 | + const content = "a b c"; | |
| 213 | + const result = executeFindAndReplace(content, "b", "x", false); | |
| 214 | + | |
| 215 | + expect(result).toBe("a x c"); | |
| 216 | + }); | |
| 217 | + | |
| 218 | + it("should handle very long strings", () => { | |
| 219 | + const longString = "a".repeat(10000); | |
| 220 | + const content = `start${longString}end`; | |
| 221 | + const result = executeFindAndReplace(content, longString, "short", false); | |
| 222 | + | |
| 223 | + expect(result).toBe("startshortend"); | |
| 224 | + }); | |
| 225 | + | |
| 226 | + it("should handle strings at beginning of content", () => { | |
| 227 | + const content = "start middle end"; | |
| 228 | + const result = executeFindAndReplace(content, "start", "begin", false); | |
| 229 | + | |
| 230 | + expect(result).toBe("begin middle end"); | |
| 231 | + }); | |
| 232 | + | |
| 233 | + it("should handle strings at end of content", () => { | |
| 234 | + const content = "start middle end"; | |
| 235 | + const result = executeFindAndReplace(content, "end", "finish", false); | |
| 236 | + | |
| 237 | + expect(result).toBe("start middle finish"); | |
| 238 | + }); | |
| 239 | + | |
| 240 | + it("should handle entire content replacement", () => { | |
| 241 | + const content = "replace everything"; | |
| 242 | + const result = executeFindAndReplace( | |
| 243 | + content, | |
| 244 | + "replace everything", | |
| 245 | + "new content", | |
| 246 | + false, | |
| 247 | + ); | |
| 248 | + | |
| 249 | + expect(result).toBe("new content"); | |
| 250 | + }); | |
| 251 | + }); | |
| 252 | +}); |
added core/edit/searchAndReplace/findAndReplaceUtils.ts +53 −0
| @@ -0,0 +1,53 @@ | ||
| 1 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 2 | + | |
| 3 | +export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = | |
| 4 | + "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * Validates a single edit operation | |
| 8 | + */ | |
| 9 | +export function validateSingleEdit( | |
| 10 | + oldString: string, | |
| 11 | + newString: string, | |
| 12 | + index?: number, | |
| 13 | +): void { | |
| 14 | + const context = index !== undefined ? `edit at index ${index}: ` : ""; | |
| 15 | + | |
| 16 | + if (!oldString && oldString !== "") { | |
| 17 | + throw new ContinueError( | |
| 18 | + ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 19 | + `${context}old_string is required`, | |
| 20 | + ); | |
| 21 | + } | |
| 22 | + if (newString === undefined) { | |
| 23 | + throw new ContinueError( | |
| 24 | + ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 25 | + `${context}new_string is required`, | |
| 26 | + ); | |
| 27 | + } | |
| 28 | + if (oldString === newString) { | |
| 29 | + throw new ContinueError( | |
| 30 | + ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 31 | + `${context}old_string and new_string must be different`, | |
| 32 | + ); | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +export function trimEmptyLines({ | |
| 37 | + lines, | |
| 38 | + fromEnd, | |
| 39 | +}: { | |
| 40 | + lines: string[]; | |
| 41 | + fromEnd: boolean; | |
| 42 | +}): string[] { | |
| 43 | + lines = fromEnd ? lines.slice().reverse() : lines.slice(); | |
| 44 | + const newLines: string[] = []; | |
| 45 | + let shouldContinueRemoving = true; | |
| 46 | + for (let index = 0; index < lines.length; index++) { | |
| 47 | + const line = lines[index]; | |
| 48 | + if (shouldContinueRemoving && line.trim() === "") continue; | |
| 49 | + shouldContinueRemoving = false; | |
| 50 | + newLines.push(line); | |
| 51 | + } | |
| 52 | + return fromEnd ? newLines.reverse() : newLines; | |
| 53 | +} |
added core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts +151 −0
| @@ -0,0 +1,151 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils"; | |
| 4 | + | |
| 5 | +describe("validateSingleEdit", () => { | |
| 6 | + describe("valid inputs", () => { | |
| 7 | + it("should not throw for valid non-empty strings", () => { | |
| 8 | + expect(() => { | |
| 9 | + validateSingleEdit("old", "new"); | |
| 10 | + }).not.toThrow(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + it("should allow empty old_string for file creation", () => { | |
| 14 | + expect(() => { | |
| 15 | + validateSingleEdit("", "new content"); | |
| 16 | + }).not.toThrow(); | |
| 17 | + }); | |
| 18 | + | |
| 19 | + it("should allow empty new_string for deletion", () => { | |
| 20 | + expect(() => { | |
| 21 | + validateSingleEdit("delete me", ""); | |
| 22 | + }).not.toThrow(); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + it("should allow multiline strings", () => { | |
| 26 | + expect(() => { | |
| 27 | + validateSingleEdit("line1\nline2", "newline1\nnewline2"); | |
| 28 | + }).not.toThrow(); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("should allow special characters", () => { | |
| 32 | + expect(() => { | |
| 33 | + validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g"); | |
| 34 | + }).not.toThrow(); | |
| 35 | + }); | |
| 36 | + }); | |
| 37 | + | |
| 38 | + describe("invalid inputs", () => { | |
| 39 | + it("should throw error when old_string is null", () => { | |
| 40 | + expect(() => { | |
| 41 | + validateSingleEdit(null as any, "new"); | |
| 42 | + }).toThrowError( | |
| 43 | + expect.objectContaining({ | |
| 44 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 45 | + }), | |
| 46 | + ); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + it("should throw error when old_string is undefined", () => { | |
| 50 | + expect(() => { | |
| 51 | + validateSingleEdit(undefined as any, "new"); | |
| 52 | + }).toThrowError( | |
| 53 | + expect.objectContaining({ | |
| 54 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 55 | + }), | |
| 56 | + ); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + it("should throw error when new_string is undefined", () => { | |
| 60 | + expect(() => { | |
| 61 | + validateSingleEdit("old", undefined as any); | |
| 62 | + }).toThrowError( | |
| 63 | + expect.objectContaining({ | |
| 64 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 65 | + }), | |
| 66 | + ); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("should throw error when old_string and new_string are identical", () => { | |
| 70 | + expect(() => { | |
| 71 | + validateSingleEdit("same", "same"); | |
| 72 | + }).toThrowError( | |
| 73 | + expect.objectContaining({ | |
| 74 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 75 | + }), | |
| 76 | + ); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + it("should throw error when both are empty strings", () => { | |
| 80 | + expect(() => { | |
| 81 | + validateSingleEdit("", ""); | |
| 82 | + }).toThrowError( | |
| 83 | + expect.objectContaining({ | |
| 84 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 85 | + }), | |
| 86 | + ); | |
| 87 | + }); | |
| 88 | + }); | |
| 89 | + | |
| 90 | + describe("error messages with context", () => { | |
| 91 | + it("should include edit number in error messages when index provided", () => { | |
| 92 | + expect(() => { | |
| 93 | + validateSingleEdit(null as any, "new", 2); | |
| 94 | + }).toThrowError( | |
| 95 | + expect.objectContaining({ | |
| 96 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 97 | + }), | |
| 98 | + ); | |
| 99 | + }); | |
| 100 | + | |
| 101 | + it("should include edit number for new_string errors", () => { | |
| 102 | + expect(() => { | |
| 103 | + validateSingleEdit("old", undefined as any, 0); | |
| 104 | + }).toThrowError( | |
| 105 | + expect.objectContaining({ | |
| 106 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 107 | + }), | |
| 108 | + ); | |
| 109 | + }); | |
| 110 | + | |
| 111 | + it("should include edit number for identical strings error", () => { | |
| 112 | + expect(() => { | |
| 113 | + validateSingleEdit("same", "same", 4); | |
| 114 | + }).toThrowError( | |
| 115 | + expect.objectContaining({ | |
| 116 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 117 | + }), | |
| 118 | + ); | |
| 119 | + }); | |
| 120 | + | |
| 121 | + it("should not include context when index not provided", () => { | |
| 122 | + expect(() => { | |
| 123 | + validateSingleEdit("same", "same"); | |
| 124 | + }).toThrowError( | |
| 125 | + expect.objectContaining({ | |
| 126 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 127 | + }), | |
| 128 | + ); | |
| 129 | + }); | |
| 130 | + }); | |
| 131 | +}); | |
| 132 | + | |
| 133 | +describe("trimEmptyLines", () => { | |
| 134 | + it("trims leading empty lines from start", () => { | |
| 135 | + const input = ["", "", "a", "", "b"]; | |
| 136 | + const result = trimEmptyLines({ lines: input, fromEnd: false }); | |
| 137 | + expect(result).toEqual(["a", "", "b"]); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("trims trailing empty lines from end", () => { | |
| 141 | + const input = ["a", "", "b", "", ""]; | |
| 142 | + const result = trimEmptyLines({ lines: input, fromEnd: true }); | |
| 143 | + expect(result).toEqual(["a", "", "b"]); | |
| 144 | + }); | |
| 145 | + | |
| 146 | + it("returns empty array when all lines are empty", () => { | |
| 147 | + const input = ["", "", ""]; | |
| 148 | + const result = trimEmptyLines({ lines: input, fromEnd: false }); | |
| 149 | + expect(result).toEqual([]); | |
| 150 | + }); | |
| 151 | +}); |
deleted core/edit/searchAndReplace/findSearchMatch.strategy.test.ts +0 −713
| @@ -1,713 +0,0 @@ | ||
| 1 | -import { findSearchMatch, SearchMatchResult } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -/** | |
| 4 | - * Helper function to perform a replacement using the match result | |
| 5 | - * This simulates what the actual replacement tool would do | |
| 6 | - */ | |
| 7 | -function performReplacement( | |
| 8 | - fileContent: string, | |
| 9 | - match: SearchMatchResult, | |
| 10 | - replacement: string, | |
| 11 | -): string { | |
| 12 | - return ( | |
| 13 | - fileContent.substring(0, match.startIndex) + | |
| 14 | - replacement + | |
| 15 | - fileContent.substring(match.endIndex) | |
| 16 | - ); | |
| 17 | -} | |
| 18 | - | |
| 19 | -/** | |
| 20 | - * Helper function to test a specific strategy by crafting inputs that | |
| 21 | - * will fail all previous strategies | |
| 22 | - */ | |
| 23 | -function testSpecificStrategy( | |
| 24 | - fileContent: string, | |
| 25 | - searchContent: string, | |
| 26 | - expectedStrategy: string, | |
| 27 | -): SearchMatchResult | null { | |
| 28 | - const result = findSearchMatch(fileContent, searchContent); | |
| 29 | - if (result && result.strategyName !== expectedStrategy) { | |
| 30 | - throw new Error( | |
| 31 | - `Expected strategy ${expectedStrategy} but got ${result.strategyName}`, | |
| 32 | - ); | |
| 33 | - } | |
| 34 | - return result; | |
| 35 | -} | |
| 36 | - | |
| 37 | -/** | |
| 38 | - * Helper function to verify that a match result correctly identifies | |
| 39 | - * the intended content and replacement works properly | |
| 40 | - */ | |
| 41 | -function verifyMatchAndReplacement( | |
| 42 | - fileContent: string, | |
| 43 | - searchContent: string, | |
| 44 | - expectedMatchedText: string, | |
| 45 | - replacementText: string, | |
| 46 | - expectedResult: string, | |
| 47 | -): void { | |
| 48 | - const match = findSearchMatch(fileContent, searchContent); | |
| 49 | - | |
| 50 | - if (!match) { | |
| 51 | - throw new Error("No match found"); | |
| 52 | - } | |
| 53 | - | |
| 54 | - // Verify the match captures the expected text | |
| 55 | - const actualMatchedText = fileContent.substring( | |
| 56 | - match.startIndex, | |
| 57 | - match.endIndex, | |
| 58 | - ); | |
| 59 | - expect(actualMatchedText).toBe(expectedMatchedText); | |
| 60 | - | |
| 61 | - // Verify replacement works correctly | |
| 62 | - const result = performReplacement(fileContent, match, replacementText); | |
| 63 | - expect(result).toBe(expectedResult); | |
| 64 | -} | |
| 65 | - | |
| 66 | -describe("Strategy-specific tests", () => { | |
| 67 | - describe("exactMatch strategy", () => { | |
| 68 | - it("should handle exact match at various positions", () => { | |
| 69 | - const testCases = [ | |
| 70 | - { | |
| 71 | - name: "at start", | |
| 72 | - fileContent: "abc def ghi", | |
| 73 | - searchContent: "abc", | |
| 74 | - expectedStart: 0, | |
| 75 | - expectedEnd: 3, | |
| 76 | - }, | |
| 77 | - { | |
| 78 | - name: "in middle", | |
| 79 | - fileContent: "abc def ghi", | |
| 80 | - searchContent: "def", | |
| 81 | - expectedStart: 4, | |
| 82 | - expectedEnd: 7, | |
| 83 | - }, | |
| 84 | - { | |
| 85 | - name: "at end", | |
| 86 | - fileContent: "abc def ghi", | |
| 87 | - searchContent: "ghi", | |
| 88 | - expectedStart: 8, | |
| 89 | - expectedEnd: 11, | |
| 90 | - }, | |
| 91 | - { | |
| 92 | - name: "entire content", | |
| 93 | - fileContent: "abc def ghi", | |
| 94 | - searchContent: "abc def ghi", | |
| 95 | - expectedStart: 0, | |
| 96 | - expectedEnd: 11, | |
| 97 | - }, | |
| 98 | - ]; | |
| 99 | - | |
| 100 | - testCases.forEach( | |
| 101 | - ({ name, fileContent, searchContent, expectedStart, expectedEnd }) => { | |
| 102 | - const result = testSpecificStrategy( | |
| 103 | - fileContent, | |
| 104 | - searchContent, | |
| 105 | - "exactMatch", | |
| 106 | - ); | |
| 107 | - expect(result).not.toBeNull(); | |
| 108 | - expect(result!.startIndex).toBe(expectedStart); | |
| 109 | - expect(result!.endIndex).toBe(expectedEnd); | |
| 110 | - | |
| 111 | - // Verify the matched content | |
| 112 | - const matchedContent = fileContent.substring( | |
| 113 | - result!.startIndex, | |
| 114 | - result!.endIndex, | |
| 115 | - ); | |
| 116 | - expect(matchedContent).toBe(searchContent); | |
| 117 | - }, | |
| 118 | - ); | |
| 119 | - }); | |
| 120 | - | |
| 121 | - it("should handle multiline exact matches", () => { | |
| 122 | - const fileContent = `line1 | |
| 123 | -line2 | |
| 124 | -line3 | |
| 125 | -line4`; | |
| 126 | - const searchContent = `line2 | |
| 127 | -line3`; | |
| 128 | - | |
| 129 | - const result = testSpecificStrategy( | |
| 130 | - fileContent, | |
| 131 | - searchContent, | |
| 132 | - "exactMatch", | |
| 133 | - ); | |
| 134 | - expect(result).not.toBeNull(); | |
| 135 | - expect(result!.startIndex).toBe(6); // After "line1\n" | |
| 136 | - expect(result!.endIndex).toBe(17); // End of "line3" | |
| 137 | - | |
| 138 | - const matchedContent = fileContent.substring( | |
| 139 | - result!.startIndex, | |
| 140 | - result!.endIndex, | |
| 141 | - ); | |
| 142 | - expect(matchedContent).toBe(searchContent); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - it("should handle content with special characters", () => { | |
| 146 | - const fileContent = `const regex = /[a-z]+/gi; | |
| 147 | -const str = "Hello, World!"; | |
| 148 | -const result = str.match(regex);`; | |
| 149 | - const searchContent = `const str = "Hello, World!";`; | |
| 150 | - | |
| 151 | - const result = testSpecificStrategy( | |
| 152 | - fileContent, | |
| 153 | - searchContent, | |
| 154 | - "exactMatch", | |
| 155 | - ); | |
| 156 | - expect(result).not.toBeNull(); | |
| 157 | - | |
| 158 | - const matchedContent = fileContent.substring( | |
| 159 | - result!.startIndex, | |
| 160 | - result!.endIndex, | |
| 161 | - ); | |
| 162 | - expect(matchedContent).toBe(searchContent); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should verify replacement works correctly for exact matches", () => { | |
| 166 | - verifyMatchAndReplacement( | |
| 167 | - "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 168 | - "const b = 2;", | |
| 169 | - "const b = 2;", | |
| 170 | - "const b = 42;", | |
| 171 | - "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 172 | - ); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - it("should handle Windows-style line endings", () => { | |
| 176 | - const fileContent = "line1\r\nline2\r\nline3"; | |
| 177 | - const searchContent = "line2"; | |
| 178 | - | |
| 179 | - const result = testSpecificStrategy( | |
| 180 | - fileContent, | |
| 181 | - searchContent, | |
| 182 | - "exactMatch", | |
| 183 | - ); | |
| 184 | - expect(result).not.toBeNull(); | |
| 185 | - expect(result!.startIndex).toBe(7); // After "line1\r\n" | |
| 186 | - expect(result!.endIndex).toBe(12); // End of "line2" | |
| 187 | - }); | |
| 188 | - | |
| 189 | - it("should handle mixed line endings", () => { | |
| 190 | - const fileContent = "line1\nline2\r\nline3\rline4"; | |
| 191 | - const searchContent = "line2\r\nline3"; | |
| 192 | - | |
| 193 | - const result = testSpecificStrategy( | |
| 194 | - fileContent, | |
| 195 | - searchContent, | |
| 196 | - "exactMatch", | |
| 197 | - ); | |
| 198 | - expect(result).not.toBeNull(); | |
| 199 | - | |
| 200 | - const matchedContent = fileContent.substring( | |
| 201 | - result!.startIndex, | |
| 202 | - result!.endIndex, | |
| 203 | - ); | |
| 204 | - expect(matchedContent).toBe(searchContent); | |
| 205 | - }); | |
| 206 | - }); | |
| 207 | - | |
| 208 | - describe("trimmedMatch strategy", () => { | |
| 209 | - it("should match when only whitespace differs at edges", () => { | |
| 210 | - const testCases = [ | |
| 211 | - { | |
| 212 | - name: "leading spaces", | |
| 213 | - fileContent: "abc\n def\nghi", | |
| 214 | - searchContent: " def", | |
| 215 | - trimmedSearch: "def", | |
| 216 | - }, | |
| 217 | - { | |
| 218 | - name: "trailing spaces", | |
| 219 | - fileContent: "abc\ndef \nghi", | |
| 220 | - searchContent: "def ", | |
| 221 | - trimmedSearch: "def", | |
| 222 | - }, | |
| 223 | - { | |
| 224 | - name: "both leading and trailing", | |
| 225 | - fileContent: "abc\n def \nghi", | |
| 226 | - searchContent: " def ", | |
| 227 | - trimmedSearch: "def", | |
| 228 | - }, | |
| 229 | - { | |
| 230 | - name: "tabs and spaces", | |
| 231 | - fileContent: "abc\n\t def \t\nghi", | |
| 232 | - searchContent: "\t def \t", | |
| 233 | - trimmedSearch: "def", | |
| 234 | - }, | |
| 235 | - ]; | |
| 236 | - | |
| 237 | - testCases.forEach( | |
| 238 | - ({ name, fileContent, searchContent, trimmedSearch }) => { | |
| 239 | - const result = findSearchMatch(fileContent, searchContent); | |
| 240 | - expect(result).not.toBeNull(); | |
| 241 | - | |
| 242 | - // For cases where exact match exists, it should be preferred | |
| 243 | - if (fileContent.indexOf(searchContent) !== -1) { | |
| 244 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 245 | - const matchedContent = fileContent.substring( | |
| 246 | - result!.startIndex, | |
| 247 | - result!.endIndex, | |
| 248 | - ); | |
| 249 | - expect(matchedContent).toBe(searchContent); | |
| 250 | - } else { | |
| 251 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 252 | - // The match should find the trimmed content with surrounding whitespace | |
| 253 | - const matchedContent = fileContent.substring( | |
| 254 | - result!.startIndex, | |
| 255 | - result!.endIndex, | |
| 256 | - ); | |
| 257 | - expect(matchedContent).toContain(trimmedSearch); | |
| 258 | - } | |
| 259 | - }, | |
| 260 | - ); | |
| 261 | - }); | |
| 262 | - | |
| 263 | - it("should handle multiline content with edge whitespace", () => { | |
| 264 | - const fileContent = `function test() { | |
| 265 | - const x = 1; | |
| 266 | - const y = 2; | |
| 267 | -}`; | |
| 268 | - const searchContent = ` const x = 1; | |
| 269 | - const y = 2; `; | |
| 270 | - | |
| 271 | - const result = findSearchMatch(fileContent, searchContent); | |
| 272 | - expect(result).not.toBeNull(); | |
| 273 | - // Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used | |
| 274 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 275 | - }); | |
| 276 | - | |
| 277 | - it("should verify replacement with trimmed matches", () => { | |
| 278 | - const fileContent = "start\n targetContent \nend"; | |
| 279 | - const searchContent = " targetContent "; | |
| 280 | - const replacement = "newContent"; | |
| 281 | - | |
| 282 | - const match = findSearchMatch(fileContent, searchContent); | |
| 283 | - expect(match).not.toBeNull(); | |
| 284 | - expect(match!.strategyName).toBe("trimmedMatch"); | |
| 285 | - | |
| 286 | - const result = performReplacement(fileContent, match!, replacement); | |
| 287 | - expect(result).toBe("start\nnewContent\nend"); | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle edge case with only whitespace", () => { | |
| 291 | - const fileContent = " \n \n "; | |
| 292 | - const searchContent = " \n "; | |
| 293 | - | |
| 294 | - const result = findSearchMatch(fileContent, searchContent); | |
| 295 | - expect(result).not.toBeNull(); | |
| 296 | - // Should find exact match since the content matches exactly | |
| 297 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 298 | - }); | |
| 299 | - }); | |
| 300 | - | |
| 301 | - describe("whitespaceIgnoredMatch strategy", () => { | |
| 302 | - it("should match content with different indentation", () => { | |
| 303 | - const fileContent = `function test() { | |
| 304 | - const x = 1; | |
| 305 | - if (x > 0) { | |
| 306 | - return true; | |
| 307 | - } | |
| 308 | -}`; | |
| 309 | - const searchContent = `const x=1; | |
| 310 | -if(x>0){ | |
| 311 | -return true; | |
| 312 | -}`; | |
| 313 | - | |
| 314 | - const result = findSearchMatch(fileContent, searchContent); | |
| 315 | - expect(result).not.toBeNull(); | |
| 316 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 317 | - | |
| 318 | - // Verify the match covers the intended code block | |
| 319 | - const matchedContent = fileContent.substring( | |
| 320 | - result!.startIndex, | |
| 321 | - result!.endIndex, | |
| 322 | - ); | |
| 323 | - expect(matchedContent).toContain("const x = 1"); | |
| 324 | - expect(matchedContent).toContain("return true"); | |
| 325 | - }); | |
| 326 | - | |
| 327 | - it("should handle complex whitespace variations", () => { | |
| 328 | - const testCases = [ | |
| 329 | - { | |
| 330 | - name: "spaces vs tabs", | |
| 331 | - fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}", | |
| 332 | - searchContent: "if (condition) { return true; }", | |
| 333 | - }, | |
| 334 | - { | |
| 335 | - name: "multiple spaces collapsed", | |
| 336 | - fileContent: "const result = calculate( x , y );", | |
| 337 | - searchContent: "const result=calculate(x,y);", | |
| 338 | - }, | |
| 339 | - { | |
| 340 | - name: "newlines removed", | |
| 341 | - fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}", | |
| 342 | - searchContent: "function test(){return 1;}", | |
| 343 | - }, | |
| 344 | - ]; | |
| 345 | - | |
| 346 | - testCases.forEach(({ name, fileContent, searchContent }) => { | |
| 347 | - const result = findSearchMatch(fileContent, searchContent); | |
| 348 | - expect(result).not.toBeNull(); | |
| 349 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 350 | - | |
| 351 | - // Verify the entire content is matched | |
| 352 | - const matchedContent = fileContent.substring( | |
| 353 | - result!.startIndex, | |
| 354 | - result!.endIndex, | |
| 355 | - ); | |
| 356 | - expect(matchedContent.replace(/\s/g, "")).toBe( | |
| 357 | - searchContent.replace(/\s/g, ""), | |
| 358 | - ); | |
| 359 | - }); | |
| 360 | - }); | |
| 361 | - | |
| 362 | - it("should handle partial matches with whitespace differences", () => { | |
| 363 | - const fileContent = `class Example { | |
| 364 | - constructor(name) { | |
| 365 | - this.name = name; | |
| 366 | - this.items = []; | |
| 367 | - } | |
| 368 | - | |
| 369 | - addItem(item) { | |
| 370 | - this.items.push(item); | |
| 371 | - } | |
| 372 | -}`; | |
| 373 | - const searchContent = `constructor(name){this.name=name;this.items=[];}`; | |
| 374 | - | |
| 375 | - const result = findSearchMatch(fileContent, searchContent); | |
| 376 | - expect(result).not.toBeNull(); | |
| 377 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 378 | - | |
| 379 | - // The match should cover the constructor method | |
| 380 | - const matchedContent = fileContent.substring( | |
| 381 | - result!.startIndex, | |
| 382 | - result!.endIndex, | |
| 383 | - ); | |
| 384 | - expect(matchedContent).toContain("constructor"); | |
| 385 | - expect(matchedContent).toContain("this.items = []"); | |
| 386 | - }); | |
| 387 | - | |
| 388 | - it("should verify replacement with whitespace-ignored matches", () => { | |
| 389 | - const fileContent = `function calculate ( a , b ) { | |
| 390 | - return a + b ; | |
| 391 | -}`; | |
| 392 | - const searchContent = `function calculate(a,b){return a+b;}`; | |
| 393 | - const replacement = `function calculate(x, y) { | |
| 394 | - return x + y; | |
| 395 | -}`; | |
| 396 | - | |
| 397 | - const match = findSearchMatch(fileContent, searchContent); | |
| 398 | - expect(match).not.toBeNull(); | |
| 399 | - expect(match!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 400 | - | |
| 401 | - const result = performReplacement(fileContent, match!, replacement); | |
| 402 | - expect(result).toBe(replacement); | |
| 403 | - }); | |
| 404 | - | |
| 405 | - it("should handle edge cases with empty content after whitespace removal", () => { | |
| 406 | - const fileContent = " \n\t\r\n "; | |
| 407 | - const searchContent = " \n "; | |
| 408 | - | |
| 409 | - const result = findSearchMatch(fileContent, searchContent); | |
| 410 | - // Since search content doesn't exist in file but trims to empty, should return emptySearch | |
| 411 | - expect(result).not.toBeNull(); | |
| 412 | - expect(result!.strategyName).toBe("emptySearch"); | |
| 413 | - }); | |
| 414 | - | |
| 415 | - it("should match correctly when multiple potential matches exist", () => { | |
| 416 | - const fileContent = `const a=1; | |
| 417 | -const a = 1 ; | |
| 418 | -const a = 1;`; | |
| 419 | - const searchContent = "const a = 1;"; | |
| 420 | - | |
| 421 | - const result = findSearchMatch(fileContent, searchContent); | |
| 422 | - expect(result).not.toBeNull(); | |
| 423 | - // Should find the exact match first (third occurrence) | |
| 424 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 425 | - expect(result!.startIndex).toBe(33); // After first two lines | |
| 426 | - }); | |
| 427 | - }); | |
| 428 | - | |
| 429 | - describe("jaroWinklerFuzzyMatch strategy", () => { | |
| 430 | - it("should match similar code with variable name differences", () => { | |
| 431 | - const fileContent = `function calculateTotal(items) { | |
| 432 | - let sum = 0; | |
| 433 | - for (const item of items) { | |
| 434 | - sum += item.price; | |
| 435 | - } | |
| 436 | - return sum; | |
| 437 | -}`; | |
| 438 | - const searchContent = `function calculateTotal(products) { | |
| 439 | - let total = 0; | |
| 440 | - for (const product of products) { | |
| 441 | - total += product.price; | |
| 442 | - } | |
| 443 | - return total; | |
| 444 | -}`; | |
| 445 | - | |
| 446 | - const result = findSearchMatch(fileContent, searchContent); | |
| 447 | - expect(result).not.toBeNull(); | |
| 448 | - expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch"); | |
| 449 | - }); | |
| 450 | - | |
| 451 | - it("should match code with minor typos", () => { | |
| 452 | - const testCases = [ | |
| 453 | - { | |
| 454 | - name: "typo in function name", | |
| 455 | - fileContent: "function getUserName() { return this.name; }", | |
| 456 | - searchContent: "function getUserNaem() { return this.name; }", | |
| 457 | - }, | |
| 458 | - { | |
| 459 | - name: "typo in variable", | |
| 460 | - fileContent: "const message = 'Hello World';", | |
| 461 | - searchContent: "const mesage = 'Hello World';", | |
| 462 | - }, | |
| 463 | - { | |
| 464 | - name: "missing character", | |
| 465 | - fileContent: "console.log('Debug info');", | |
| 466 | - searchContent: "console.log('Debug nfo');", | |
| 467 | - }, | |
| 468 | - ]; | |
| 469 | - | |
| 470 | - testCases.forEach(({ name, fileContent, searchContent }) => { | |
| 471 | - const result = findSearchMatch(fileContent, searchContent); | |
| 472 | - expect(result).not.toBeNull(); | |
| 473 | - expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch"); | |
| 474 | - }); | |
| 475 | - }); | |
| 476 | - | |
| 477 | - it("should not match when similarity is too low", () => { | |
| 478 | - const fileContent = "function add(a, b) { return a + b; }"; | |
| 479 | - const searchContent = | |
| 480 | - "class Calculator { multiply(x, y) { return x * y; } }"; | |
| 481 | - | |
| 482 | - const result = findSearchMatch(fileContent, searchContent); | |
| 483 | - expect(result).toBeNull(); | |
| 484 | - }); | |
| 485 | - | |
| 486 | - it("should handle multiline fuzzy matches", () => { | |
| 487 | - const fileContent = `if (userIsLoggedIn) { | |
| 488 | - showDashboard(); | |
| 489 | - loadUserData(); | |
| 490 | -}`; | |
| 491 | - const searchContent = `if (isUserLoggedIn) { | |
| 492 | - displayDashboard(); | |
| 493 | - fetchUserData(); | |
| 494 | -}`; | |
| 495 | - | |
| 496 | - const result = findSearchMatch(fileContent, searchContent); | |
| 497 | - expect(result).not.toBeNull(); | |
| 498 | - expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch"); | |
| 499 | - }); | |
| 500 | - | |
| 501 | - it("should verify replacement with fuzzy matches", () => { | |
| 502 | - const fileContent = "const userName = 'John';"; | |
| 503 | - const searchContent = "const usrName = 'John';"; // Typo in variable name | |
| 504 | - const replacement = "const userName = 'Jane';"; | |
| 505 | - | |
| 506 | - const match = findSearchMatch(fileContent, searchContent); | |
| 507 | - expect(match).not.toBeNull(); | |
| 508 | - expect(match!.strategyName).toBe("jaroWinklerFuzzyMatch"); | |
| 509 | - | |
| 510 | - const result = performReplacement(fileContent, match!, replacement); | |
| 511 | - expect(result).toBe(replacement); | |
| 512 | - }); | |
| 513 | - | |
| 514 | - it("should handle edge case with very short strings", () => { | |
| 515 | - const fileContent = "ab"; | |
| 516 | - const searchContent = "ac"; | |
| 517 | - | |
| 518 | - const result = findSearchMatch(fileContent, searchContent); | |
| 519 | - // Should not match due to low similarity on short strings | |
| 520 | - expect(result).toBeNull(); | |
| 521 | - }); | |
| 522 | - }); | |
| 523 | - | |
| 524 | - describe("Empty search content", () => { | |
| 525 | - it("should always return position 0 for empty search", () => { | |
| 526 | - const testCases = [ | |
| 527 | - { fileContent: "some content" }, | |
| 528 | - { fileContent: "" }, | |
| 529 | - { fileContent: "line1\nline2\nline3" }, | |
| 530 | - { fileContent: " spaces " }, | |
| 531 | - ]; | |
| 532 | - | |
| 533 | - testCases.forEach(({ fileContent }) => { | |
| 534 | - const result = findSearchMatch(fileContent, ""); | |
| 535 | - expect(result).toEqual({ | |
| 536 | - startIndex: 0, | |
| 537 | - endIndex: 0, | |
| 538 | - strategyName: "emptySearch", | |
| 539 | - }); | |
| 540 | - }); | |
| 541 | - }); | |
| 542 | - | |
| 543 | - it("should treat whitespace-only search as empty", () => { | |
| 544 | - const searchVariants = [" ", "\n\n", "\t\t", " \n\t "]; | |
| 545 | - | |
| 546 | - searchVariants.forEach((searchContent) => { | |
| 547 | - const result = findSearchMatch("test content", searchContent); | |
| 548 | - expect(result).toEqual({ | |
| 549 | - startIndex: 0, | |
| 550 | - endIndex: 0, | |
| 551 | - strategyName: "emptySearch", | |
| 552 | - }); | |
| 553 | - }); | |
| 554 | - }); | |
| 555 | - }); | |
| 556 | - | |
| 557 | - describe("Strategy precedence", () => { | |
| 558 | - it("should always prefer exact match over other strategies", () => { | |
| 559 | - const fileContent = `exact match | |
| 560 | -exact match with spaces | |
| 561 | -exactmatch`; | |
| 562 | - | |
| 563 | - // This should find exact match even though fuzzy would also work | |
| 564 | - const result = findSearchMatch(fileContent, "exact match"); | |
| 565 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 566 | - expect(result!.startIndex).toBe(0); | |
| 567 | - }); | |
| 568 | - | |
| 569 | - it("should prefer trimmed match over whitespace-ignored", () => { | |
| 570 | - const fileContent = " content "; | |
| 571 | - const searchContent = " content "; | |
| 572 | - | |
| 573 | - // Should find exact match | |
| 574 | - const result = findSearchMatch(fileContent, searchContent); | |
| 575 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 576 | - }); | |
| 577 | - | |
| 578 | - it("should prefer whitespace-ignored over fuzzy", () => { | |
| 579 | - const fileContent = "const x = 1;"; | |
| 580 | - const searchContent = "const x=1;"; | |
| 581 | - | |
| 582 | - // Should use whitespace-ignored, not fuzzy | |
| 583 | - const result = findSearchMatch(fileContent, searchContent); | |
| 584 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 585 | - }); | |
| 586 | - }); | |
| 587 | - | |
| 588 | - describe("Replacement verification tests", () => { | |
| 589 | - it("should correctly replace content found by each strategy", () => { | |
| 590 | - const testCases = [ | |
| 591 | - { | |
| 592 | - name: "exact match replacement", | |
| 593 | - fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 594 | - searchContent: "const b = 2;", | |
| 595 | - replacement: "const b = 42;", | |
| 596 | - expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 597 | - expectedStrategy: "exactMatch", | |
| 598 | - }, | |
| 599 | - { | |
| 600 | - name: "trimmed match replacement", | |
| 601 | - fileContent: "start\n target \nend", | |
| 602 | - searchContent: " target ", | |
| 603 | - replacement: "replaced", | |
| 604 | - expectedResult: "start\nreplaced\nend", | |
| 605 | - expectedStrategy: "trimmedMatch", | |
| 606 | - }, | |
| 607 | - { | |
| 608 | - name: "whitespace-ignored replacement", | |
| 609 | - fileContent: "if ( x > 0 ) { return true; }", | |
| 610 | - searchContent: "if(x>0){return true;}", | |
| 611 | - replacement: "if (x > 0) { return false; }", | |
| 612 | - expectedResult: "if (x > 0) { return false; }", | |
| 613 | - expectedStrategy: "whitespaceIgnoredMatch", | |
| 614 | - }, | |
| 615 | - ]; | |
| 616 | - | |
| 617 | - testCases.forEach( | |
| 618 | - ({ | |
| 619 | - name, | |
| 620 | - fileContent, | |
| 621 | - searchContent, | |
| 622 | - replacement, | |
| 623 | - expectedResult, | |
| 624 | - expectedStrategy, | |
| 625 | - }) => { | |
| 626 | - const match = findSearchMatch(fileContent, searchContent); | |
| 627 | - expect(match).not.toBeNull(); | |
| 628 | - expect(match!.strategyName).toBe(expectedStrategy); | |
| 629 | - | |
| 630 | - const result = performReplacement(fileContent, match!, replacement); | |
| 631 | - expect(result).toBe(expectedResult); | |
| 632 | - }, | |
| 633 | - ); | |
| 634 | - }); | |
| 635 | - | |
| 636 | - it("should handle edge cases in replacement", () => { | |
| 637 | - // Empty replacement | |
| 638 | - verifyMatchAndReplacement( | |
| 639 | - "before target after", | |
| 640 | - "target", | |
| 641 | - "target", | |
| 642 | - "", | |
| 643 | - "before after", | |
| 644 | - ); | |
| 645 | - | |
| 646 | - // Replacement longer than original | |
| 647 | - verifyMatchAndReplacement( | |
| 648 | - "short", | |
| 649 | - "short", | |
| 650 | - "short", | |
| 651 | - "much longer replacement", | |
| 652 | - "much longer replacement", | |
| 653 | - ); | |
| 654 | - | |
| 655 | - // Multiline replacement | |
| 656 | - verifyMatchAndReplacement( | |
| 657 | - "single line", | |
| 658 | - "single", | |
| 659 | - "single", | |
| 660 | - "multi\nline\nreplacement", | |
| 661 | - "multi\nline\nreplacement line", | |
| 662 | - ); | |
| 663 | - }); | |
| 664 | - }); | |
| 665 | - | |
| 666 | - describe("Performance and edge cases", () => { | |
| 667 | - it("should handle very long content efficiently", () => { | |
| 668 | - const longContent = "x".repeat(10000) + "target" + "y".repeat(10000); | |
| 669 | - const result = findSearchMatch(longContent, "target"); | |
| 670 | - | |
| 671 | - expect(result).not.toBeNull(); | |
| 672 | - expect(result!.startIndex).toBe(10000); | |
| 673 | - expect(result!.endIndex).toBe(10006); | |
| 674 | - }); | |
| 675 | - | |
| 676 | - it("should handle unicode and special characters", () => { | |
| 677 | - const testCases = [ | |
| 678 | - { | |
| 679 | - fileContent: "const emoji = '🚀🌟🎉';", | |
| 680 | - searchContent: "🚀🌟🎉", | |
| 681 | - }, | |
| 682 | - { | |
| 683 | - fileContent: "const chinese = '你好世界';", | |
| 684 | - searchContent: "你好世界", | |
| 685 | - }, | |
| 686 | - { | |
| 687 | - fileContent: "const regex = /\\d+/g;", | |
| 688 | - searchContent: "/\\d+/g", | |
| 689 | - }, | |
| 690 | - ]; | |
| 691 | - | |
| 692 | - testCases.forEach(({ fileContent, searchContent }) => { | |
| 693 | - const result = findSearchMatch(fileContent, searchContent); | |
| 694 | - expect(result).not.toBeNull(); | |
| 695 | - | |
| 696 | - const matchedContent = fileContent.substring( | |
| 697 | - result!.startIndex, | |
| 698 | - result!.endIndex, | |
| 699 | - ); | |
| 700 | - expect(matchedContent).toContain(searchContent); | |
| 701 | - }); | |
| 702 | - }); | |
| 703 | - | |
| 704 | - it("should handle null bytes and control characters", () => { | |
| 705 | - const fileContent = "before\x00null\x01byte\x02after"; | |
| 706 | - const searchContent = "\x00null\x01byte\x02"; | |
| 707 | - | |
| 708 | - const result = findSearchMatch(fileContent, searchContent); | |
| 709 | - expect(result).not.toBeNull(); | |
| 710 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 711 | - }); | |
| 712 | - }); | |
| 713 | -}); |
deleted core/edit/searchAndReplace/findSearchMatch.test.ts +0 −768
| @@ -1,768 +0,0 @@ | ||
| 1 | -import { findSearchMatch } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -describe("Exact matches", () => { | |
| 4 | - it("should find exact match at the beginning of file", () => { | |
| 5 | - const fileContent = `function hello() { | |
| 6 | - console.log("world"); | |
| 7 | -}`; | |
| 8 | - const searchContent = `function hello() { | |
| 9 | - console.log("world"); | |
| 10 | -}`; | |
| 11 | - | |
| 12 | - const result = findSearchMatch(fileContent, searchContent); | |
| 13 | - | |
| 14 | - expect(result).toEqual({ | |
| 15 | - startIndex: 0, | |
| 16 | - endIndex: fileContent.length, | |
| 17 | - strategyName: "exactMatch", | |
| 18 | - }); | |
| 19 | - }); | |
| 20 | - | |
| 21 | - it("should find exact match in the middle of file", () => { | |
| 22 | - const fileContent = `const a = 1; | |
| 23 | -function hello() { | |
| 24 | - console.log("world"); | |
| 25 | -} | |
| 26 | -const b = 2;`; | |
| 27 | - const searchContent = `function hello() { | |
| 28 | - console.log("world"); | |
| 29 | -}`; | |
| 30 | - | |
| 31 | - const result = findSearchMatch(fileContent, searchContent); | |
| 32 | - | |
| 33 | - expect(result).toEqual({ | |
| 34 | - startIndex: 13, // After "const a = 1;\n" | |
| 35 | - endIndex: 13 + searchContent.length, | |
| 36 | - strategyName: "exactMatch", | |
| 37 | - }); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - it("should find exact match at the end of file", () => { | |
| 41 | - const fileContent = `const a = 1; | |
| 42 | -function hello() { | |
| 43 | - console.log("world"); | |
| 44 | -}`; | |
| 45 | - const searchContent = `function hello() { | |
| 46 | - console.log("world"); | |
| 47 | -}`; | |
| 48 | - | |
| 49 | - const result = findSearchMatch(fileContent, searchContent); | |
| 50 | - | |
| 51 | - expect(result).toEqual({ | |
| 52 | - startIndex: 13, // After "const a = 1;\n" | |
| 53 | - endIndex: fileContent.length, | |
| 54 | - strategyName: "exactMatch", | |
| 55 | - }); | |
| 56 | - }); | |
| 57 | - | |
| 58 | - it("should find exact match with single line", () => { | |
| 59 | - const fileContent = `const a = 1; | |
| 60 | -const b = 2; | |
| 61 | -const c = 3;`; | |
| 62 | - const searchContent = `const b = 2;`; | |
| 63 | - | |
| 64 | - const result = findSearchMatch(fileContent, searchContent); | |
| 65 | - | |
| 66 | - expect(result).toEqual({ | |
| 67 | - startIndex: 13, // After "const a = 1;\n" | |
| 68 | - endIndex: 13 + searchContent.length, | |
| 69 | - strategyName: "exactMatch", | |
| 70 | - }); | |
| 71 | - }); | |
| 72 | - | |
| 73 | - it("should find exact match with whitespace preserved", () => { | |
| 74 | - const fileContent = `function test() { | |
| 75 | - const x = 1; | |
| 76 | - const y = 2; | |
| 77 | -}`; | |
| 78 | - const searchContent = ` const x = 1; | |
| 79 | - const y = 2;`; | |
| 80 | - | |
| 81 | - const result = findSearchMatch(fileContent, searchContent); | |
| 82 | - | |
| 83 | - // The actual indexOf result is 18, not 17 | |
| 84 | - expect(result).toEqual({ | |
| 85 | - startIndex: 18, | |
| 86 | - endIndex: 18 + searchContent.length, | |
| 87 | - strategyName: "exactMatch", | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | -}); | |
| 91 | - | |
| 92 | -describe("Trimmed matches", () => { | |
| 93 | - it("should find trimmed match when exact match fails due to leading newlines", () => { | |
| 94 | - const fileContent = `function hello() { | |
| 95 | - console.log("world"); | |
| 96 | -}`; | |
| 97 | - const searchContent = `\n\nfunction hello() { | |
| 98 | - console.log("world"); | |
| 99 | -}\n\n`; | |
| 100 | - | |
| 101 | - const result = findSearchMatch(fileContent, searchContent); | |
| 102 | - | |
| 103 | - expect(result).toEqual({ | |
| 104 | - startIndex: 0, | |
| 105 | - endIndex: fileContent.length, // Uses trimmed length | |
| 106 | - strategyName: "trimmedMatch", | |
| 107 | - }); | |
| 108 | - }); | |
| 109 | - | |
| 110 | - it("should find trimmed match when exact match fails due to trailing newlines", () => { | |
| 111 | - const fileContent = `const a = 1; | |
| 112 | -function hello() { | |
| 113 | - return "world"; | |
| 114 | -} | |
| 115 | -const b = 2;`; | |
| 116 | - const searchContent = `\nfunction hello() { | |
| 117 | - return "world"; | |
| 118 | -}\n`; | |
| 119 | - | |
| 120 | - const result = findSearchMatch(fileContent, searchContent); | |
| 121 | - | |
| 122 | - // The function finds the exact match first (at index 12), not the trimmed match | |
| 123 | - expect(result).toEqual({ | |
| 124 | - startIndex: 12, | |
| 125 | - endIndex: 12 + searchContent.length, | |
| 126 | - strategyName: "exactMatch", | |
| 127 | - }); | |
| 128 | - }); | |
| 129 | - | |
| 130 | - it("should find trimmed match for single line with extra whitespace", () => { | |
| 131 | - const fileContent = `const a = 1; | |
| 132 | -const b = 2; | |
| 133 | -const c = 3;`; | |
| 134 | - const searchContent = `\n const b = 2; \n`; | |
| 135 | - | |
| 136 | - const result = findSearchMatch(fileContent, searchContent); | |
| 137 | - | |
| 138 | - const trimmedSearchContent = searchContent.trim(); | |
| 139 | - const expectedStart = fileContent.indexOf(trimmedSearchContent); | |
| 140 | - | |
| 141 | - expect(result).toEqual({ | |
| 142 | - startIndex: expectedStart, | |
| 143 | - endIndex: expectedStart + trimmedSearchContent.length, | |
| 144 | - strategyName: "trimmedMatch", | |
| 145 | - }); | |
| 146 | - }); | |
| 147 | -}); | |
| 148 | - | |
| 149 | -describe("Empty search content", () => { | |
| 150 | - it("should match at beginning for empty search content", () => { | |
| 151 | - const fileContent = `function hello() { | |
| 152 | - console.log("world"); | |
| 153 | -}`; | |
| 154 | - const searchContent = ""; | |
| 155 | - | |
| 156 | - const result = findSearchMatch(fileContent, searchContent); | |
| 157 | - | |
| 158 | - expect(result).toEqual({ | |
| 159 | - startIndex: 0, | |
| 160 | - endIndex: 0, | |
| 161 | - strategyName: "emptySearch", | |
| 162 | - }); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should match at beginning for whitespace-only search content", () => { | |
| 166 | - const fileContent = `function hello() { | |
| 167 | - console.log("world"); | |
| 168 | -}`; | |
| 169 | - const searchContent = "\n\n \t \n"; | |
| 170 | - | |
| 171 | - const result = findSearchMatch(fileContent, searchContent); | |
| 172 | - | |
| 173 | - expect(result).toEqual({ | |
| 174 | - startIndex: 0, | |
| 175 | - endIndex: 0, | |
| 176 | - strategyName: "emptySearch", | |
| 177 | - }); | |
| 178 | - }); | |
| 179 | - | |
| 180 | - it("should match at beginning for empty file and empty search", () => { | |
| 181 | - const fileContent = ""; | |
| 182 | - const searchContent = ""; | |
| 183 | - | |
| 184 | - const result = findSearchMatch(fileContent, searchContent); | |
| 185 | - | |
| 186 | - expect(result).toEqual({ | |
| 187 | - startIndex: 0, | |
| 188 | - endIndex: 0, | |
| 189 | - strategyName: "emptySearch", | |
| 190 | - }); | |
| 191 | - }); | |
| 192 | -}); | |
| 193 | - | |
| 194 | -describe("No matches", () => { | |
| 195 | - it("should return null when search content is not found", () => { | |
| 196 | - const fileContent = `function hello() { | |
| 197 | - console.log("world"); | |
| 198 | -}`; | |
| 199 | - const searchContent = `function goodbye() { | |
| 200 | - console.log("world"); | |
| 201 | -}`; | |
| 202 | - | |
| 203 | - const result = findSearchMatch(fileContent, searchContent); | |
| 204 | - | |
| 205 | - expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch"); | |
| 206 | - }); | |
| 207 | - | |
| 208 | - it("should return only fuzzy result when trimmed search content is not found", () => { | |
| 209 | - const fileContent = `function hello() { | |
| 210 | - console.log("world"); | |
| 211 | -}`; | |
| 212 | - const searchContent = `\n\nfunction goodbye() { | |
| 213 | - console.log("world"); | |
| 214 | -}\n\n`; | |
| 215 | - | |
| 216 | - const result = findSearchMatch(fileContent, searchContent); | |
| 217 | - | |
| 218 | - expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch"); | |
| 219 | - }); | |
| 220 | -}); | |
| 221 | - | |
| 222 | -describe("Edge cases", () => { | |
| 223 | - it("should handle empty file with non-empty search", () => { | |
| 224 | - const fileContent = ""; | |
| 225 | - const searchContent = "function hello() {}"; | |
| 226 | - | |
| 227 | - const result = findSearchMatch(fileContent, searchContent); | |
| 228 | - | |
| 229 | - expect(result).toBeNull(); | |
| 230 | - }); | |
| 231 | - | |
| 232 | - it("should handle very large content", () => { | |
| 233 | - const repeatedLine = "const x = 1;\n"; | |
| 234 | - const fileContent = | |
| 235 | - repeatedLine.repeat(1000) + | |
| 236 | - "const target = 2;\n" + | |
| 237 | - repeatedLine.repeat(1000); | |
| 238 | - const searchContent = "const target = 2;"; | |
| 239 | - | |
| 240 | - const result = findSearchMatch(fileContent, searchContent); | |
| 241 | - | |
| 242 | - const expectedStart = repeatedLine.length * 1000; | |
| 243 | - expect(result).toEqual({ | |
| 244 | - startIndex: expectedStart, | |
| 245 | - endIndex: expectedStart + searchContent.length, | |
| 246 | - strategyName: "exactMatch", | |
| 247 | - }); | |
| 248 | - }); | |
| 249 | - | |
| 250 | - it("should handle special characters and symbols", () => { | |
| 251 | - const fileContent = `const regex = /[a-zA-Z]+/g; | |
| 252 | -const symbols = !@#$%^&*(); | |
| 253 | -const unicode = "🚀 Hello 世界";`; | |
| 254 | - const searchContent = `const symbols = !@#$%^&*();`; | |
| 255 | - | |
| 256 | - const result = findSearchMatch(fileContent, searchContent); | |
| 257 | - | |
| 258 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 259 | - expect(result).toEqual({ | |
| 260 | - startIndex: expectedStart, | |
| 261 | - endIndex: expectedStart + searchContent.length, | |
| 262 | - strategyName: "exactMatch", | |
| 263 | - }); | |
| 264 | - }); | |
| 265 | - | |
| 266 | - it("should prefer exact match over trimmed match", () => { | |
| 267 | - const fileContent = `function test() { | |
| 268 | - const x = 1; | |
| 269 | -} | |
| 270 | - | |
| 271 | -function test() { | |
| 272 | - const x = 1; | |
| 273 | -}`; | |
| 274 | - const searchContent = `function test() { | |
| 275 | - const x = 1; | |
| 276 | -}`; | |
| 277 | - | |
| 278 | - const result = findSearchMatch(fileContent, searchContent); | |
| 279 | - | |
| 280 | - // Should find the first exact match, not a trimmed version | |
| 281 | - expect(result).toEqual({ | |
| 282 | - startIndex: 0, | |
| 283 | - endIndex: searchContent.length, | |
| 284 | - strategyName: "exactMatch", | |
| 285 | - }); | |
| 286 | - }); | |
| 287 | - | |
| 288 | - it("should handle multiple occurrences and return first match", () => { | |
| 289 | - const fileContent = `const a = 1; | |
| 290 | -const b = 2; | |
| 291 | -const a = 1;`; | |
| 292 | - const searchContent = `const a = 1;`; | |
| 293 | - | |
| 294 | - const result = findSearchMatch(fileContent, searchContent); | |
| 295 | - | |
| 296 | - expect(result).toEqual({ | |
| 297 | - startIndex: 0, | |
| 298 | - endIndex: searchContent.length, | |
| 299 | - strategyName: "exactMatch", | |
| 300 | - }); | |
| 301 | - }); | |
| 302 | -}); | |
| 303 | - | |
| 304 | -describe("Whitespace-ignored matches", () => { | |
| 305 | - it("should match code with different indentation", () => { | |
| 306 | - const fileContent = `function example() { | |
| 307 | - const x = 1; | |
| 308 | - const y = 2; | |
| 309 | - return x + y; | |
| 310 | -}`; | |
| 311 | - const searchContent = `const x=1; | |
| 312 | -const y=2; | |
| 313 | -return x+y;`; | |
| 314 | - | |
| 315 | - const result = findSearchMatch(fileContent, searchContent); | |
| 316 | - | |
| 317 | - expect(result).not.toBeNull(); | |
| 318 | - expect(result!.startIndex).toBe(20); // After "function example() {\n" | |
| 319 | - expect(result!.endIndex).toBe(72); // End of " return x + y;" | |
| 320 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 321 | - | |
| 322 | - // Verify the matched content contains the original whitespace | |
| 323 | - const matchedContent = fileContent.substring( | |
| 324 | - result!.startIndex, | |
| 325 | - result!.endIndex, | |
| 326 | - ); | |
| 327 | - expect(matchedContent).toBe(` | |
| 328 | - const x = 1; | |
| 329 | - const y = 2; | |
| 330 | - return x + y;`); | |
| 331 | - }); | |
| 332 | - | |
| 333 | - it("should match single line with different spacing", () => { | |
| 334 | - const fileContent = `const a = 1; | |
| 335 | -const b = 2; | |
| 336 | -const c = 3;`; | |
| 337 | - const searchContent = `const b=2;`; | |
| 338 | - | |
| 339 | - const result = findSearchMatch(fileContent, searchContent); | |
| 340 | - | |
| 341 | - expect(result).not.toBeNull(); | |
| 342 | - expect(result!.startIndex).toBe(12); // After "const a = 1;" | |
| 343 | - expect(result!.endIndex).toBe(32); // End of "const b = 2;" | |
| 344 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 345 | - | |
| 346 | - // Verify the matched content preserves original spacing | |
| 347 | - const matchedContent = fileContent.substring( | |
| 348 | - result!.startIndex, | |
| 349 | - result!.endIndex, | |
| 350 | - ); | |
| 351 | - expect(matchedContent).toBe(` | |
| 352 | -const b = 2;`); | |
| 353 | - }); | |
| 354 | - | |
| 355 | - it("should match with tabs vs spaces", () => { | |
| 356 | - const fileContent = `function test() { | |
| 357 | -\tif (condition) { | |
| 358 | -\t\treturn true; | |
| 359 | -\t} | |
| 360 | -}`; | |
| 361 | - const searchContent = `if (condition) { | |
| 362 | - return true; | |
| 363 | -}`; | |
| 364 | - | |
| 365 | - const result = findSearchMatch(fileContent, searchContent); | |
| 366 | - | |
| 367 | - expect(result).not.toBeNull(); | |
| 368 | - expect(result!.startIndex).toBe(17); // After "function test() {" | |
| 369 | - expect(result!.endIndex).toBe(53); // End of "\t}" | |
| 370 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 371 | - | |
| 372 | - // Verify the matched content preserves original tabs | |
| 373 | - const matchedContent = fileContent.substring( | |
| 374 | - result!.startIndex, | |
| 375 | - result!.endIndex, | |
| 376 | - ); | |
| 377 | - expect(matchedContent).toBe(` | |
| 378 | -\tif (condition) { | |
| 379 | -\t\treturn true; | |
| 380 | -\t}`); | |
| 381 | - }); | |
| 382 | - | |
| 383 | - it("should match complex whitespace patterns", () => { | |
| 384 | - const fileContent = `const obj = { | |
| 385 | - key1 : 'value1', | |
| 386 | - key2 : 'value2', | |
| 387 | - key3 : 'value3' | |
| 388 | -};`; | |
| 389 | - const searchContent = `key1:'value1', | |
| 390 | -key2:'value2', | |
| 391 | -key3:'value3'`; | |
| 392 | - | |
| 393 | - const result = findSearchMatch(fileContent, searchContent); | |
| 394 | - | |
| 395 | - expect(result).not.toBeNull(); | |
| 396 | - expect(result!.startIndex).toBe(13); // After "const obj = {" | |
| 397 | - expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'" | |
| 398 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 399 | - | |
| 400 | - // Verify the matched content preserves original formatting | |
| 401 | - const matchedContent = fileContent.substring( | |
| 402 | - result!.startIndex, | |
| 403 | - result!.endIndex, | |
| 404 | - ); | |
| 405 | - expect(matchedContent).toBe(` | |
| 406 | - key1 : 'value1', | |
| 407 | - key2 : 'value2', | |
| 408 | - key3 : 'value3'`); | |
| 409 | - }); | |
| 410 | - | |
| 411 | - it("should handle newlines and mixed whitespace", () => { | |
| 412 | - const fileContent = `function calc() { | |
| 413 | - | |
| 414 | - | |
| 415 | - let result = 0; | |
| 416 | - | |
| 417 | - result += 5; | |
| 418 | - | |
| 419 | - | |
| 420 | - return result; | |
| 421 | -}`; | |
| 422 | - const searchContent = `let result=0;result+=5;return result;`; | |
| 423 | - | |
| 424 | - const result = findSearchMatch(fileContent, searchContent); | |
| 425 | - | |
| 426 | - expect(result).not.toBeNull(); | |
| 427 | - expect(result!.startIndex).toBe(17); // After "function calc() {\n\n" | |
| 428 | - expect(result!.endIndex).toBe(78); // End of " return result;" | |
| 429 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 430 | - | |
| 431 | - // Verify the matched content includes all original whitespace | |
| 432 | - const matchedContent = fileContent.substring( | |
| 433 | - result!.startIndex, | |
| 434 | - result!.endIndex, | |
| 435 | - ); | |
| 436 | - expect(matchedContent).toBe(` | |
| 437 | - | |
| 438 | - | |
| 439 | - let result = 0; | |
| 440 | - | |
| 441 | - result += 5; | |
| 442 | - | |
| 443 | - | |
| 444 | - return result;`); | |
| 445 | - }); | |
| 446 | - | |
| 447 | - it("should prefer exact match over whitespace-ignored match", () => { | |
| 448 | - const fileContent = `const x=1; | |
| 449 | -const x = 1;`; | |
| 450 | - const searchContent = `const x=1;`; | |
| 451 | - | |
| 452 | - const result = findSearchMatch(fileContent, searchContent); | |
| 453 | - | |
| 454 | - // Should find the exact match first (at index 0), not the whitespace-ignored match | |
| 455 | - expect(result).toEqual({ | |
| 456 | - startIndex: 0, | |
| 457 | - endIndex: 10, | |
| 458 | - strategyName: "exactMatch", | |
| 459 | - }); | |
| 460 | - }); | |
| 461 | - | |
| 462 | - it("should handle empty content after whitespace removal", () => { | |
| 463 | - const fileContent = `function test() { | |
| 464 | - return 1; | |
| 465 | -}`; | |
| 466 | - const searchContent = `\n\n \t \n`; | |
| 467 | - | |
| 468 | - const result = findSearchMatch(fileContent, searchContent); | |
| 469 | - | |
| 470 | - // Should match at beginning for empty/whitespace-only content | |
| 471 | - expect(result).toEqual({ | |
| 472 | - startIndex: 0, | |
| 473 | - endIndex: 0, | |
| 474 | - strategyName: "emptySearch", | |
| 475 | - }); | |
| 476 | - }); | |
| 477 | - | |
| 478 | - it("should handle complex code blocks with different formatting", () => { | |
| 479 | - const fileContent = `class Example { | |
| 480 | - constructor(name) { | |
| 481 | - this.name = name; | |
| 482 | - this.value = 0; | |
| 483 | - } | |
| 484 | - | |
| 485 | - getValue() { | |
| 486 | - return this.value; | |
| 487 | - } | |
| 488 | -}`; | |
| 489 | - const searchContent = `constructor(name){ | |
| 490 | -this.name=name; | |
| 491 | -this.value=0; | |
| 492 | -}`; | |
| 493 | - | |
| 494 | - const result = findSearchMatch(fileContent, searchContent); | |
| 495 | - | |
| 496 | - expect(result).not.toBeNull(); | |
| 497 | - expect(result!.startIndex).toBe(15); // After "class Example {" | |
| 498 | - expect(result!.endIndex).toBe(95); // End of " }" | |
| 499 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 500 | - | |
| 501 | - // Verify the matched content preserves original formatting | |
| 502 | - const matchedContent = fileContent.substring( | |
| 503 | - result!.startIndex, | |
| 504 | - result!.endIndex, | |
| 505 | - ); | |
| 506 | - expect(matchedContent).toBe(` | |
| 507 | - constructor(name) { | |
| 508 | - this.name = name; | |
| 509 | - this.value = 0; | |
| 510 | - }`); | |
| 511 | - }); | |
| 512 | - | |
| 513 | - it("should return null when no close match exists", () => { | |
| 514 | - const fileContent = `function hello() { | |
| 515 | - console.log("world"); | |
| 516 | -}`; | |
| 517 | - const searchContent = `this has nothing to do with the other option`; | |
| 518 | - | |
| 519 | - const result = findSearchMatch(fileContent, searchContent); | |
| 520 | - | |
| 521 | - expect(result).toBeNull(); | |
| 522 | - }); | |
| 523 | - | |
| 524 | - it("should handle multiple potential matches and return first", () => { | |
| 525 | - const fileContent = `const a=1; | |
| 526 | -const a = 1; | |
| 527 | -const a = 1;`; | |
| 528 | - const searchContent = `const a=1;`; | |
| 529 | - | |
| 530 | - const result = findSearchMatch(fileContent, searchContent); | |
| 531 | - | |
| 532 | - // Should find the first exact match | |
| 533 | - expect(result).toEqual({ | |
| 534 | - startIndex: 0, | |
| 535 | - endIndex: 10, | |
| 536 | - strategyName: "exactMatch", | |
| 537 | - }); | |
| 538 | - }); | |
| 539 | -}); | |
| 540 | - | |
| 541 | -describe("Real-world scenarios", () => { | |
| 542 | - it("should match typical function replacement", () => { | |
| 543 | - const fileContent = `class Calculator { | |
| 544 | - constructor() { | |
| 545 | - this.result = 0; | |
| 546 | - } | |
| 547 | - | |
| 548 | - reset() { | |
| 549 | - this.result = 0; | |
| 550 | - return this; | |
| 551 | - } | |
| 552 | - | |
| 553 | - add(value) { | |
| 554 | - this.result += value; | |
| 555 | - return this; | |
| 556 | - } | |
| 557 | -}`; | |
| 558 | - const searchContent = ` reset() { | |
| 559 | - this.result = 0; | |
| 560 | - return this; | |
| 561 | - }`; | |
| 562 | - | |
| 563 | - const result = findSearchMatch(fileContent, searchContent); | |
| 564 | - | |
| 565 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 566 | - expect(result).toEqual({ | |
| 567 | - startIndex: expectedStart, | |
| 568 | - endIndex: expectedStart + searchContent.length, | |
| 569 | - strategyName: "exactMatch", | |
| 570 | - }); | |
| 571 | - }); | |
| 572 | - | |
| 573 | - it("should match import statement", () => { | |
| 574 | - const fileContent = `import React from 'react'; | |
| 575 | -import { useState, useEffect } from 'react'; | |
| 576 | -import './App.css'; | |
| 577 | - | |
| 578 | -function App() { | |
| 579 | - return <div>Hello World</div>; | |
| 580 | -}`; | |
| 581 | - const searchContent = `import { useState, useEffect } from 'react';`; | |
| 582 | - | |
| 583 | - const result = findSearchMatch(fileContent, searchContent); | |
| 584 | - | |
| 585 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 586 | - expect(result).toEqual({ | |
| 587 | - startIndex: expectedStart, | |
| 588 | - endIndex: expectedStart + searchContent.length, | |
| 589 | - strategyName: "exactMatch", | |
| 590 | - }); | |
| 591 | - }); | |
| 592 | - | |
| 593 | - it("should match comment block", () => { | |
| 594 | - const fileContent = `/** | |
| 595 | - * This is a comment | |
| 596 | - * that spans multiple lines | |
| 597 | - */ | |
| 598 | -function test() { | |
| 599 | - // Single line comment | |
| 600 | - return true; | |
| 601 | -}`; | |
| 602 | - const searchContent = `/** | |
| 603 | - * This is a comment | |
| 604 | - * that spans multiple lines | |
| 605 | - */`; | |
| 606 | - | |
| 607 | - const result = findSearchMatch(fileContent, searchContent); | |
| 608 | - | |
| 609 | - expect(result).toEqual({ | |
| 610 | - startIndex: 0, | |
| 611 | - endIndex: searchContent.length, | |
| 612 | - strategyName: "exactMatch", | |
| 613 | - }); | |
| 614 | - }); | |
| 615 | - | |
| 616 | - describe("Jaro-Winkler fuzzy matching", () => { | |
| 617 | - describe("Basic fuzzy matching", () => { | |
| 618 | - it("should find fuzzy match for similar strings", () => { | |
| 619 | - const fileContent = `function calculateSum(a, b) { | |
| 620 | - return a + b; | |
| 621 | -}`; | |
| 622 | - const searchContent = `function calculateSum(x, y) { | |
| 623 | - return x + y; | |
| 624 | -}`; | |
| 625 | - | |
| 626 | - const result = findSearchMatch(fileContent, searchContent); | |
| 627 | - | |
| 628 | - expect(result).not.toBeNull(); | |
| 629 | - }); | |
| 630 | - | |
| 631 | - it("should find fuzzy match with minor typos", () => { | |
| 632 | - const fileContent = `const message = "Hello World";`; | |
| 633 | - const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message' | |
| 634 | - | |
| 635 | - const result = findSearchMatch(fileContent, searchContent); | |
| 636 | - | |
| 637 | - expect(result).not.toBeNull(); | |
| 638 | - expect(result?.startIndex).toBe(0); | |
| 639 | - }); | |
| 640 | - | |
| 641 | - it("should find fuzzy match with different variable names", () => { | |
| 642 | - const fileContent = `let userAge = 25; | |
| 643 | -let userName = "John";`; | |
| 644 | - const searchContent = `let age = 25; | |
| 645 | -let name = "John";`; | |
| 646 | - | |
| 647 | - const result = findSearchMatch(fileContent, searchContent); | |
| 648 | - | |
| 649 | - expect(result).not.toBeNull(); | |
| 650 | - }); | |
| 651 | - | |
| 652 | - it("should find fuzzy match for similar function signature", () => { | |
| 653 | - const fileContent = `function processUserData(userData) { | |
| 654 | - validateInput(userData); | |
| 655 | - return formatOutput(userData); | |
| 656 | -}`; | |
| 657 | - const searchContent = `function processData(data) { | |
| 658 | - validateInput(data); | |
| 659 | - return formatOutput(data); | |
| 660 | -}`; | |
| 661 | - | |
| 662 | - const result = findSearchMatch(fileContent, searchContent); | |
| 663 | - | |
| 664 | - expect(result).not.toBeNull(); | |
| 665 | - }); | |
| 666 | - }); | |
| 667 | - | |
| 668 | - describe("Multi-line fuzzy matching", () => { | |
| 669 | - it("should find fuzzy match for multi-line blocks", () => { | |
| 670 | - const fileContent = `class Calculator { | |
| 671 | - constructor() { | |
| 672 | - this.result = 0; | |
| 673 | - } | |
| 674 | - | |
| 675 | - add(value) { | |
| 676 | - this.result += value; | |
| 677 | - return this; | |
| 678 | - } | |
| 679 | -}`; | |
| 680 | - const searchContent = `class Calculator { | |
| 681 | - constructor() { | |
| 682 | - this.value = 0; | |
| 683 | - } | |
| 684 | - | |
| 685 | - add(num) { | |
| 686 | - this.value += num; | |
| 687 | - return this; | |
| 688 | - } | |
| 689 | -}`; | |
| 690 | - | |
| 691 | - const result = findSearchMatch(fileContent, searchContent); | |
| 692 | - | |
| 693 | - expect(result).not.toBeNull(); | |
| 694 | - }); | |
| 695 | - | |
| 696 | - it("should find fuzzy match for partial blocks", () => { | |
| 697 | - const fileContent = `function processData(input) { | |
| 698 | - const validated = validateInput(input); | |
| 699 | - const processed = transformData(validated); | |
| 700 | - const result = formatOutput(processed); | |
| 701 | - return result; | |
| 702 | -}`; | |
| 703 | - const searchContent = `const validated = validateInput(input); | |
| 704 | - const processed = transformData(validated);`; | |
| 705 | - | |
| 706 | - const result = findSearchMatch(fileContent, searchContent); | |
| 707 | - | |
| 708 | - expect(result).not.toBeNull(); | |
| 709 | - }); | |
| 710 | - }); | |
| 711 | - | |
| 712 | - describe("Edge cases with fuzzy matching", () => { | |
| 713 | - it("should handle empty search content with fuzzy matching enabled", () => { | |
| 714 | - const fileContent = `function test() {}`; | |
| 715 | - const searchContent = ""; | |
| 716 | - | |
| 717 | - const result = findSearchMatch(fileContent, searchContent); | |
| 718 | - | |
| 719 | - expect(result).toEqual({ | |
| 720 | - startIndex: 0, | |
| 721 | - endIndex: 0, | |
| 722 | - strategyName: "emptySearch", | |
| 723 | - }); | |
| 724 | - }); | |
| 725 | - | |
| 726 | - it("should handle empty file content with fuzzy matching enabled", () => { | |
| 727 | - const fileContent = ""; | |
| 728 | - const searchContent = "function test() {}"; | |
| 729 | - | |
| 730 | - const result = findSearchMatch(fileContent, searchContent); | |
| 731 | - | |
| 732 | - expect(result).toBeNull(); | |
| 733 | - }); | |
| 734 | - | |
| 735 | - it("should prefer exact match over fuzzy match", () => { | |
| 736 | - const fileContent = `function test() { return true; } | |
| 737 | -function test() { return false; }`; | |
| 738 | - const searchContent = `function test() { return true; }`; | |
| 739 | - | |
| 740 | - const result = findSearchMatch(fileContent, searchContent); | |
| 741 | - | |
| 742 | - expect(result).not.toBeNull(); | |
| 743 | - expect(result?.startIndex).toBe(0); | |
| 744 | - }); | |
| 745 | - | |
| 746 | - it("should handle very short strings", () => { | |
| 747 | - const fileContent = `a b c`; | |
| 748 | - const searchContent = `a c`; | |
| 749 | - | |
| 750 | - const result = findSearchMatch(fileContent, searchContent); | |
| 751 | - | |
| 752 | - // Should not match due to low similarity | |
| 753 | - expect(result).toBeNull(); | |
| 754 | - }); | |
| 755 | - | |
| 756 | - it("should handle special characters in fuzzy matching", () => { | |
| 757 | - const fileContent = `const regex = /[a-zA-Z]+/g; | |
| 758 | -const symbols = !@#$%^&*();`; | |
| 759 | - const searchContent = `const regex = /[a-zA-Z0-9]+/g; | |
| 760 | -const symbols = !@#$%^&*();`; | |
| 761 | - | |
| 762 | - const result = findSearchMatch(fileContent, searchContent); | |
| 763 | - | |
| 764 | - expect(result).not.toBeNull(); | |
| 765 | - }); | |
| 766 | - }); | |
| 767 | - }); | |
| 768 | -}); |
modified core/edit/searchAndReplace/findSearchMatch.ts +87 −67
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | interface BasicMatchResult { |
| 5 | 5 | /** The starting character index of the match in the file content */ |
| 6 | 6 | startIndex: number; |
| 7 | - /** The ending character index of the match in the file content */ | |
| 7 | + /** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/ | |
| 8 | 8 | endIndex: number; |
| 9 | 9 | } |
| 10 | 10 | |
| @@ -43,48 +43,20 @@ | ||
| 43 | 43 | |
| 44 | 44 | /** |
| 45 | 45 | * Trimmed content matching strategy |
| 46 | - * Finds content where the search content (when trimmed) matches content in the file, | |
| 47 | - * and returns the span that includes the file content's whitespace | |
| 48 | 46 | */ |
| 49 | 47 | function trimmedMatch( |
| 50 | 48 | fileContent: string, |
| 51 | 49 | searchContent: string, |
| 52 | 50 | ): BasicMatchResult | null { |
| 53 | 51 | const trimmedSearchContent = searchContent.trim(); |
| 54 | - | |
| 55 | - // Don't apply if search content has no leading/trailing whitespace to trim | |
| 56 | - if (trimmedSearchContent === searchContent) { | |
| 57 | - return null; | |
| 58 | - } | |
| 59 | - | |
| 60 | - // Don't match if trimmed content is empty | |
| 61 | - if (trimmedSearchContent === "") { | |
| 62 | - return null; | |
| 63 | - } | |
| 64 | - | |
| 65 | - // Look for the trimmed content in the file | |
| 66 | - const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent); | |
| 67 | - if (trimmedContentIndex === -1) { | |
| 68 | - return null; | |
| 69 | - } | |
| 70 | - | |
| 71 | - // Find the boundaries that include surrounding whitespace (but not newlines) | |
| 72 | - // Look backwards for horizontal whitespace (spaces and tabs) | |
| 73 | - let startIndex = trimmedContentIndex; | |
| 74 | - while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) { | |
| 75 | - startIndex--; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Look forwards for horizontal whitespace (spaces and tabs) | |
| 79 | - let endIndex = trimmedContentIndex + trimmedSearchContent.length; | |
| 80 | - while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) { | |
| 81 | - endIndex++; | |
| 52 | + const trimmedIndex = fileContent.indexOf(trimmedSearchContent); | |
| 53 | + if (trimmedIndex !== -1) { | |
| 54 | + return { | |
| 55 | + startIndex: trimmedIndex, | |
| 56 | + endIndex: trimmedIndex + trimmedSearchContent.length, | |
| 57 | + }; | |
| 82 | 58 | } |
| 83 | - | |
| 84 | - return { | |
| 85 | - startIndex, | |
| 86 | - endIndex, | |
| 87 | - }; | |
| 59 | + return null; | |
| 88 | 60 | } |
| 89 | 61 | |
| 90 | 62 | /** |
| @@ -109,32 +81,38 @@ | ||
| 109 | 81 | } |
| 110 | 82 | |
| 111 | 83 | // Map the stripped position back to the original file content |
| 112 | - let originalStartIndex = 0; | |
| 84 | + let originalStartIndex = -1; | |
| 113 | 85 | let strippedCharCount = 0; |
| 114 | 86 | |
| 115 | - // Find the original position by counting non-whitespace characters | |
| 87 | + // Find the original start position by counting non-whitespace characters | |
| 116 | 88 | for (let i = 0; i < fileContent.length; i++) { |
| 117 | - if (strippedCharCount === strippedIndex) { | |
| 118 | - originalStartIndex = i; | |
| 119 | - break; | |
| 120 | - } | |
| 121 | 89 | if (!/\s/.test(fileContent[i])) { |
| 90 | + if (strippedCharCount === strippedIndex) { | |
| 91 | + originalStartIndex = i; | |
| 92 | + break; | |
| 93 | + } | |
| 122 | 94 | strippedCharCount++; |
| 123 | 95 | } |
| 124 | 96 | } |
| 125 | 97 | |
| 126 | - // Find the end position by counting the length of the search content | |
| 98 | + if (originalStartIndex === -1) { | |
| 99 | + return null; // Should not happen if strippedIndex was valid | |
| 100 | + } | |
| 101 | + | |
| 102 | + // Find the end position by counting through all characters (including whitespace) | |
| 103 | + // that correspond to the stripped search content length | |
| 127 | 104 | let originalEndIndex = originalStartIndex; |
| 128 | - let matchedChars = 0; | |
| 105 | + let matchedNonWhitespaceChars = 0; | |
| 129 | 106 | |
| 130 | - for ( | |
| 131 | - let i = originalStartIndex; | |
| 132 | - i < fileContent.length && matchedChars < strippedSearchContent.length; | |
| 133 | - i++ | |
| 134 | - ) { | |
| 107 | + for (let i = originalStartIndex; i < fileContent.length; i++) { | |
| 135 | 108 | if (!/\s/.test(fileContent[i])) { |
| 136 | - matchedChars++; | |
| 109 | + matchedNonWhitespaceChars++; | |
| 110 | + if (matchedNonWhitespaceChars === strippedSearchContent.length) { | |
| 111 | + originalEndIndex = i + 1; | |
| 112 | + break; | |
| 113 | + } | |
| 137 | 114 | } |
| 115 | + // Always update end index to include current position (whether whitespace or not) | |
| 138 | 116 | originalEndIndex = i + 1; |
| 139 | 117 | } |
| 140 | 118 | |
| @@ -146,6 +124,7 @@ | ||
| 146 | 124 | |
| 147 | 125 | /** |
| 148 | 126 | * Calculate the Jaro similarity between two strings |
| 127 | + * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match | |
| 149 | 128 | */ |
| 150 | 129 | function jaroSimilarity(s1: string, s2: string): number { |
| 151 | 130 | if (s1 === s2) return 1.0; |
| @@ -306,7 +285,7 @@ | ||
| 306 | 285 | { strategy: exactMatch, name: "exactMatch" }, |
| 307 | 286 | { strategy: trimmedMatch, name: "trimmedMatch" }, |
| 308 | 287 | { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, |
| 309 | - { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, | |
| 288 | + // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, | |
| 310 | 289 | ]; |
| 311 | 290 | |
| 312 | 291 | /** |
| @@ -326,24 +305,10 @@ | ||
| 326 | 305 | fileContent: string, |
| 327 | 306 | searchContent: string, |
| 328 | 307 | ): SearchMatchResult | null { |
| 329 | - // Handle truly empty search content | |
| 330 | - if (searchContent === "") { | |
| 331 | - return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; | |
| 332 | - } | |
| 333 | - | |
| 334 | - // Handle whitespace-only search content that trims to empty | |
| 335 | 308 | const trimmedSearchContent = searchContent.trim(); |
| 309 | + | |
| 336 | 310 | if (trimmedSearchContent === "") { |
| 337 | - // Check if the whitespace-only search content has an exact match first | |
| 338 | - const exactIndex = fileContent.indexOf(searchContent); | |
| 339 | - if (exactIndex !== -1) { | |
| 340 | - return { | |
| 341 | - startIndex: exactIndex, | |
| 342 | - endIndex: exactIndex + searchContent.length, | |
| 343 | - strategyName: "exactMatch", | |
| 344 | - }; | |
| 345 | - } | |
| 346 | - // If no exact match for whitespace-only content, treat as empty search | |
| 311 | + // Empty search content matches the beginning of the file | |
| 347 | 312 | return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; |
| 348 | 313 | } |
| 349 | 314 | |
| @@ -357,3 +322,58 @@ | ||
| 357 | 322 | |
| 358 | 323 | return null; |
| 359 | 324 | } |
| 325 | + | |
| 326 | +/** | |
| 327 | + * Find all matches for search content in file content. | |
| 328 | + * Uses the same matching strategies as findSearchMatch, applied iteratively. | |
| 329 | + * | |
| 330 | + * @param fileContent - The complete content of the file to search in | |
| 331 | + * @param searchContent - The content to search for | |
| 332 | + * @returns Array of match results with character positions, empty array if no matches found | |
| 333 | + */ | |
| 334 | +export function findSearchMatches( | |
| 335 | + fileContent: string, | |
| 336 | + searchContent: string, | |
| 337 | +): SearchMatchResult[] { | |
| 338 | + const matches: SearchMatchResult[] = []; | |
| 339 | + | |
| 340 | + // Special case: empty search string always matches at position 0 | |
| 341 | + if (searchContent.trim() === "") { | |
| 342 | + return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }]; | |
| 343 | + } | |
| 344 | + | |
| 345 | + let remainingContent = fileContent; | |
| 346 | + let currentOffset = 0; | |
| 347 | + | |
| 348 | + while (remainingContent.length > 0) { | |
| 349 | + const match = findSearchMatch(remainingContent, searchContent); | |
| 350 | + | |
| 351 | + if (match === null) { | |
| 352 | + break; | |
| 353 | + } | |
| 354 | + | |
| 355 | + // Adjust match positions to account for the current offset | |
| 356 | + const adjustedMatch: SearchMatchResult = { | |
| 357 | + startIndex: match.startIndex + currentOffset, | |
| 358 | + endIndex: match.endIndex + currentOffset, | |
| 359 | + strategyName: match.strategyName, | |
| 360 | + }; | |
| 361 | + | |
| 362 | + // Prevent infinite loops by ensuring we're making progress | |
| 363 | + // If the new match starts at or before the last match's start position, break | |
| 364 | + if ( | |
| 365 | + matches.length > 0 && | |
| 366 | + adjustedMatch.startIndex <= matches[matches.length - 1].startIndex | |
| 367 | + ) { | |
| 368 | + break; | |
| 369 | + } | |
| 370 | + | |
| 371 | + matches.push(adjustedMatch); | |
| 372 | + | |
| 373 | + // Update offset and truncate content after the current match | |
| 374 | + currentOffset = adjustedMatch.endIndex; | |
| 375 | + remainingContent = fileContent.slice(currentOffset); | |
| 376 | + } | |
| 377 | + | |
| 378 | + return matches; | |
| 379 | +} |
added core/edit/searchAndReplace/findSearchMatch.vitest.ts +571 −0
| @@ -0,0 +1,571 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { findSearchMatch } from "./findSearchMatch"; | |
| 3 | + | |
| 4 | +describe("findSearchMatch", () => { | |
| 5 | + describe("Empty search content", () => { | |
| 6 | + it("should return position 0 for empty string", () => { | |
| 7 | + const result = findSearchMatch("some file content", ""); | |
| 8 | + expect(result).toEqual({ | |
| 9 | + startIndex: 0, | |
| 10 | + endIndex: 0, | |
| 11 | + strategyName: "emptySearch", | |
| 12 | + }); | |
| 13 | + }); | |
| 14 | + | |
| 15 | + it("should return position 0 for whitespace-only string", () => { | |
| 16 | + const result = findSearchMatch("some file content", " \n\t "); | |
| 17 | + expect(result).toEqual({ | |
| 18 | + startIndex: 0, | |
| 19 | + endIndex: 0, | |
| 20 | + strategyName: "emptySearch", | |
| 21 | + }); | |
| 22 | + }); | |
| 23 | + | |
| 24 | + it("should handle empty file content with empty search", () => { | |
| 25 | + const result = findSearchMatch("", ""); | |
| 26 | + expect(result).toEqual({ | |
| 27 | + startIndex: 0, | |
| 28 | + endIndex: 0, | |
| 29 | + strategyName: "emptySearch", | |
| 30 | + }); | |
| 31 | + }); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + describe("Exact match strategy", () => { | |
| 35 | + it("should find exact match at beginning of file", () => { | |
| 36 | + const fileContent = "hello world"; | |
| 37 | + const searchContent = "hello"; | |
| 38 | + const result = findSearchMatch(fileContent, searchContent); | |
| 39 | + | |
| 40 | + expect(result).toEqual({ | |
| 41 | + startIndex: 0, | |
| 42 | + endIndex: 5, | |
| 43 | + strategyName: "exactMatch", | |
| 44 | + }); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should find exact match in middle of file", () => { | |
| 48 | + const fileContent = "hello world test"; | |
| 49 | + const searchContent = "world"; | |
| 50 | + const result = findSearchMatch(fileContent, searchContent); | |
| 51 | + | |
| 52 | + expect(result).toEqual({ | |
| 53 | + startIndex: 6, | |
| 54 | + endIndex: 11, | |
| 55 | + strategyName: "exactMatch", | |
| 56 | + }); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + it("should find exact match at end of file", () => { | |
| 60 | + const fileContent = "hello world"; | |
| 61 | + const searchContent = "world"; | |
| 62 | + const result = findSearchMatch(fileContent, searchContent); | |
| 63 | + | |
| 64 | + expect(result).toEqual({ | |
| 65 | + startIndex: 6, | |
| 66 | + endIndex: 11, | |
| 67 | + strategyName: "exactMatch", | |
| 68 | + }); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("should find multi-line exact match", () => { | |
| 72 | + const fileContent = "line1\nline2\nline3"; | |
| 73 | + const searchContent = "line2\nline3"; | |
| 74 | + const result = findSearchMatch(fileContent, searchContent); | |
| 75 | + | |
| 76 | + expect(result).toEqual({ | |
| 77 | + startIndex: 6, | |
| 78 | + endIndex: 17, | |
| 79 | + strategyName: "exactMatch", | |
| 80 | + }); | |
| 81 | + }); | |
| 82 | + | |
| 83 | + it("should handle exact match with special characters", () => { | |
| 84 | + const fileContent = 'function test() { return "hello"; }'; | |
| 85 | + const searchContent = '{ return "hello"; }'; | |
| 86 | + const result = findSearchMatch(fileContent, searchContent); | |
| 87 | + | |
| 88 | + expect(result).toEqual({ | |
| 89 | + startIndex: 16, | |
| 90 | + endIndex: 35, | |
| 91 | + strategyName: "exactMatch", | |
| 92 | + }); | |
| 93 | + }); | |
| 94 | + | |
| 95 | + it("should find first occurrence when multiple matches exist", () => { | |
| 96 | + const fileContent = "test test test"; | |
| 97 | + const searchContent = "test"; | |
| 98 | + const result = findSearchMatch(fileContent, searchContent); | |
| 99 | + | |
| 100 | + expect(result).toEqual({ | |
| 101 | + startIndex: 0, | |
| 102 | + endIndex: 4, | |
| 103 | + strategyName: "exactMatch", | |
| 104 | + }); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + it("should handle case-sensitive matching", () => { | |
| 108 | + const fileContent = "Hello World"; | |
| 109 | + const searchContent = "hello"; | |
| 110 | + const result = findSearchMatch(fileContent, searchContent); | |
| 111 | + | |
| 112 | + // Should not match due to case sensitivity, will fall through to other strategies | |
| 113 | + expect(result).toBeNull(); | |
| 114 | + }); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + describe("Trimmed match strategy fallback", () => { | |
| 118 | + it("should find match when search content has leading/trailing whitespace", () => { | |
| 119 | + const fileContent = "hello world"; | |
| 120 | + const searchContent = " hello "; | |
| 121 | + const result = findSearchMatch(fileContent, searchContent); | |
| 122 | + | |
| 123 | + expect(result).toEqual({ | |
| 124 | + startIndex: 0, | |
| 125 | + endIndex: 5, | |
| 126 | + strategyName: "trimmedMatch", | |
| 127 | + }); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should find match when search content has tabs and newlines", () => { | |
| 131 | + const fileContent = "function test() {}"; | |
| 132 | + const searchContent = "\t\nfunction test()\n\t"; | |
| 133 | + const result = findSearchMatch(fileContent, searchContent); | |
| 134 | + | |
| 135 | + expect(result).toEqual({ | |
| 136 | + startIndex: 0, | |
| 137 | + endIndex: 15, | |
| 138 | + strategyName: "trimmedMatch", | |
| 139 | + }); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("should handle complex whitespace trimming", () => { | |
| 143 | + const fileContent = "const x = 5;"; | |
| 144 | + const searchContent = " \n\t const x = 5; \t\n "; | |
| 145 | + const result = findSearchMatch(fileContent, searchContent); | |
| 146 | + | |
| 147 | + expect(result).toEqual({ | |
| 148 | + startIndex: 0, | |
| 149 | + endIndex: 12, | |
| 150 | + strategyName: "trimmedMatch", | |
| 151 | + }); | |
| 152 | + }); | |
| 153 | + }); | |
| 154 | + | |
| 155 | + describe("Whitespace ignored strategy fallback", () => { | |
| 156 | + it("should match content with different whitespace formatting", () => { | |
| 157 | + const fileContent = "function test() {\n return true;\n}"; | |
| 158 | + const searchContent = "function test(){return true;}"; | |
| 159 | + const result = findSearchMatch(fileContent, searchContent); | |
| 160 | + | |
| 161 | + expect(result).toEqual({ | |
| 162 | + startIndex: 0, | |
| 163 | + endIndex: 34, | |
| 164 | + strategyName: "whitespaceIgnoredMatch", | |
| 165 | + }); | |
| 166 | + }); | |
| 167 | + | |
| 168 | + it("should handle mixed whitespace differences", () => { | |
| 169 | + const fileContent = "if (condition) {\n doSomething();\n}"; | |
| 170 | + const searchContent = "if(condition){doSomething();}"; | |
| 171 | + const result = findSearchMatch(fileContent, searchContent); | |
| 172 | + | |
| 173 | + expect(result).toEqual({ | |
| 174 | + startIndex: 0, | |
| 175 | + endIndex: 37, | |
| 176 | + strategyName: "whitespaceIgnoredMatch", | |
| 177 | + }); | |
| 178 | + }); | |
| 179 | + | |
| 180 | + it("should match with tabs vs spaces differences", () => { | |
| 181 | + const fileContent = "function test() {\n\treturn 42;\n}"; | |
| 182 | + const searchContent = "function test() {\n return 42;\n}"; | |
| 183 | + const result = findSearchMatch(fileContent, searchContent); | |
| 184 | + | |
| 185 | + expect(result).toEqual({ | |
| 186 | + startIndex: 0, | |
| 187 | + endIndex: 31, | |
| 188 | + strategyName: "whitespaceIgnoredMatch", | |
| 189 | + }); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + it("should handle partial matches within larger content", () => { | |
| 193 | + const fileContent = "before\nfunction test() {\n return true;\n}\nafter"; | |
| 194 | + const searchContent = "function test(){return true;}"; | |
| 195 | + const result = findSearchMatch(fileContent, searchContent); | |
| 196 | + | |
| 197 | + expect(result).toEqual({ | |
| 198 | + startIndex: 7, | |
| 199 | + endIndex: 41, | |
| 200 | + strategyName: "whitespaceIgnoredMatch", | |
| 201 | + }); | |
| 202 | + }); | |
| 203 | + | |
| 204 | + it("should recognize empty search", () => { | |
| 205 | + const fileContent = "some content"; | |
| 206 | + const searchContent = " \t\n "; | |
| 207 | + const result = findSearchMatch(fileContent, searchContent); | |
| 208 | + | |
| 209 | + expect(result).toEqual({ | |
| 210 | + startIndex: 0, | |
| 211 | + endIndex: 0, | |
| 212 | + strategyName: "emptySearch", | |
| 213 | + }); | |
| 214 | + }); | |
| 215 | + | |
| 216 | + it("should handle complex nested structures with whitespace differences", () => { | |
| 217 | + const fileContent = `{ | |
| 218 | + "key": "value", | |
| 219 | + "nested": { | |
| 220 | + "prop": 123 | |
| 221 | + } | |
| 222 | +}`; | |
| 223 | + const searchContent = '{"key":"value","nested":{"prop":123}}'; | |
| 224 | + const result = findSearchMatch(fileContent, searchContent); | |
| 225 | + | |
| 226 | + expect(result).toEqual({ | |
| 227 | + startIndex: 0, | |
| 228 | + endIndex: 55, | |
| 229 | + strategyName: "whitespaceIgnoredMatch", | |
| 230 | + }); | |
| 231 | + }); | |
| 232 | + | |
| 233 | + it("should match content in middle of file with complex indentation", () => { | |
| 234 | + const fileContent = `import React from 'react'; | |
| 235 | + | |
| 236 | +function MyComponent() { | |
| 237 | + const handleClick = () => { | |
| 238 | + console.log('clicked'); | |
| 239 | + }; | |
| 240 | + return <button onClick={handleClick}>Click me</button>; | |
| 241 | +} | |
| 242 | + | |
| 243 | +export default MyComponent;`; | |
| 244 | + const searchContent = `const handleClick=()=>{console.log('clicked');};`; | |
| 245 | + const result = findSearchMatch(fileContent, searchContent); | |
| 246 | + | |
| 247 | + expect(result).toEqual({ | |
| 248 | + startIndex: 55, | |
| 249 | + endIndex: 115, | |
| 250 | + strategyName: "whitespaceIgnoredMatch", | |
| 251 | + }); | |
| 252 | + }); | |
| 253 | + | |
| 254 | + it("should handle matches with mixed line endings and special characters", () => { | |
| 255 | + const fileContent = `<!DOCTYPE html>\r\n<html>\r\n <body>\r\n <div id="app">\r\n <p>Hello & goodbye</p>\r\n </div>\r\n </body>\r\n</html>`; | |
| 256 | + const searchContent = `<divid="app"><p>Hello&goodbye</p></div>`; | |
| 257 | + const result = findSearchMatch(fileContent, searchContent); | |
| 258 | + | |
| 259 | + expect(result).toEqual({ | |
| 260 | + startIndex: 39, | |
| 261 | + endIndex: 95, | |
| 262 | + strategyName: "whitespaceIgnoredMatch", | |
| 263 | + }); | |
| 264 | + }); | |
| 265 | + | |
| 266 | + it("should match content surrounded by different types of whitespace", () => { | |
| 267 | + 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};`; | |
| 268 | + const searchContent = `address:{street:"MainSt",city:"NYC"}`; | |
| 269 | + const result = findSearchMatch(fileContent, searchContent); | |
| 270 | + | |
| 271 | + expect(result).toEqual({ | |
| 272 | + startIndex: 45, | |
| 273 | + endIndex: 96, | |
| 274 | + strategyName: "whitespaceIgnoredMatch", | |
| 275 | + }); | |
| 276 | + }); | |
| 277 | + | |
| 278 | + // IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both | |
| 279 | + it("should handle unicode characters with whitespace differences", () => { | |
| 280 | + const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`; | |
| 281 | + const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`; | |
| 282 | + const result = findSearchMatch(fileContent, searchContent); | |
| 283 | + | |
| 284 | + expect(result).toEqual({ | |
| 285 | + startIndex: 44, | |
| 286 | + endIndex: 89, | |
| 287 | + strategyName: "whitespaceIgnoredMatch", | |
| 288 | + }); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + it("should match across multiple nested blocks with varying indentation", () => { | |
| 292 | + 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}`; | |
| 293 | + const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`; | |
| 294 | + const result = findSearchMatch(fileContent, searchContent); | |
| 295 | + | |
| 296 | + expect(result).toEqual({ | |
| 297 | + startIndex: 43, | |
| 298 | + endIndex: 132, | |
| 299 | + strategyName: "whitespaceIgnoredMatch", | |
| 300 | + }); | |
| 301 | + }); | |
| 302 | + | |
| 303 | + it("should handle regex-like patterns with escaped characters", () => { | |
| 304 | + const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`; | |
| 305 | + const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`; | |
| 306 | + const result = findSearchMatch(fileContent, searchContent); | |
| 307 | + | |
| 308 | + expect(result).toEqual({ | |
| 309 | + startIndex: 29, | |
| 310 | + endIndex: 110, | |
| 311 | + strategyName: "whitespaceIgnoredMatch", | |
| 312 | + }); | |
| 313 | + }); | |
| 314 | + | |
| 315 | + it("should match SQL-like content with varying whitespace", () => { | |
| 316 | + 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;`; | |
| 317 | + const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`; | |
| 318 | + const result = findSearchMatch(fileContent, searchContent); | |
| 319 | + | |
| 320 | + expect(result).toEqual({ | |
| 321 | + startIndex: 0, | |
| 322 | + endIndex: 89, | |
| 323 | + strategyName: "whitespaceIgnoredMatch", | |
| 324 | + }); | |
| 325 | + }); | |
| 326 | + | |
| 327 | + it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => { | |
| 328 | + const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`; | |
| 329 | + const searchContent = `functionprocessdata(input){returninput.trim();}`; | |
| 330 | + const result = findSearchMatch(fileContent, searchContent); | |
| 331 | + | |
| 332 | + expect(result).toEqual({ | |
| 333 | + startIndex: 0, | |
| 334 | + endIndex: 56, | |
| 335 | + strategyName: "whitespaceIgnoredMatch", | |
| 336 | + }); | |
| 337 | + }); | |
| 338 | + | |
| 339 | + it("should match content with Windows-style CRLF line endings", () => { | |
| 340 | + 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.`; | |
| 341 | + const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`; | |
| 342 | + const result = findSearchMatch(fileContent, searchContent); | |
| 343 | + | |
| 344 | + expect(result).toEqual({ | |
| 345 | + startIndex: 37, | |
| 346 | + endIndex: 105, | |
| 347 | + strategyName: "whitespaceIgnoredMatch", | |
| 348 | + }); | |
| 349 | + }); | |
| 350 | + | |
| 351 | + it("should handle deeply nested JSON with mixed formatting", () => { | |
| 352 | + 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}`; | |
| 353 | + const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`; | |
| 354 | + const result = findSearchMatch(fileContent, searchContent); | |
| 355 | + | |
| 356 | + expect(result).toEqual({ | |
| 357 | + startIndex: 87, | |
| 358 | + endIndex: 243, | |
| 359 | + strategyName: "whitespaceIgnoredMatch", | |
| 360 | + }); | |
| 361 | + }); | |
| 362 | + | |
| 363 | + it("should match XML content with attribute spacing differences", () => { | |
| 364 | + const fileContent = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n <item id = \"1\" type= \"primary\" >\n <name>Test Item</name>\n <value unit=\"px\" >100</value>\n </item>\n</root>`; | |
| 365 | + const searchContent = `<itemid=\"1\"type=\"primary\"><name>TestItem</name><valueunit=\"px\">100</value></item>`; | |
| 366 | + const result = findSearchMatch(fileContent, searchContent); | |
| 367 | + | |
| 368 | + expect(result).toEqual({ | |
| 369 | + startIndex: 48, | |
| 370 | + endIndex: 155, | |
| 371 | + strategyName: "whitespaceIgnoredMatch", | |
| 372 | + }); | |
| 373 | + }); | |
| 374 | + | |
| 375 | + it("should handle mathematical expressions with varying spacing", () => { | |
| 376 | + 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 );`; | |
| 377 | + const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`; | |
| 378 | + const result = findSearchMatch(fileContent, searchContent); | |
| 379 | + | |
| 380 | + expect(result).toEqual({ | |
| 381 | + startIndex: 36, | |
| 382 | + endIndex: 142, | |
| 383 | + strategyName: "whitespaceIgnoredMatch", | |
| 384 | + }); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + it("should match across comments and code with whitespace variations", () => { | |
| 388 | + 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}`; | |
| 389 | + const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`; | |
| 390 | + const result = findSearchMatch(fileContent, searchContent); | |
| 391 | + | |
| 392 | + expect(result).toEqual({ | |
| 393 | + startIndex: 0, | |
| 394 | + endIndex: 205, | |
| 395 | + strategyName: "whitespaceIgnoredMatch", | |
| 396 | + }); | |
| 397 | + }); | |
| 398 | + }); | |
| 399 | + | |
| 400 | + describe("No match scenarios", () => { | |
| 401 | + it("should return null when no strategy finds a match", () => { | |
| 402 | + const fileContent = "hello world"; | |
| 403 | + const searchContent = "goodbye"; | |
| 404 | + const result = findSearchMatch(fileContent, searchContent); | |
| 405 | + | |
| 406 | + expect(result).toBeNull(); | |
| 407 | + }); | |
| 408 | + | |
| 409 | + it("should return null for completely different content", () => { | |
| 410 | + const fileContent = "function test() { return true; }"; | |
| 411 | + const searchContent = "class MyClass { }"; | |
| 412 | + const result = findSearchMatch(fileContent, searchContent); | |
| 413 | + | |
| 414 | + expect(result).toBeNull(); | |
| 415 | + }); | |
| 416 | + | |
| 417 | + it("should return null when search content is longer than file content", () => { | |
| 418 | + const fileContent = "short"; | |
| 419 | + const searchContent = "this is much longer than the file content"; | |
| 420 | + const result = findSearchMatch(fileContent, searchContent); | |
| 421 | + | |
| 422 | + expect(result).toBeNull(); | |
| 423 | + }); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + describe("Edge cases", () => { | |
| 427 | + it("should handle empty file content with non-empty search", () => { | |
| 428 | + const fileContent = ""; | |
| 429 | + const searchContent = "something"; | |
| 430 | + const result = findSearchMatch(fileContent, searchContent); | |
| 431 | + | |
| 432 | + expect(result).toBeNull(); | |
| 433 | + }); | |
| 434 | + | |
| 435 | + it("should handle single character matches", () => { | |
| 436 | + const fileContent = "a"; | |
| 437 | + const searchContent = "a"; | |
| 438 | + const result = findSearchMatch(fileContent, searchContent); | |
| 439 | + | |
| 440 | + expect(result).toEqual({ | |
| 441 | + startIndex: 0, | |
| 442 | + endIndex: 1, | |
| 443 | + strategyName: "exactMatch", | |
| 444 | + }); | |
| 445 | + }); | |
| 446 | + | |
| 447 | + it("should handle unicode characters", () => { | |
| 448 | + const fileContent = "Hello 🌍 World"; | |
| 449 | + const searchContent = "🌍"; | |
| 450 | + const result = findSearchMatch(fileContent, searchContent); | |
| 451 | + | |
| 452 | + expect(result).toEqual({ | |
| 453 | + startIndex: 6, | |
| 454 | + endIndex: 8, // Unicode emoji takes 2 character positions | |
| 455 | + strategyName: "exactMatch", | |
| 456 | + }); | |
| 457 | + }); | |
| 458 | + | |
| 459 | + it("should handle newlines and carriage returns", () => { | |
| 460 | + const fileContent = "line1\r\nline2\nline3"; | |
| 461 | + const searchContent = "\r\nline2"; | |
| 462 | + const result = findSearchMatch(fileContent, searchContent); | |
| 463 | + | |
| 464 | + expect(result).toEqual({ | |
| 465 | + startIndex: 5, | |
| 466 | + endIndex: 12, | |
| 467 | + strategyName: "exactMatch", | |
| 468 | + }); | |
| 469 | + }); | |
| 470 | + | |
| 471 | + it("should handle very long content efficiently", () => { | |
| 472 | + const longContent = "a".repeat(10000) + "target" + "b".repeat(10000); | |
| 473 | + const searchContent = "target"; | |
| 474 | + const result = findSearchMatch(longContent, searchContent); | |
| 475 | + | |
| 476 | + expect(result).toEqual({ | |
| 477 | + startIndex: 10000, | |
| 478 | + endIndex: 10006, | |
| 479 | + strategyName: "exactMatch", | |
| 480 | + }); | |
| 481 | + }); | |
| 482 | + }); | |
| 483 | + | |
| 484 | + describe("Strategy precedence", () => { | |
| 485 | + it("should prefer exact match over trimmed match", () => { | |
| 486 | + const fileContent = "hello world hello"; | |
| 487 | + const searchContent = "hello"; // This exists exactly, so should use exactMatch | |
| 488 | + const result = findSearchMatch(fileContent, searchContent); | |
| 489 | + | |
| 490 | + expect(result).toEqual({ | |
| 491 | + startIndex: 0, | |
| 492 | + endIndex: 5, | |
| 493 | + strategyName: "exactMatch", | |
| 494 | + }); | |
| 495 | + }); | |
| 496 | + | |
| 497 | + it("should prefer trimmed match over whitespace ignored match", () => { | |
| 498 | + // Set up content where trimmed match would work but whitespace ignored would also work | |
| 499 | + const fileContent = "hello world"; | |
| 500 | + const searchContent = " hello "; // Has whitespace but trimmed version exists | |
| 501 | + const result = findSearchMatch(fileContent, searchContent); | |
| 502 | + | |
| 503 | + expect(result).toEqual({ | |
| 504 | + startIndex: 0, | |
| 505 | + endIndex: 5, | |
| 506 | + strategyName: "trimmedMatch", | |
| 507 | + }); | |
| 508 | + }); | |
| 509 | + | |
| 510 | + it("should fall back through strategies in correct order", () => { | |
| 511 | + const fileContent = "function test() {\n return true;\n}"; | |
| 512 | + const searchContent = " function test(){return true;} "; // Needs whitespace ignored | |
| 513 | + const result = findSearchMatch(fileContent, searchContent); | |
| 514 | + | |
| 515 | + expect(result).toEqual({ | |
| 516 | + startIndex: 0, | |
| 517 | + endIndex: 34, | |
| 518 | + strategyName: "whitespaceIgnoredMatch", | |
| 519 | + }); | |
| 520 | + }); | |
| 521 | + }); | |
| 522 | + | |
| 523 | + describe("Real-world code examples", () => { | |
| 524 | + it("should handle JavaScript function matching", () => { | |
| 525 | + const fileContent = `function calculateSum(a, b) { | |
| 526 | + const result = a + b; | |
| 527 | + return result; | |
| 528 | +}`; | |
| 529 | + const searchContent = `function calculateSum(a, b) { | |
| 530 | + const result = a + b; | |
| 531 | + return result; | |
| 532 | +}`; | |
| 533 | + const result = findSearchMatch(fileContent, searchContent); | |
| 534 | + | |
| 535 | + expect(result).toEqual({ | |
| 536 | + startIndex: 0, | |
| 537 | + endIndex: 72, | |
| 538 | + strategyName: "exactMatch", | |
| 539 | + }); | |
| 540 | + }); | |
| 541 | + | |
| 542 | + it("should handle HTML tag matching with different formatting", () => { | |
| 543 | + const fileContent = `<div class="container"> | |
| 544 | + <p>Hello World</p> | |
| 545 | +</div>`; | |
| 546 | + const searchContent = `<div class="container"><p>Hello World</p></div>`; | |
| 547 | + const result = findSearchMatch(fileContent, searchContent); | |
| 548 | + | |
| 549 | + expect(result).toEqual({ | |
| 550 | + startIndex: 0, | |
| 551 | + endIndex: 51, | |
| 552 | + strategyName: "whitespaceIgnoredMatch", | |
| 553 | + }); | |
| 554 | + }); | |
| 555 | + | |
| 556 | + it("should handle CSS rule matching", () => { | |
| 557 | + const fileContent = `.button { | |
| 558 | + background-color: blue; | |
| 559 | + color: white; | |
| 560 | +}`; | |
| 561 | + const searchContent = `.button{background-color:blue;color:white;}`; | |
| 562 | + const result = findSearchMatch(fileContent, searchContent); | |
| 563 | + | |
| 564 | + expect(result).toEqual({ | |
| 565 | + startIndex: 0, | |
| 566 | + endIndex: 53, | |
| 567 | + strategyName: "whitespaceIgnoredMatch", | |
| 568 | + }); | |
| 569 | + }); | |
| 570 | + }); | |
| 571 | +}); |
added core/edit/searchAndReplace/findSearchMatches.test.ts +368 −0
| @@ -0,0 +1,368 @@ | ||
| 1 | +import { findSearchMatches } from "./findSearchMatch"; | |
| 2 | + | |
| 3 | +describe("findSearchMatches", () => { | |
| 4 | + describe("exact match strategy", () => { | |
| 5 | + it("should find single occurrence", () => { | |
| 6 | + const content = "const foo = 'bar';"; | |
| 7 | + const search = "foo"; | |
| 8 | + const matches = findSearchMatches(content, search); | |
| 9 | + | |
| 10 | + expect(matches).toHaveLength(1); | |
| 11 | + expect(matches[0]).toEqual({ | |
| 12 | + startIndex: 6, | |
| 13 | + endIndex: 9, | |
| 14 | + strategyName: "exactMatch", | |
| 15 | + }); | |
| 16 | + }); | |
| 17 | + | |
| 18 | + it("should find multiple occurrences", () => { | |
| 19 | + const content = "const foo = 'foo';"; | |
| 20 | + const search = "foo"; | |
| 21 | + const matches = findSearchMatches(content, search); | |
| 22 | + | |
| 23 | + expect(matches).toHaveLength(2); | |
| 24 | + expect(matches[0]).toEqual({ | |
| 25 | + startIndex: 6, | |
| 26 | + endIndex: 9, | |
| 27 | + strategyName: "exactMatch", | |
| 28 | + }); | |
| 29 | + expect(matches[1]).toEqual({ | |
| 30 | + startIndex: 13, | |
| 31 | + endIndex: 16, | |
| 32 | + strategyName: "exactMatch", | |
| 33 | + }); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should find overlapping pattern occurrences correctly", () => { | |
| 37 | + const content = "aaaa"; | |
| 38 | + const search = "aa"; | |
| 39 | + const matches = findSearchMatches(content, search); | |
| 40 | + | |
| 41 | + expect(matches).toHaveLength(2); | |
| 42 | + expect(matches[0]).toEqual({ | |
| 43 | + startIndex: 0, | |
| 44 | + endIndex: 2, | |
| 45 | + strategyName: "exactMatch", | |
| 46 | + }); | |
| 47 | + expect(matches[1]).toEqual({ | |
| 48 | + startIndex: 2, | |
| 49 | + endIndex: 4, | |
| 50 | + strategyName: "exactMatch", | |
| 51 | + }); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("should return empty array when no matches found", () => { | |
| 55 | + const content = "const bar = 'baz';"; | |
| 56 | + const search = "foo"; | |
| 57 | + const matches = findSearchMatches(content, search); | |
| 58 | + | |
| 59 | + expect(matches).toEqual([]); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + it("should handle multi-line content", () => { | |
| 63 | + const content = `line 1 foo | |
| 64 | +line 2 bar | |
| 65 | +line 3 foo`; | |
| 66 | + const search = "foo"; | |
| 67 | + const matches = findSearchMatches(content, search); | |
| 68 | + | |
| 69 | + expect(matches).toHaveLength(2); | |
| 70 | + expect(matches[0]).toEqual({ | |
| 71 | + startIndex: 7, | |
| 72 | + endIndex: 10, | |
| 73 | + strategyName: "exactMatch", | |
| 74 | + }); | |
| 75 | + expect(matches[1]).toEqual({ | |
| 76 | + startIndex: 29, | |
| 77 | + endIndex: 32, | |
| 78 | + strategyName: "exactMatch", | |
| 79 | + }); | |
| 80 | + }); | |
| 81 | + }); | |
| 82 | + | |
| 83 | + describe("trimmed match strategy", () => { | |
| 84 | + it("should find trimmed occurrences when exact match fails", () => { | |
| 85 | + const content = "const foo = 'bar';"; | |
| 86 | + const search = " foo "; | |
| 87 | + const matches = findSearchMatches(content, search); | |
| 88 | + | |
| 89 | + expect(matches).toHaveLength(1); | |
| 90 | + expect(matches[0]).toEqual({ | |
| 91 | + startIndex: 6, | |
| 92 | + endIndex: 9, | |
| 93 | + strategyName: "trimmedMatch", | |
| 94 | + }); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should find multiple trimmed occurrences", () => { | |
| 98 | + const content = "const foo = 'foo';"; | |
| 99 | + const search = " foo "; | |
| 100 | + const matches = findSearchMatches(content, search); | |
| 101 | + | |
| 102 | + expect(matches).toHaveLength(2); | |
| 103 | + expect(matches[0]).toEqual({ | |
| 104 | + startIndex: 6, | |
| 105 | + endIndex: 9, | |
| 106 | + strategyName: "trimmedMatch", | |
| 107 | + }); | |
| 108 | + expect(matches[1]).toEqual({ | |
| 109 | + startIndex: 13, | |
| 110 | + endIndex: 16, | |
| 111 | + strategyName: "trimmedMatch", | |
| 112 | + }); | |
| 113 | + }); | |
| 114 | + }); | |
| 115 | + | |
| 116 | + describe("whitespace ignored match strategy", () => { | |
| 117 | + it("should find matches ignoring internal whitespace", () => { | |
| 118 | + const content = "const foo = bar;"; | |
| 119 | + const search = "const foo=bar"; | |
| 120 | + const matches = findSearchMatches(content, search); | |
| 121 | + | |
| 122 | + expect(matches).toHaveLength(1); | |
| 123 | + expect(matches[0]).toEqual({ | |
| 124 | + startIndex: 0, | |
| 125 | + endIndex: 15, | |
| 126 | + strategyName: "whitespaceIgnoredMatch", | |
| 127 | + }); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should find multiple matches ignoring whitespace", () => { | |
| 131 | + const content = `const foo = bar; | |
| 132 | +const baz = foo;`; | |
| 133 | + const search = "const foo"; | |
| 134 | + const matches = findSearchMatches(content, search); | |
| 135 | + | |
| 136 | + expect(matches).toHaveLength(1); | |
| 137 | + expect(matches[0]).toEqual({ | |
| 138 | + startIndex: 0, | |
| 139 | + endIndex: 9, | |
| 140 | + strategyName: "exactMatch", | |
| 141 | + }); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should handle complex whitespace patterns", () => { | |
| 145 | + const content = `function test() { | |
| 146 | + return true; | |
| 147 | +}`; | |
| 148 | + const search = "function test(){return true;}"; | |
| 149 | + const matches = findSearchMatches(content, search); | |
| 150 | + | |
| 151 | + expect(matches).toHaveLength(1); | |
| 152 | + expect(matches[0]).toEqual({ | |
| 153 | + startIndex: 0, | |
| 154 | + endIndex: 34, | |
| 155 | + strategyName: "whitespaceIgnoredMatch", | |
| 156 | + }); | |
| 157 | + }); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + describe("empty search content", () => { | |
| 161 | + it("should return single match at position 0 for empty string", () => { | |
| 162 | + const content = "const foo = 'bar';"; | |
| 163 | + const search = ""; | |
| 164 | + const matches = findSearchMatches(content, search); | |
| 165 | + | |
| 166 | + expect(matches).toHaveLength(1); | |
| 167 | + expect(matches[0]).toEqual({ | |
| 168 | + startIndex: 0, | |
| 169 | + endIndex: 0, | |
| 170 | + strategyName: "emptySearch", | |
| 171 | + }); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + it("should return single match at position 0 for whitespace-only string", () => { | |
| 175 | + const content = "const foo = 'bar';"; | |
| 176 | + const search = " \n\t "; | |
| 177 | + const matches = findSearchMatches(content, search); | |
| 178 | + | |
| 179 | + expect(matches).toHaveLength(1); | |
| 180 | + expect(matches[0]).toEqual({ | |
| 181 | + startIndex: 0, | |
| 182 | + endIndex: 0, | |
| 183 | + strategyName: "emptySearch", | |
| 184 | + }); | |
| 185 | + }); | |
| 186 | + }); | |
| 187 | + | |
| 188 | + describe("edge cases", () => { | |
| 189 | + it("should handle searching in empty content", () => { | |
| 190 | + const content = ""; | |
| 191 | + const search = "foo"; | |
| 192 | + const matches = findSearchMatches(content, search); | |
| 193 | + | |
| 194 | + expect(matches).toEqual([]); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should handle searching for content at the beginning", () => { | |
| 198 | + const content = "foo bar baz"; | |
| 199 | + const search = "foo"; | |
| 200 | + const matches = findSearchMatches(content, search); | |
| 201 | + | |
| 202 | + expect(matches).toHaveLength(1); | |
| 203 | + expect(matches[0]).toEqual({ | |
| 204 | + startIndex: 0, | |
| 205 | + endIndex: 3, | |
| 206 | + strategyName: "exactMatch", | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + it("should handle searching for content at the end", () => { | |
| 211 | + const content = "foo bar baz"; | |
| 212 | + const search = "baz"; | |
| 213 | + const matches = findSearchMatches(content, search); | |
| 214 | + | |
| 215 | + expect(matches).toHaveLength(1); | |
| 216 | + expect(matches[0]).toEqual({ | |
| 217 | + startIndex: 8, | |
| 218 | + endIndex: 11, | |
| 219 | + strategyName: "exactMatch", | |
| 220 | + }); | |
| 221 | + }); | |
| 222 | + | |
| 223 | + it("should handle searching for the entire content", () => { | |
| 224 | + const content = "foo bar baz"; | |
| 225 | + const search = "foo bar baz"; | |
| 226 | + const matches = findSearchMatches(content, search); | |
| 227 | + | |
| 228 | + expect(matches).toHaveLength(1); | |
| 229 | + expect(matches[0]).toEqual({ | |
| 230 | + startIndex: 0, | |
| 231 | + endIndex: 11, | |
| 232 | + strategyName: "exactMatch", | |
| 233 | + }); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + it("should handle special characters", () => { | |
| 237 | + const content = "const regex = /[a-z]+/g;"; | |
| 238 | + const search = "/[a-z]+/g"; | |
| 239 | + const matches = findSearchMatches(content, search); | |
| 240 | + | |
| 241 | + expect(matches).toHaveLength(1); | |
| 242 | + expect(matches[0]).toEqual({ | |
| 243 | + startIndex: 14, | |
| 244 | + endIndex: 23, | |
| 245 | + strategyName: "exactMatch", | |
| 246 | + }); | |
| 247 | + }); | |
| 248 | + | |
| 249 | + it("should handle Unicode characters", () => { | |
| 250 | + const content = "const emoji = '🚀 Hello 🌍';"; | |
| 251 | + const search = "🚀 Hello 🌍"; | |
| 252 | + const matches = findSearchMatches(content, search); | |
| 253 | + | |
| 254 | + expect(matches).toHaveLength(1); | |
| 255 | + expect(matches[0]).toEqual({ | |
| 256 | + startIndex: 15, | |
| 257 | + endIndex: 26, | |
| 258 | + strategyName: "exactMatch", | |
| 259 | + }); | |
| 260 | + }); | |
| 261 | + }); | |
| 262 | + | |
| 263 | + describe("performance considerations", () => { | |
| 264 | + it("should handle long content with multiple matches", () => { | |
| 265 | + const repeatedContent = "foo bar ".repeat(1000); | |
| 266 | + const search = "foo"; | |
| 267 | + const matches = findSearchMatches(repeatedContent, search); | |
| 268 | + | |
| 269 | + expect(matches).toHaveLength(1000); | |
| 270 | + expect(matches[0]).toEqual({ | |
| 271 | + startIndex: 0, | |
| 272 | + endIndex: 3, | |
| 273 | + strategyName: "exactMatch", | |
| 274 | + }); | |
| 275 | + expect(matches[999]).toEqual({ | |
| 276 | + startIndex: 7992, | |
| 277 | + endIndex: 7995, | |
| 278 | + strategyName: "exactMatch", | |
| 279 | + }); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("should prevent infinite loops on edge cases", () => { | |
| 283 | + const content = "aaaa"; | |
| 284 | + const search = ""; | |
| 285 | + const matches = findSearchMatches(content, search); | |
| 286 | + | |
| 287 | + // Should only return one match for empty search | |
| 288 | + expect(matches).toHaveLength(1); | |
| 289 | + expect(matches[0]).toEqual({ | |
| 290 | + startIndex: 0, | |
| 291 | + endIndex: 0, | |
| 292 | + strategyName: "emptySearch", | |
| 293 | + }); | |
| 294 | + }); | |
| 295 | + }); | |
| 296 | + | |
| 297 | + describe("strategy selection", () => { | |
| 298 | + it("should use exact match strategy when possible", () => { | |
| 299 | + const content = "const foo = bar;"; | |
| 300 | + const search = "foo"; | |
| 301 | + const matches = findSearchMatches(content, search); | |
| 302 | + | |
| 303 | + expect(matches).toHaveLength(1); | |
| 304 | + expect(matches[0].strategyName).toBe("exactMatch"); | |
| 305 | + }); | |
| 306 | + | |
| 307 | + it("should fallback to trimmed match when exact fails", () => { | |
| 308 | + const content = "const foo = bar;"; | |
| 309 | + const search = " foo "; | |
| 310 | + const matches = findSearchMatches(content, search); | |
| 311 | + | |
| 312 | + expect(matches).toHaveLength(1); | |
| 313 | + expect(matches[0].strategyName).toBe("trimmedMatch"); | |
| 314 | + }); | |
| 315 | + | |
| 316 | + it("should fallback to whitespace ignored when others fail", () => { | |
| 317 | + const content = "const foo = bar;"; | |
| 318 | + const search = "const foo=bar"; | |
| 319 | + const matches = findSearchMatches(content, search); | |
| 320 | + | |
| 321 | + expect(matches).toHaveLength(1); | |
| 322 | + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); | |
| 323 | + }); | |
| 324 | + }); | |
| 325 | + | |
| 326 | + describe("complex patterns", () => { | |
| 327 | + it("should handle multiple matches with different line endings", () => { | |
| 328 | + const content = "foo\r\nbar\r\nfoo\nfoo"; | |
| 329 | + const search = "foo"; | |
| 330 | + const matches = findSearchMatches(content, search); | |
| 331 | + | |
| 332 | + expect(matches).toHaveLength(3); | |
| 333 | + expect(matches[0].startIndex).toBe(0); | |
| 334 | + expect(matches[1].startIndex).toBe(10); | |
| 335 | + expect(matches[2].startIndex).toBe(14); | |
| 336 | + }); | |
| 337 | + | |
| 338 | + it("should handle matches across different strategies", () => { | |
| 339 | + const content = "const foo = 'bar';\n const foo='baz';"; | |
| 340 | + const search = "foo"; | |
| 341 | + const matches = findSearchMatches(content, search); | |
| 342 | + | |
| 343 | + // Both occurrences of "foo" should be found with exact match | |
| 344 | + expect(matches).toHaveLength(2); | |
| 345 | + expect(matches[0]).toEqual({ | |
| 346 | + startIndex: 6, | |
| 347 | + endIndex: 9, | |
| 348 | + strategyName: "exactMatch", | |
| 349 | + }); | |
| 350 | + expect(matches[1]).toEqual({ | |
| 351 | + startIndex: 29, | |
| 352 | + endIndex: 32, | |
| 353 | + strategyName: "exactMatch", | |
| 354 | + }); | |
| 355 | + }); | |
| 356 | + | |
| 357 | + it("should handle code with mixed indentation", () => { | |
| 358 | + const content = `\tfunction test() { | |
| 359 | + return true; | |
| 360 | +\t}`; | |
| 361 | + const search = "function test(){return true;}"; | |
| 362 | + const matches = findSearchMatches(content, search); | |
| 363 | + | |
| 364 | + expect(matches).toHaveLength(1); | |
| 365 | + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); | |
| 366 | + }); | |
| 367 | + }); | |
| 368 | +}); |
added core/edit/searchAndReplace/multiEdit.vitest.ts +341 −0
| @@ -0,0 +1,341 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 3 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 4 | +import { validateMultiEdit } from "./multiEditValidation"; | |
| 5 | +import { executeMultiFindAndReplace } from "./performReplace"; | |
| 6 | + | |
| 7 | +describe("multiEdit shared validation", () => { | |
| 8 | + describe("validateMultiEdit", () => { | |
| 9 | + it("should throw error if edits is not an array", () => { | |
| 10 | + expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError( | |
| 11 | + expect.objectContaining({ | |
| 12 | + reason: ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 13 | + }), | |
| 14 | + ); | |
| 15 | + }); | |
| 16 | + | |
| 17 | + it("should throw error if edits is missing", () => { | |
| 18 | + expect(() => validateMultiEdit({})).toThrowError( | |
| 19 | + expect.objectContaining({ | |
| 20 | + reason: ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 21 | + }), | |
| 22 | + ); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + it("should throw error if edits array is empty", () => { | |
| 26 | + expect(() => validateMultiEdit({ edits: [] })).toThrowError( | |
| 27 | + expect.objectContaining({ | |
| 28 | + reason: ContinueErrorReason.MultiEditEditsArrayEmpty, | |
| 29 | + }), | |
| 30 | + ); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + it("should return valid edits", () => { | |
| 34 | + const edits: EditOperation[] = [ | |
| 35 | + { old_string: "hello", new_string: "world" }, | |
| 36 | + ]; | |
| 37 | + const result = validateMultiEdit({ edits }); | |
| 38 | + expect(result.edits).toEqual(edits); | |
| 39 | + }); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + describe("validateMultiEdit - individual edit validation", () => { | |
| 43 | + it("should throw error if edit has missing old_string", () => { | |
| 44 | + const args = { | |
| 45 | + edits: [ | |
| 46 | + { | |
| 47 | + old_string: undefined as any, | |
| 48 | + new_string: "Hi there", | |
| 49 | + }, | |
| 50 | + ], | |
| 51 | + }; | |
| 52 | + | |
| 53 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 54 | + expect.objectContaining({ | |
| 55 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 56 | + }), | |
| 57 | + ); | |
| 58 | + }); | |
| 59 | + | |
| 60 | + it("should throw error if edit has missing new_string", () => { | |
| 61 | + const args = { | |
| 62 | + edits: [ | |
| 63 | + { | |
| 64 | + old_string: "Hello world", | |
| 65 | + new_string: undefined as any, | |
| 66 | + }, | |
| 67 | + ], | |
| 68 | + }; | |
| 69 | + | |
| 70 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 71 | + expect.objectContaining({ | |
| 72 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 73 | + }), | |
| 74 | + ); | |
| 75 | + }); | |
| 76 | + | |
| 77 | + it("should throw error if old_string and new_string are the same", () => { | |
| 78 | + const args = { | |
| 79 | + edits: [ | |
| 80 | + { | |
| 81 | + old_string: "Hello world", | |
| 82 | + new_string: "Hello world", | |
| 83 | + }, | |
| 84 | + ], | |
| 85 | + }; | |
| 86 | + | |
| 87 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 88 | + expect.objectContaining({ | |
| 89 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 90 | + }), | |
| 91 | + ); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should throw error if non-first edit has empty old_string", () => { | |
| 95 | + const args = { | |
| 96 | + edits: [ | |
| 97 | + { | |
| 98 | + old_string: "Hello world", | |
| 99 | + new_string: "Hi there", | |
| 100 | + }, | |
| 101 | + { | |
| 102 | + old_string: "", | |
| 103 | + new_string: "Invalid insertion", | |
| 104 | + }, | |
| 105 | + ], | |
| 106 | + }; | |
| 107 | + | |
| 108 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 109 | + expect.objectContaining({ | |
| 110 | + reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, | |
| 111 | + }), | |
| 112 | + ); | |
| 113 | + }); | |
| 114 | + | |
| 115 | + it("should allow first edit to have empty old_string", () => { | |
| 116 | + const args = { | |
| 117 | + edits: [ | |
| 118 | + { | |
| 119 | + old_string: "", | |
| 120 | + new_string: "New content", | |
| 121 | + }, | |
| 122 | + ], | |
| 123 | + }; | |
| 124 | + | |
| 125 | + expect(() => validateMultiEdit(args)).not.toThrow(); | |
| 126 | + }); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + describe("executeMultiFindAndReplace", () => { | |
| 130 | + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; | |
| 131 | + | |
| 132 | + it("should handle single edit", () => { | |
| 133 | + const edits = [ | |
| 134 | + { | |
| 135 | + old_string: "Hello world", | |
| 136 | + new_string: "Hi there", | |
| 137 | + }, | |
| 138 | + ]; | |
| 139 | + | |
| 140 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 141 | + expect(result).toBe("Hi there\nThis is a test file\nGoodbye world"); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should handle multiple edits", () => { | |
| 145 | + const edits = [ | |
| 146 | + { | |
| 147 | + old_string: "Hello world", | |
| 148 | + new_string: "Hi there", | |
| 149 | + }, | |
| 150 | + { | |
| 151 | + old_string: "Goodbye world", | |
| 152 | + new_string: "See you later", | |
| 153 | + }, | |
| 154 | + ]; | |
| 155 | + | |
| 156 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 157 | + expect(result).toBe("Hi there\nThis is a test file\nSee you later"); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + it("should handle replace_all", () => { | |
| 161 | + const edits = [ | |
| 162 | + { | |
| 163 | + old_string: "world", | |
| 164 | + new_string: "universe", | |
| 165 | + replace_all: true, | |
| 166 | + }, | |
| 167 | + ]; | |
| 168 | + | |
| 169 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 170 | + expect(result).toBe( | |
| 171 | + "Hello universe\nThis is a test file\nGoodbye universe", | |
| 172 | + ); | |
| 173 | + }); | |
| 174 | + | |
| 175 | + it("should handle empty old_string as insertion at beginning", () => { | |
| 176 | + const edits = [ | |
| 177 | + { | |
| 178 | + old_string: "", | |
| 179 | + new_string: "New first line\n", | |
| 180 | + }, | |
| 181 | + ]; | |
| 182 | + | |
| 183 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 184 | + expect(result).toBe( | |
| 185 | + "New first line\nHello world\nThis is a test file\nGoodbye world", | |
| 186 | + ); | |
| 187 | + }); | |
| 188 | + | |
| 189 | + it("should handle empty string in empty file", () => { | |
| 190 | + const edits = [ | |
| 191 | + { | |
| 192 | + old_string: "", | |
| 193 | + new_string: "Content for empty file", | |
| 194 | + }, | |
| 195 | + ]; | |
| 196 | + | |
| 197 | + // Empty old_string matches at position 0 (beginning of file) | |
| 198 | + const result = executeMultiFindAndReplace("", edits); | |
| 199 | + expect(result).toBe("Content for empty file"); | |
| 200 | + }); | |
| 201 | + | |
| 202 | + it("should apply edits sequentially", () => { | |
| 203 | + const edits = [ | |
| 204 | + { | |
| 205 | + old_string: "Hello world", | |
| 206 | + new_string: "Hi universe", | |
| 207 | + }, | |
| 208 | + { | |
| 209 | + old_string: "Hi universe", | |
| 210 | + new_string: "Greetings cosmos", | |
| 211 | + }, | |
| 212 | + ]; | |
| 213 | + | |
| 214 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 215 | + expect(result).toBe( | |
| 216 | + "Greetings cosmos\nThis is a test file\nGoodbye world", | |
| 217 | + ); | |
| 218 | + }); | |
| 219 | + | |
| 220 | + it("should throw error if old_string is not found", () => { | |
| 221 | + const edits = [ | |
| 222 | + { | |
| 223 | + old_string: "Not found", | |
| 224 | + new_string: "Hi there", | |
| 225 | + }, | |
| 226 | + ]; | |
| 227 | + | |
| 228 | + expect(() => | |
| 229 | + executeMultiFindAndReplace(originalContent, edits), | |
| 230 | + ).toThrowError( | |
| 231 | + expect.objectContaining({ | |
| 232 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 233 | + }), | |
| 234 | + ); | |
| 235 | + }); | |
| 236 | + | |
| 237 | + it("should throw error if old_string appears multiple times and replace_all is false", () => { | |
| 238 | + const edits = [ | |
| 239 | + { | |
| 240 | + old_string: "world", | |
| 241 | + new_string: "universe", | |
| 242 | + replace_all: false, | |
| 243 | + }, | |
| 244 | + ]; | |
| 245 | + | |
| 246 | + expect(() => | |
| 247 | + executeMultiFindAndReplace(originalContent, edits), | |
| 248 | + ).toThrowError( | |
| 249 | + expect.objectContaining({ | |
| 250 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 251 | + }), | |
| 252 | + ); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + it("should throw if string not found in edit sequence", () => { | |
| 256 | + const content = "Hello world"; | |
| 257 | + const edits = [ | |
| 258 | + { old_string: "Hello", new_string: "Hi" }, | |
| 259 | + { old_string: "not found", new_string: "test" }, | |
| 260 | + ]; | |
| 261 | + | |
| 262 | + expect(() => executeMultiFindAndReplace(content, edits)).toThrowError( | |
| 263 | + expect.objectContaining({ | |
| 264 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 265 | + }), | |
| 266 | + ); | |
| 267 | + }); | |
| 268 | + | |
| 269 | + it("should handle whitespace differences using findSearchMatch", () => { | |
| 270 | + const content = "function test() {\n return true;\n}"; | |
| 271 | + const edits = [ | |
| 272 | + { | |
| 273 | + old_string: "function test(){return true;}", | |
| 274 | + new_string: "function test() { return false; }", | |
| 275 | + }, | |
| 276 | + ]; | |
| 277 | + | |
| 278 | + const result = executeMultiFindAndReplace(content, edits); | |
| 279 | + expect(result).toBe("function test() { return false; }"); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("should handle mixed replace_all settings", () => { | |
| 283 | + const content = "x y x z x"; | |
| 284 | + const edits = [ | |
| 285 | + { old_string: "x", new_string: "a", replace_all: true }, | |
| 286 | + { old_string: "y", new_string: "b" }, | |
| 287 | + ]; | |
| 288 | + | |
| 289 | + const result = executeMultiFindAndReplace(content, edits); | |
| 290 | + expect(result).toBe("a b a z a"); | |
| 291 | + }); | |
| 292 | + }); | |
| 293 | + | |
| 294 | + describe("preprocessing logic", () => { | |
| 295 | + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; | |
| 296 | + | |
| 297 | + it("should handle single edit preprocessing", () => { | |
| 298 | + const edits = [ | |
| 299 | + { | |
| 300 | + old_string: "Hello world", | |
| 301 | + new_string: "Hi there", | |
| 302 | + }, | |
| 303 | + ]; | |
| 304 | + | |
| 305 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 306 | + | |
| 307 | + expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world"); | |
| 308 | + }); | |
| 309 | + | |
| 310 | + it("should handle multiple edits preprocessing", () => { | |
| 311 | + const edits = [ | |
| 312 | + { | |
| 313 | + old_string: "Hello world", | |
| 314 | + new_string: "Hi there", | |
| 315 | + }, | |
| 316 | + { | |
| 317 | + old_string: "Goodbye world", | |
| 318 | + new_string: "See you later", | |
| 319 | + }, | |
| 320 | + ]; | |
| 321 | + | |
| 322 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 323 | + | |
| 324 | + expect(newContent).toBe("Hi there\nThis is a test file\nSee you later"); | |
| 325 | + }); | |
| 326 | + | |
| 327 | + it("should count edits correctly", () => { | |
| 328 | + const edits = [ | |
| 329 | + { old_string: "Hello", new_string: "Hi" }, | |
| 330 | + { old_string: "world", new_string: "universe", replace_all: true }, | |
| 331 | + ]; | |
| 332 | + | |
| 333 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 334 | + | |
| 335 | + expect(newContent).toBe( | |
| 336 | + "Hi universe\nThis is a test file\nGoodbye universe", | |
| 337 | + ); | |
| 338 | + expect(edits.length).toBe(2); | |
| 339 | + }); | |
| 340 | + }); | |
| 341 | +}); |
added core/edit/searchAndReplace/multiEditValidation.ts +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 2 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { validateSingleEdit } from "./findAndReplaceUtils"; | |
| 4 | + | |
| 5 | +export interface MultiEditValidationResult { | |
| 6 | + edits: EditOperation[]; | |
| 7 | +} | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * Validates multi-edit arguments and all edits in a single pass | |
| 11 | + * @param args - The arguments object containing the edits array | |
| 12 | + * @returns Validated edits array | |
| 13 | + * @throws ContinueError if validation fails | |
| 14 | + */ | |
| 15 | +export function validateMultiEdit(args: any): MultiEditValidationResult { | |
| 16 | + const { edits } = args; | |
| 17 | + | |
| 18 | + // Validate that edits is a non-empty array | |
| 19 | + if (!edits || !Array.isArray(edits)) { | |
| 20 | + throw new ContinueError( | |
| 21 | + ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 22 | + "edits array is required", | |
| 23 | + ); | |
| 24 | + } | |
| 25 | + | |
| 26 | + if (edits.length === 0) { | |
| 27 | + throw new ContinueError( | |
| 28 | + ContinueErrorReason.MultiEditEditsArrayEmpty, | |
| 29 | + "edits array must contain at least one edit", | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + | |
| 33 | + // Validate each individual edit | |
| 34 | + for (let i = 0; i < edits.length; i++) { | |
| 35 | + const edit = edits[i]; | |
| 36 | + | |
| 37 | + // Use existing single edit validation | |
| 38 | + validateSingleEdit(edit.old_string, edit.new_string, i); | |
| 39 | + | |
| 40 | + // Only the first edit can have empty old_string (for insertion at beginning) | |
| 41 | + if (i > 0 && edit.old_string === "") { | |
| 42 | + throw new ContinueError( | |
| 43 | + ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, | |
| 44 | + `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.`, | |
| 45 | + ); | |
| 46 | + } | |
| 47 | + } | |
| 48 | + | |
| 49 | + return { edits }; | |
| 50 | +} |
deleted core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts +0 −390
| @@ -1,390 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - parseAllSearchReplaceBlocks, | |
| 3 | - parseSearchReplaceBlock, | |
| 4 | -} from "./parseSearchReplaceBlock"; | |
| 5 | - | |
| 6 | -describe("parseSearchReplaceBlock", () => { | |
| 7 | - describe("Complete blocks", () => { | |
| 8 | - it("should parse a complete basic search/replace block", () => { | |
| 9 | - const content = `------- SEARCH | |
| 10 | -reset() { | |
| 11 | -this.result = 0; | |
| 12 | -return this; | |
| 13 | -} | |
| 14 | -======= | |
| 15 | -// Resets the calculator result to 0 and returns the instance for method chaining | |
| 16 | -reset() { | |
| 17 | -this.result = 0; | |
| 18 | -return this; | |
| 19 | -} | |
| 20 | -+++++++ REPLACE`; | |
| 21 | - | |
| 22 | - const result = parseSearchReplaceBlock(content); | |
| 23 | - | |
| 24 | - expect(result.isComplete).toBe(true); | |
| 25 | - expect(result.searchContent).toBe(`reset() { | |
| 26 | -this.result = 0; | |
| 27 | -return this; | |
| 28 | -}`); | |
| 29 | - expect(result.replaceContent) | |
| 30 | - .toBe(`// Resets the calculator result to 0 and returns the instance for method chaining | |
| 31 | -reset() { | |
| 32 | -this.result = 0; | |
| 33 | -return this; | |
| 34 | -}`); | |
| 35 | - expect(result.error).toBeUndefined(); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - it("should handle different marker lengths", () => { | |
| 39 | - const content = `------- SEARCH | |
| 40 | -old content | |
| 41 | -========= | |
| 42 | -new content | |
| 43 | -+++++++++++ REPLACE`; | |
| 44 | - | |
| 45 | - const result = parseSearchReplaceBlock(content); | |
| 46 | - | |
| 47 | - expect(result.isComplete).toBe(true); | |
| 48 | - expect(result.searchContent).toBe("old content"); | |
| 49 | - expect(result.replaceContent).toBe("new content"); | |
| 50 | - }); | |
| 51 | - | |
| 52 | - it("should handle empty search content", () => { | |
| 53 | - const content = `------- SEARCH | |
| 54 | -======= | |
| 55 | -new content | |
| 56 | -+++++++ REPLACE`; | |
| 57 | - | |
| 58 | - const result = parseSearchReplaceBlock(content); | |
| 59 | - | |
| 60 | - expect(result.isComplete).toBe(true); | |
| 61 | - expect(result.searchContent).toBe(""); | |
| 62 | - expect(result.replaceContent).toBe("new content"); | |
| 63 | - }); | |
| 64 | - | |
| 65 | - it("should handle empty replace content (deletion)", () => { | |
| 66 | - const content = `------- SEARCH | |
| 67 | -old content to delete | |
| 68 | -======= | |
| 69 | -+++++++ REPLACE`; | |
| 70 | - | |
| 71 | - const result = parseSearchReplaceBlock(content); | |
| 72 | - | |
| 73 | - expect(result.isComplete).toBe(true); | |
| 74 | - expect(result.searchContent).toBe("old content to delete"); | |
| 75 | - expect(result.replaceContent).toBe(""); | |
| 76 | - }); | |
| 77 | - | |
| 78 | - it("should handle both empty search and replace content", () => { | |
| 79 | - const content = `------- SEARCH | |
| 80 | -======= | |
| 81 | -+++++++ REPLACE`; | |
| 82 | - | |
| 83 | - const result = parseSearchReplaceBlock(content); | |
| 84 | - | |
| 85 | - expect(result.isComplete).toBe(true); | |
| 86 | - expect(result.searchContent).toBe(""); | |
| 87 | - expect(result.replaceContent).toBe(""); | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | - | |
| 91 | - describe("Incomplete blocks", () => { | |
| 92 | - it("should handle incomplete search block", () => { | |
| 93 | - const content = `------- SEARCH | |
| 94 | -some content`; | |
| 95 | - | |
| 96 | - const result = parseSearchReplaceBlock(content); | |
| 97 | - | |
| 98 | - expect(result.isComplete).toBe(false); | |
| 99 | - expect(result.searchContent).toBe("some content"); | |
| 100 | - expect(result.replaceContent).toBe(""); | |
| 101 | - expect(result.error).toBeUndefined(); | |
| 102 | - }); | |
| 103 | - | |
| 104 | - it("should handle incomplete replace block", () => { | |
| 105 | - const content = `------- SEARCH | |
| 106 | -old content | |
| 107 | -======= | |
| 108 | -new content`; | |
| 109 | - | |
| 110 | - const result = parseSearchReplaceBlock(content); | |
| 111 | - | |
| 112 | - expect(result.isComplete).toBe(false); | |
| 113 | - expect(result.searchContent).toBe("old content"); | |
| 114 | - expect(result.replaceContent).toBe("new content"); | |
| 115 | - expect(result.error).toBeUndefined(); | |
| 116 | - }); | |
| 117 | - }); | |
| 118 | - | |
| 119 | - describe("Error cases", () => { | |
| 120 | - it("should error on search end without start", () => { | |
| 121 | - const content = `======= | |
| 122 | -some content | |
| 123 | -+++++++ REPLACE`; | |
| 124 | - | |
| 125 | - const result = parseSearchReplaceBlock(content); | |
| 126 | - | |
| 127 | - expect(result.isComplete).toBe(false); | |
| 128 | - expect(result.error).toBe( | |
| 129 | - "Found search block end marker without matching start marker", | |
| 130 | - ); | |
| 131 | - }); | |
| 132 | - | |
| 133 | - it("should error on replace end without replace start", () => { | |
| 134 | - const content = `+++++++ REPLACE`; | |
| 135 | - | |
| 136 | - const result = parseSearchReplaceBlock(content); | |
| 137 | - | |
| 138 | - expect(result.isComplete).toBe(false); | |
| 139 | - expect(result.error).toBe( | |
| 140 | - "Found replace block end marker without matching replace start marker", | |
| 141 | - ); | |
| 142 | - }); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - describe("Regex pattern validation", () => { | |
| 146 | - it("should match various search start patterns", () => { | |
| 147 | - const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"]; | |
| 148 | - | |
| 149 | - patterns.forEach((pattern) => { | |
| 150 | - const content = `${pattern} | |
| 151 | -content | |
| 152 | -======= | |
| 153 | -replacement | |
| 154 | -+++++++ REPLACE`; | |
| 155 | - | |
| 156 | - const result = parseSearchReplaceBlock(content); | |
| 157 | - expect(result.isComplete).toBe(true); | |
| 158 | - }); | |
| 159 | - }); | |
| 160 | - | |
| 161 | - it("should match various search end patterns", () => { | |
| 162 | - const patterns = ["===", "=======", "=============="]; | |
| 163 | - | |
| 164 | - patterns.forEach((pattern) => { | |
| 165 | - const content = `------- SEARCH | |
| 166 | -content | |
| 167 | -${pattern} | |
| 168 | -replacement | |
| 169 | -+++++++ REPLACE`; | |
| 170 | - | |
| 171 | - const result = parseSearchReplaceBlock(content); | |
| 172 | - expect(result.isComplete).toBe(true); | |
| 173 | - }); | |
| 174 | - }); | |
| 175 | - | |
| 176 | - it("should match various replace end patterns", () => { | |
| 177 | - const patterns = [ | |
| 178 | - "+++ REPLACE", | |
| 179 | - "+++++++ REPLACE", | |
| 180 | - "+++++++++++ REPLACE", | |
| 181 | - ]; | |
| 182 | - | |
| 183 | - patterns.forEach((pattern) => { | |
| 184 | - const content = `------- SEARCH | |
| 185 | -content | |
| 186 | -======= | |
| 187 | -replacement | |
| 188 | -${pattern}`; | |
| 189 | - | |
| 190 | - const result = parseSearchReplaceBlock(content); | |
| 191 | - expect(result.isComplete).toBe(true); | |
| 192 | - }); | |
| 193 | - }); | |
| 194 | - | |
| 195 | - it("should not match invalid patterns", () => { | |
| 196 | - const invalidPatterns = [ | |
| 197 | - "-- SEARCH", // Too few dashes | |
| 198 | - "SEARCH", // No markers | |
| 199 | - "== SEARCH", // Wrong markers | |
| 200 | - "=== REPLACE", // Wrong end marker | |
| 201 | - "++++ SEARCH", // Wrong markers for search | |
| 202 | - ]; | |
| 203 | - | |
| 204 | - invalidPatterns.forEach((pattern) => { | |
| 205 | - const content = `${pattern} | |
| 206 | -content`; | |
| 207 | - | |
| 208 | - const result = parseSearchReplaceBlock(content); | |
| 209 | - expect(result.isComplete).toBe(false); | |
| 210 | - expect(result.searchContent).toBe(""); // Should not enter search mode | |
| 211 | - }); | |
| 212 | - }); | |
| 213 | - }); | |
| 214 | -}); | |
| 215 | - | |
| 216 | -describe("parseAllSearchReplaceBlocks", () => { | |
| 217 | - it("should parse multiple complete blocks", () => { | |
| 218 | - const content = `------- SEARCH | |
| 219 | -old code 1 | |
| 220 | -======= | |
| 221 | -new code 1 | |
| 222 | -+++++++ REPLACE | |
| 223 | - | |
| 224 | -------- SEARCH | |
| 225 | -old code 2 | |
| 226 | -======= | |
| 227 | -new code 2 | |
| 228 | -+++++++ REPLACE`; | |
| 229 | - | |
| 230 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 231 | - | |
| 232 | - expect(blocks).toHaveLength(2); | |
| 233 | - expect(blocks[0].searchContent).toBe("old code 1"); | |
| 234 | - expect(blocks[0].replaceContent).toBe("new code 1"); | |
| 235 | - expect(blocks[1].searchContent).toBe("old code 2"); | |
| 236 | - expect(blocks[1].replaceContent).toBe("new code 2"); | |
| 237 | - }); | |
| 238 | - | |
| 239 | - it("should handle blocks with different content", () => { | |
| 240 | - const content = `------- SEARCH | |
| 241 | -function old() { | |
| 242 | - return 1; | |
| 243 | -} | |
| 244 | -======= | |
| 245 | -function new() { | |
| 246 | - return 2; | |
| 247 | -} | |
| 248 | -+++++++ REPLACE | |
| 249 | - | |
| 250 | -------- SEARCH | |
| 251 | -const x = 'old'; | |
| 252 | -======= | |
| 253 | -const x = 'new'; | |
| 254 | -+++++++ REPLACE`; | |
| 255 | - | |
| 256 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 257 | - | |
| 258 | - expect(blocks).toHaveLength(2); | |
| 259 | - expect(blocks[0].searchContent).toBe(`function old() { | |
| 260 | - return 1; | |
| 261 | -}`); | |
| 262 | - expect(blocks[0].replaceContent).toBe(`function new() { | |
| 263 | - return 2; | |
| 264 | -}`); | |
| 265 | - expect(blocks[1].searchContent).toBe(`const x = 'old';`); | |
| 266 | - expect(blocks[1].replaceContent).toBe(`const x = 'new';`); | |
| 267 | - }); | |
| 268 | - | |
| 269 | - it("should handle deletion blocks (empty replace content)", () => { | |
| 270 | - const content = `------- SEARCH | |
| 271 | -code to keep | |
| 272 | -======= | |
| 273 | -modified code | |
| 274 | -+++++++ REPLACE | |
| 275 | - | |
| 276 | -------- SEARCH | |
| 277 | -code to delete | |
| 278 | -======= | |
| 279 | -+++++++ REPLACE`; | |
| 280 | - | |
| 281 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 282 | - | |
| 283 | - expect(blocks).toHaveLength(2); | |
| 284 | - expect(blocks[0].searchContent).toBe("code to keep"); | |
| 285 | - expect(blocks[0].replaceContent).toBe("modified code"); | |
| 286 | - expect(blocks[1].searchContent).toBe("code to delete"); | |
| 287 | - expect(blocks[1].replaceContent).toBe(""); // Deletion | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle insertion blocks (empty search content)", () => { | |
| 291 | - const content = `------- SEARCH | |
| 292 | -existing code | |
| 293 | -======= | |
| 294 | -modified existing code | |
| 295 | -+++++++ REPLACE | |
| 296 | - | |
| 297 | -------- SEARCH | |
| 298 | -======= | |
| 299 | -new code to insert | |
| 300 | -+++++++ REPLACE`; | |
| 301 | - | |
| 302 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 303 | - | |
| 304 | - expect(blocks).toHaveLength(2); | |
| 305 | - expect(blocks[0].searchContent).toBe("existing code"); | |
| 306 | - expect(blocks[0].replaceContent).toBe("modified existing code"); | |
| 307 | - expect(blocks[1].searchContent).toBe(""); // Insertion | |
| 308 | - expect(blocks[1].replaceContent).toBe("new code to insert"); | |
| 309 | - }); | |
| 310 | - | |
| 311 | - it("should skip incomplete blocks", () => { | |
| 312 | - const content = `------- SEARCH | |
| 313 | -incomplete block | |
| 314 | - | |
| 315 | -------- SEARCH | |
| 316 | -complete block | |
| 317 | -======= | |
| 318 | -replacement | |
| 319 | -+++++++ REPLACE`; | |
| 320 | - | |
| 321 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 322 | - | |
| 323 | - expect(blocks).toHaveLength(1); | |
| 324 | - expect(blocks[0].searchContent).toBe("complete block"); | |
| 325 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 326 | - }); | |
| 327 | - | |
| 328 | - it("should handle single block", () => { | |
| 329 | - const content = `------- SEARCH | |
| 330 | -single block | |
| 331 | -======= | |
| 332 | -replacement | |
| 333 | -+++++++ REPLACE`; | |
| 334 | - | |
| 335 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 336 | - | |
| 337 | - expect(blocks).toHaveLength(1); | |
| 338 | - expect(blocks[0].searchContent).toBe("single block"); | |
| 339 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 340 | - }); | |
| 341 | - | |
| 342 | - it("should return empty array when no complete blocks found", () => { | |
| 343 | - const content = `------- SEARCH | |
| 344 | -incomplete | |
| 345 | -======= | |
| 346 | -missing replace marker`; | |
| 347 | - | |
| 348 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 349 | - | |
| 350 | - expect(blocks).toHaveLength(0); | |
| 351 | - }); | |
| 352 | - | |
| 353 | - it("should handle blocks with extra content between them", () => { | |
| 354 | - const content = `Some other content here | |
| 355 | - | |
| 356 | -------- SEARCH | |
| 357 | -block 1 | |
| 358 | -======= | |
| 359 | -replacement 1 | |
| 360 | -+++++++ REPLACE | |
| 361 | - | |
| 362 | -More content in between | |
| 363 | - | |
| 364 | -------- SEARCH | |
| 365 | -block 2 | |
| 366 | -======= | |
| 367 | -replacement 2 | |
| 368 | -+++++++ REPLACE | |
| 369 | - | |
| 370 | -Trailing content`; | |
| 371 | - | |
| 372 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 373 | - | |
| 374 | - expect(blocks).toHaveLength(2); | |
| 375 | - expect(blocks[0].searchContent).toBe("block 1"); | |
| 376 | - expect(blocks[0].replaceContent).toBe("replacement 1"); | |
| 377 | - expect(blocks[1].searchContent).toBe("block 2"); | |
| 378 | - expect(blocks[1].replaceContent).toBe("replacement 2"); | |
| 379 | - }); | |
| 380 | - | |
| 381 | - it("should throw error for malformed blocks", () => { | |
| 382 | - const content = `------- SEARCH | |
| 383 | -content | |
| 384 | -+++++++ REPLACE`; // Missing ======= | |
| 385 | - | |
| 386 | - expect(() => parseAllSearchReplaceBlocks(content)).toThrow( | |
| 387 | - "Found replace block end marker without matching replace start marker", | |
| 388 | - ); | |
| 389 | - }); | |
| 390 | -}); |
deleted core/edit/searchAndReplace/parseSearchReplaceBlock.ts +0 −147
| @@ -1,147 +0,0 @@ | ||
| 1 | -// Search and replace block markers using flexible regex patterns | |
| 2 | -const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; | |
| 3 | -const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; | |
| 4 | -const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; | |
| 5 | - | |
| 6 | -export interface SearchReplaceBlockResult { | |
| 7 | - /** Whether a complete search/replace block has been parsed */ | |
| 8 | - isComplete: boolean; | |
| 9 | - /** The content to search for in the file */ | |
| 10 | - searchContent?: string; | |
| 11 | - /** The content to replace the search content with */ | |
| 12 | - replaceContent?: string; | |
| 13 | - /** Error message if parsing failed */ | |
| 14 | - error?: string; | |
| 15 | -} | |
| 16 | - | |
| 17 | -/** | |
| 18 | - * Parses a search and replace block from content. | |
| 19 | - * | |
| 20 | - * Expected format: | |
| 21 | - * ------- SEARCH | |
| 22 | - * [content to find] | |
| 23 | - * ======= | |
| 24 | - * [content to replace with] | |
| 25 | - * +++++++ REPLACE | |
| 26 | - * | |
| 27 | - * @param content - The content to parse | |
| 28 | - * @returns ParseResult with completion status and extracted content | |
| 29 | - */ | |
| 30 | -export function parseSearchReplaceBlock( | |
| 31 | - content: string, | |
| 32 | -): SearchReplaceBlockResult { | |
| 33 | - const lines = content.split("\n"); | |
| 34 | - | |
| 35 | - let currentSearchContent = ""; | |
| 36 | - let currentReplaceContent = ""; | |
| 37 | - let inSearch = false; | |
| 38 | - let inReplace = false; | |
| 39 | - | |
| 40 | - for (const line of lines) { | |
| 41 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 42 | - inSearch = true; | |
| 43 | - inReplace = false; | |
| 44 | - currentSearchContent = ""; | |
| 45 | - currentReplaceContent = ""; | |
| 46 | - continue; | |
| 47 | - } | |
| 48 | - | |
| 49 | - if (SEARCH_BLOCK_END_REGEX.test(line)) { | |
| 50 | - if (!inSearch) { | |
| 51 | - return { | |
| 52 | - isComplete: false, | |
| 53 | - error: "Found search block end marker without matching start marker", | |
| 54 | - }; | |
| 55 | - } | |
| 56 | - inSearch = false; | |
| 57 | - inReplace = true; | |
| 58 | - continue; | |
| 59 | - } | |
| 60 | - | |
| 61 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 62 | - if (!inReplace) { | |
| 63 | - return { | |
| 64 | - isComplete: false, | |
| 65 | - error: | |
| 66 | - "Found replace block end marker without matching replace start marker", | |
| 67 | - }; | |
| 68 | - } | |
| 69 | - | |
| 70 | - // Complete block found | |
| 71 | - return { | |
| 72 | - isComplete: true, | |
| 73 | - searchContent: currentSearchContent.trim(), | |
| 74 | - replaceContent: currentReplaceContent.trim(), | |
| 75 | - }; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Accumulate content | |
| 79 | - if (inSearch) { | |
| 80 | - currentSearchContent += line + "\n"; | |
| 81 | - } else if (inReplace) { | |
| 82 | - currentReplaceContent += line + "\n"; | |
| 83 | - } | |
| 84 | - } | |
| 85 | - | |
| 86 | - // Block is not yet complete | |
| 87 | - return { | |
| 88 | - isComplete: false, | |
| 89 | - searchContent: currentSearchContent.trim(), | |
| 90 | - replaceContent: currentReplaceContent.trim(), | |
| 91 | - }; | |
| 92 | -} | |
| 93 | - | |
| 94 | -/** | |
| 95 | - * Parses all complete search and replace blocks from content. | |
| 96 | - * | |
| 97 | - * @param content - The content containing multiple search/replace blocks | |
| 98 | - * @returns Array of complete search/replace blocks found | |
| 99 | - * @throws Error if any malformed blocks are encountered | |
| 100 | - */ | |
| 101 | -export function parseAllSearchReplaceBlocks( | |
| 102 | - content: string, | |
| 103 | -): SearchReplaceBlockResult[] { | |
| 104 | - const blocks: SearchReplaceBlockResult[] = []; | |
| 105 | - const lines = content.split("\n"); | |
| 106 | - | |
| 107 | - let currentBlockLines: string[] = []; | |
| 108 | - let inBlock = false; | |
| 109 | - | |
| 110 | - for (const line of lines) { | |
| 111 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 112 | - // Start of new block | |
| 113 | - if (inBlock && currentBlockLines.length > 0) { | |
| 114 | - // Process previous incomplete block if any | |
| 115 | - const blockContent = currentBlockLines.join("\n"); | |
| 116 | - const result = parseSearchReplaceBlock(blockContent); | |
| 117 | - if (result.isComplete) { | |
| 118 | - blocks.push(result); | |
| 119 | - } else if (result.error) { | |
| 120 | - // Fail fast on any parsing error | |
| 121 | - throw new Error(result.error); | |
| 122 | - } | |
| 123 | - // If incomplete but no error, it's just a partial block - continue processing | |
| 124 | - } | |
| 125 | - currentBlockLines = [line]; | |
| 126 | - inBlock = true; | |
| 127 | - } else if (inBlock) { | |
| 128 | - currentBlockLines.push(line); | |
| 129 | - | |
| 130 | - // Check if this line completes the current block | |
| 131 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 132 | - const blockContent = currentBlockLines.join("\n"); | |
| 133 | - const result = parseSearchReplaceBlock(blockContent); | |
| 134 | - if (result.isComplete) { | |
| 135 | - blocks.push(result); | |
| 136 | - } else if (result.error) { | |
| 137 | - // Fail fast on any parsing error | |
| 138 | - throw new Error(result.error); | |
| 139 | - } | |
| 140 | - currentBlockLines = []; | |
| 141 | - inBlock = false; | |
| 142 | - } | |
| 143 | - } | |
| 144 | - } | |
| 145 | - | |
| 146 | - return blocks; | |
| 147 | -} |
added core/edit/searchAndReplace/performReplace.ts +70 −0
| @@ -0,0 +1,70 @@ | ||
| 1 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 2 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { findSearchMatches } from "./findSearchMatch"; | |
| 4 | + | |
| 5 | +export function executeFindAndReplace( | |
| 6 | + fileContent: string, | |
| 7 | + oldString: string, | |
| 8 | + newString: string, | |
| 9 | + replaceAll: boolean, | |
| 10 | + editIndex = 0, | |
| 11 | +): string { | |
| 12 | + const matches = findSearchMatches(fileContent, oldString); | |
| 13 | + | |
| 14 | + if (matches.length === 0) { | |
| 15 | + throw new ContinueError( | |
| 16 | + ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 17 | + `Edit at index ${editIndex}: string not found in file: "${oldString}"`, | |
| 18 | + ); | |
| 19 | + } | |
| 20 | + | |
| 21 | + if (replaceAll) { | |
| 22 | + // Apply replacements in reverse order to maintain correct positions | |
| 23 | + let result = fileContent; | |
| 24 | + for (let i = matches.length - 1; i >= 0; i--) { | |
| 25 | + const match = matches[i]; | |
| 26 | + result = | |
| 27 | + result.substring(0, match.startIndex) + | |
| 28 | + newString + | |
| 29 | + result.substring(match.endIndex); | |
| 30 | + } | |
| 31 | + return result; | |
| 32 | + } else { | |
| 33 | + // For single replacement, check for multiple matches first | |
| 34 | + if (matches.length > 1) { | |
| 35 | + throw new ContinueError( | |
| 36 | + ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 37 | + `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.`, | |
| 38 | + ); | |
| 39 | + } | |
| 40 | + | |
| 41 | + // Apply single replacement | |
| 42 | + const match = matches[0]; | |
| 43 | + return ( | |
| 44 | + fileContent.substring(0, match.startIndex) + | |
| 45 | + newString + | |
| 46 | + fileContent.substring(match.endIndex) | |
| 47 | + ); | |
| 48 | + } | |
| 49 | +} | |
| 50 | + | |
| 51 | +export function executeMultiFindAndReplace( | |
| 52 | + fileContent: string, | |
| 53 | + edits: EditOperation[], | |
| 54 | +): string { | |
| 55 | + let result = fileContent; | |
| 56 | + | |
| 57 | + // Apply edits in sequence | |
| 58 | + for (let editIndex = 0; editIndex < edits.length; editIndex++) { | |
| 59 | + const edit = edits[editIndex]; | |
| 60 | + result = executeFindAndReplace( | |
| 61 | + result, | |
| 62 | + edit.old_string, | |
| 63 | + edit.new_string, | |
| 64 | + edit.replace_all ?? false, | |
| 65 | + editIndex, | |
| 66 | + ); | |
| 67 | + } | |
| 68 | + | |
| 69 | + return result; | |
| 70 | +} |
modified core/edit/streamDiffLines.ts +53 −40
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | ILLM, |
| 5 | 5 | Prediction, |
| 6 | 6 | RuleWithSource, |
| 7 | + StreamDiffLinesPayload, | |
| 7 | 8 | ToolResultChatMessage, |
| 8 | 9 | UserChatMessage, |
| 9 | 10 | } from "../"; |
| @@ -20,6 +21,7 @@ | ||
| 20 | 21 | import { streamLines } from "../diff/util"; |
| 21 | 22 | import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; |
| 22 | 23 | import { gptEditPrompt } from "../llm/templates/edit"; |
| 24 | +import { defaultApplyPrompt } from "../llm/templates/edit/gpt"; | |
| 23 | 25 | import { findLast } from "../util/findLast"; |
| 24 | 26 | import { Telemetry } from "../util/posthog"; |
| 25 | 27 | import { recursiveStream } from "./recursiveStream"; |
| @@ -42,6 +44,20 @@ | ||
| 42 | 44 | }); |
| 43 | 45 | } |
| 44 | 46 | |
| 47 | +function constructApplyPrompt( | |
| 48 | + originalCode: string, | |
| 49 | + newCode: string, | |
| 50 | + llm: ILLM, | |
| 51 | +) { | |
| 52 | + const template = llm.promptTemplates?.apply ?? defaultApplyPrompt; | |
| 53 | + const rendered = llm.renderPromptTemplate(template, [], { | |
| 54 | + original_code: originalCode, | |
| 55 | + new_code: newCode, | |
| 56 | + }); | |
| 57 | + | |
| 58 | + return rendered; | |
| 59 | +} | |
| 60 | + | |
| 45 | 61 | export async function* addIndentation( |
| 46 | 62 | diffLineGenerator: AsyncGenerator<DiffLine>, |
| 47 | 63 | indentation: string, |
| @@ -58,27 +74,15 @@ | ||
| 58 | 74 | return !(model.includes("gpt") || model.includes("claude")); |
| 59 | 75 | } |
| 60 | 76 | |
| 61 | -export async function* streamDiffLines({ | |
| 62 | - prefix, | |
| 63 | - highlighted, | |
| 64 | - suffix, | |
| 65 | - llm, | |
| 66 | - abortController, | |
| 67 | - input, | |
| 68 | - language, | |
| 69 | - overridePrompt, | |
| 70 | - rulesToInclude, | |
| 71 | -}: { | |
| 72 | - prefix: string; | |
| 73 | - highlighted: string; | |
| 74 | - suffix: string; | |
| 75 | - llm: ILLM; | |
| 76 | - abortController: AbortController; | |
| 77 | - input: string; | |
| 78 | - language: string | undefined; | |
| 79 | - overridePrompt: ChatMessage[] | undefined; | |
| 80 | - rulesToInclude: RuleWithSource[] | undefined; | |
| 81 | -}): AsyncGenerator<DiffLine> { | |
| 77 | +export async function* streamDiffLines( | |
| 78 | + options: StreamDiffLinesPayload, | |
| 79 | + llm: ILLM, | |
| 80 | + abortController: AbortController, | |
| 81 | + overridePrompt: ChatMessage[] | undefined, | |
| 82 | + rulesToInclude: RuleWithSource[] | undefined, | |
| 83 | +): AsyncGenerator<DiffLine> { | |
| 84 | + const { type, prefix, highlighted, suffix, input, language } = options; | |
| 85 | + | |
| 82 | 86 | void Telemetry.capture( |
| 83 | 87 | "inlineEdit", |
| 84 | 88 | { |
| @@ -104,27 +108,30 @@ | ||
| 104 | 108 | // For apply can be overridden with simply apply prompt |
| 105 | 109 | let prompt = |
| 106 | 110 | overridePrompt ?? |
| 107 | - constructEditPrompt(prefix, highlighted, suffix, llm, input, language); | |
| 111 | + (type === "apply" | |
| 112 | + ? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm) | |
| 113 | + : constructEditPrompt(prefix, highlighted, suffix, llm, input, language)); | |
| 108 | 114 | |
| 109 | 115 | // Rules can be included with edit prompt |
| 110 | 116 | // If any rules are present this will result in using chat instead of legacy completion |
| 111 | - const systemMessage = rulesToInclude | |
| 112 | - ? getSystemMessageWithRules({ | |
| 113 | - availableRules: rulesToInclude, | |
| 114 | - userMessage: | |
| 115 | - typeof prompt === "string" | |
| 116 | - ? ({ | |
| 117 | - role: "user", | |
| 118 | - content: prompt, | |
| 119 | - } as UserChatMessage) | |
| 120 | - : (findLast( | |
| 121 | - prompt, | |
| 122 | - (msg) => msg.role === "user" || msg.role === "tool", | |
| 123 | - ) as UserChatMessage | ToolResultChatMessage | undefined), | |
| 124 | - baseSystemMessage: undefined, | |
| 125 | - contextItems: [], | |
| 126 | - }).systemMessage | |
| 127 | - : undefined; | |
| 117 | + const systemMessage = | |
| 118 | + rulesToInclude || llm.baseChatSystemMessage | |
| 119 | + ? getSystemMessageWithRules({ | |
| 120 | + availableRules: rulesToInclude ?? [], | |
| 121 | + userMessage: | |
| 122 | + typeof prompt === "string" | |
| 123 | + ? ({ | |
| 124 | + role: "user", | |
| 125 | + content: prompt, | |
| 126 | + } as UserChatMessage) | |
| 127 | + : (findLast( | |
| 128 | + prompt, | |
| 129 | + (msg) => msg.role === "user" || msg.role === "tool", | |
| 130 | + ) as UserChatMessage | ToolResultChatMessage | undefined), | |
| 131 | + baseSystemMessage: llm.baseChatSystemMessage, | |
| 132 | + contextItems: [], | |
| 133 | + }).systemMessage | |
| 134 | + : undefined; | |
| 128 | 135 | |
| 129 | 136 | if (systemMessage) { |
| 130 | 137 | if (typeof prompt === "string") { |
| @@ -158,7 +165,13 @@ | ||
| 158 | 165 | content: highlighted, |
| 159 | 166 | }; |
| 160 | 167 | |
| 161 | - const completion = recursiveStream(llm, abortController, prompt, prediction); | |
| 168 | + const completion = recursiveStream( | |
| 169 | + llm, | |
| 170 | + abortController, | |
| 171 | + type, | |
| 172 | + prompt, | |
| 173 | + prediction, | |
| 174 | + ); | |
| 162 | 175 | |
| 163 | 176 | let lines = streamLines(completion); |
| 164 | 177 |
modified core/index.d.ts +42 −14
| @@ -173,6 +173,11 @@ | ||
| 173 | 173 | } |
| 174 | 174 | |
| 175 | 175 | export type ContextProviderType = "normal" | "query" | "submenu"; |
| 176 | +export type ContextIndexingType = | |
| 177 | + | "chunk" | |
| 178 | + | "embeddings" | |
| 179 | + | "fullTextSearch" | |
| 180 | + | "codeSnippets"; | |
| 176 | 181 | |
| 177 | 182 | export interface ContextProviderDescription { |
| 178 | 183 | title: ContextProviderName; |
| @@ -180,7 +185,7 @@ | ||
| 180 | 185 | description: string; |
| 181 | 186 | renderInlineAs?: string; |
| 182 | 187 | type: ContextProviderType; |
| 183 | - dependsOnIndexing?: boolean; | |
| 188 | + dependsOnIndexing?: ContextIndexingType[]; | |
| 184 | 189 | } |
| 185 | 190 | |
| 186 | 191 | export type FetchFunction = (url: string | URL, init?: any) => Promise<any>; |
| @@ -267,7 +272,7 @@ | ||
| 267 | 272 | history: ChatHistoryItem[]; |
| 268 | 273 | } |
| 269 | 274 | |
| 270 | -export interface SessionMetadata { | |
| 275 | +export interface BaseSessionMetadata { | |
| 271 | 276 | sessionId: string; |
| 272 | 277 | title: string; |
| 273 | 278 | dateCreated: string; |
| @@ -305,11 +310,6 @@ | ||
| 305 | 310 | replacement: string; |
| 306 | 311 | } |
| 307 | 312 | |
| 308 | -export interface ContinueError { | |
| 309 | - title: string; | |
| 310 | - message: string; | |
| 311 | -} | |
| 312 | - | |
| 313 | 313 | export interface CompletionOptions extends BaseCompletionOptions { |
| 314 | 314 | model: string; |
| 315 | 315 | } |
| @@ -456,7 +456,6 @@ | ||
| 456 | 456 | export interface PromptLog { |
| 457 | 457 | modelTitle: string; |
| 458 | 458 | modelProvider: string; |
| 459 | - completionOptions: CompletionOptions; | |
| 460 | 459 | prompt: string; |
| 461 | 460 | completion: string; |
| 462 | 461 | } |
| @@ -666,6 +665,7 @@ | ||
| 666 | 665 | env?: Record<string, string | number | boolean>; |
| 667 | 666 | |
| 668 | 667 | sourceFile?: string; |
| 668 | + isFromAutoDetect?: boolean; | |
| 669 | 669 | } |
| 670 | 670 | |
| 671 | 671 | type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick< |
| @@ -819,6 +819,8 @@ | ||
| 819 | 819 | |
| 820 | 820 | openUrl(url: string): Promise<void>; |
| 821 | 821 | |
| 822 | + getExternalUri?(uri: string): Promise<string>; | |
| 823 | + | |
| 822 | 824 | runCommand(command: string, options?: TerminalOptions): Promise<void>; |
| 823 | 825 | |
| 824 | 826 | saveFile(fileUri: string): Promise<void>; |
| @@ -1070,11 +1072,6 @@ | ||
| 1070 | 1072 | codeBaseIndexer?: CodebaseIndexer; |
| 1071 | 1073 | } |
| 1072 | 1074 | |
| 1073 | -export type ToolPolicy = | |
| 1074 | - | "allowedWithPermission" | |
| 1075 | - | "allowedWithoutPermission" | |
| 1076 | - | "disabled"; | |
| 1077 | - | |
| 1078 | 1075 | export interface Tool { |
| 1079 | 1076 | type: "function"; |
| 1080 | 1077 | function: { |
| @@ -1099,6 +1096,11 @@ | ||
| 1099 | 1096 | exampleArgs?: Array<[string, string | number]>; |
| 1100 | 1097 | }; |
| 1101 | 1098 | defaultToolPolicy?: ToolPolicy; |
| 1099 | + toolCallIcon?: string; | |
| 1100 | + evaluateToolCallPolicy?: ( | |
| 1101 | + basePolicy: ToolPolicy, | |
| 1102 | + parsedArgs: Record<string, unknown>, | |
| 1103 | + ) => ToolPolicy; | |
| 1102 | 1104 | } |
| 1103 | 1105 | |
| 1104 | 1106 | interface ToolChoice { |
| @@ -1111,6 +1113,9 @@ | ||
| 1111 | 1113 | export interface ConfigDependentToolParams { |
| 1112 | 1114 | rules: RuleWithSource[]; |
| 1113 | 1115 | enableExperimentalTools: boolean; |
| 1116 | + isSignedIn: boolean; | |
| 1117 | + isRemote: boolean; | |
| 1118 | + modelName: string | undefined; | |
| 1114 | 1119 | } |
| 1115 | 1120 | |
| 1116 | 1121 | export type GetTool = (params: ConfigDependentToolParams) => Tool; |
| @@ -1174,6 +1179,7 @@ | ||
| 1174 | 1179 | configurationStatus?: LLMConfigurationStatuses; |
| 1175 | 1180 | |
| 1176 | 1181 | sourceFile?: string; |
| 1182 | + isFromAutoDetect?: boolean; | |
| 1177 | 1183 | } |
| 1178 | 1184 | |
| 1179 | 1185 | export interface JSONEmbedOptions { |
| @@ -1273,6 +1279,7 @@ | ||
| 1273 | 1279 | transport: TransportOptions; |
| 1274 | 1280 | faviconUrl?: string; |
| 1275 | 1281 | timeout?: number; |
| 1282 | + requestOptions?: RequestOptions; | |
| 1276 | 1283 | } |
| 1277 | 1284 | |
| 1278 | 1285 | export type MCPConnectionStatus = |
| @@ -1325,6 +1332,7 @@ | ||
| 1325 | 1332 | export interface MCPServerStatus extends MCPOptions { |
| 1326 | 1333 | status: MCPConnectionStatus; |
| 1327 | 1334 | errors: string[]; |
| 1335 | + infos: string[]; | |
| 1328 | 1336 | isProtectedResource: boolean; |
| 1329 | 1337 | |
| 1330 | 1338 | prompts: MCPPrompt[]; |
| @@ -1342,6 +1350,7 @@ | ||
| 1342 | 1350 | codeWrap?: boolean; |
| 1343 | 1351 | showSessionTabs?: boolean; |
| 1344 | 1352 | autoAcceptEditToolDiffs?: boolean; |
| 1353 | + continueAfterToolRejection?: boolean; | |
| 1345 | 1354 | } |
| 1346 | 1355 | |
| 1347 | 1356 | export interface ContextMenuConfig { |
| @@ -1378,9 +1387,12 @@ | ||
| 1378 | 1387 | fileContent?: string; |
| 1379 | 1388 | originalFileContent?: string; |
| 1380 | 1389 | toolCallId?: string; |
| 1390 | + autoFormattingDiff?: string; | |
| 1381 | 1391 | } |
| 1382 | 1392 | |
| 1383 | -export interface StreamDiffLinesPayload { | |
| 1393 | +export type StreamDiffLinesType = "edit" | "apply"; | |
| 1394 | +interface StreamDiffLinesOptionsBase { | |
| 1395 | + type: StreamDiffLinesType; | |
| 1384 | 1396 | prefix: string; |
| 1385 | 1397 | highlighted: string; |
| 1386 | 1398 | suffix: string; |
| @@ -1391,6 +1403,19 @@ | ||
| 1391 | 1403 | fileUri?: string; |
| 1392 | 1404 | } |
| 1393 | 1405 | |
| 1406 | +interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase { | |
| 1407 | + type: "edit"; | |
| 1408 | +} | |
| 1409 | + | |
| 1410 | +interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase { | |
| 1411 | + type: "apply"; | |
| 1412 | + newCode: string; | |
| 1413 | +} | |
| 1414 | + | |
| 1415 | +type StreamDiffLinesPayload = | |
| 1416 | + | StreamDiffLinesOptionsApply | |
| 1417 | + | StreamDiffLinesOptionsEdit; | |
| 1418 | + | |
| 1394 | 1419 | export interface HighlightedCodePayload { |
| 1395 | 1420 | rangeInFileWithContents: RangeInFileWithContents; |
| 1396 | 1421 | prompt?: string; |
| @@ -1604,6 +1629,7 @@ | ||
| 1604 | 1629 | aiGatewaySlug?: string; |
| 1605 | 1630 | useLegacyCompletionsEndpoint?: boolean; |
| 1606 | 1631 | deploymentId?: string; |
| 1632 | + isFromAutoDetect?: boolean; | |
| 1607 | 1633 | } |
| 1608 | 1634 | |
| 1609 | 1635 | // config.json |
| @@ -1681,6 +1707,7 @@ | ||
| 1681 | 1707 | experimental?: ExperimentalConfig; |
| 1682 | 1708 | /** Analytics configuration */ |
| 1683 | 1709 | analytics?: AnalyticsConfig; |
| 1710 | + docs?: SiteIndexingConfig[]; | |
| 1684 | 1711 | data?: DataDestination[]; |
| 1685 | 1712 | } |
| 1686 | 1713 | |
| @@ -1796,6 +1823,7 @@ | ||
| 1796 | 1823 | description?: string; |
| 1797 | 1824 | ruleFile?: string; |
| 1798 | 1825 | alwaysApply?: boolean; |
| 1826 | + invokable?: boolean; | |
| 1799 | 1827 | } |
| 1800 | 1828 | export interface CompleteOnboardingPayload { |
| 1801 | 1829 | mode: OnboardingModes; |
modified core/indexing/CodebaseIndexer.test.ts +177 −61
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import { ContinueConfig } from "../index.js"; |
| 22 | 22 | import { localPathToUri } from "../util/pathToUri.js"; |
| 23 | 23 | import { CodebaseIndexer } from "./CodebaseIndexer.js"; |
| 24 | +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; | |
| 24 | 25 | import { getComputeDeleteAddRemove } from "./refreshIndex.js"; |
| 25 | 26 | import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; |
| 26 | 27 | import { CodebaseIndex } from "./types.js"; |
| @@ -64,8 +65,8 @@ | ||
| 64 | 65 | } |
| 65 | 66 | |
| 66 | 67 | // Add public methods to test private methods |
| 67 | - public testHasCodebaseContextProvider() { | |
| 68 | - return (this as any).hasCodebaseContextProvider(); | |
| 68 | + public testHasIndexingProvider() { | |
| 69 | + return (this as any).hasIndexingContextProvider(); | |
| 69 | 70 | } |
| 70 | 71 | |
| 71 | 72 | public async testHandleConfigUpdate( |
| @@ -202,7 +203,7 @@ | ||
| 202 | 203 | |
| 203 | 204 | test("should have indexed all of the files", async () => { |
| 204 | 205 | const indexed = await getAllIndexedFiles(); |
| 205 | - expect(indexed.length).toBe(4); // Files are indexed twice due to test execution | |
| 206 | + expect(indexed.length).toBe(2); | |
| 206 | 207 | expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true); |
| 207 | 208 | expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true); |
| 208 | 209 | }); |
| @@ -226,7 +227,7 @@ | ||
| 226 | 227 | |
| 227 | 228 | // Check that the new file was indexed |
| 228 | 229 | const files = await getAllIndexedFiles(); |
| 229 | - expect(files.length).toBe(5); // Updated to match actual behavior | |
| 230 | + expect(files.length).toBe(3); | |
| 230 | 231 | expect(files.some((file) => file.endsWith("main.rs"))).toBe(true); |
| 231 | 232 | }); |
| 232 | 233 | |
| @@ -240,7 +241,7 @@ | ||
| 240 | 241 | |
| 241 | 242 | // Check that the deleted file was removed from the index |
| 242 | 243 | const files = await getAllIndexedFiles(); |
| 243 | - expect(files.length).toBe(4); // Updated to match actual behavior | |
| 244 | + expect(files.length).toBe(2); | |
| 244 | 245 | expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true); |
| 245 | 246 | }); |
| 246 | 247 | |
| @@ -474,20 +475,14 @@ | ||
| 474 | 475 | jest.clearAllMocks(); |
| 475 | 476 | }); |
| 476 | 477 | |
| 477 | - describe("hasCodebaseContextProvider", () => { | |
| 478 | + describe("hasIndexingProvider", () => { | |
| 478 | 479 | test("should return true when codebase context provider is present", () => { |
| 479 | 480 | // Set up config with codebase context provider |
| 480 | 481 | (testIndexer as any).config = { |
| 481 | - contextProviders: [ | |
| 482 | - { | |
| 483 | - description: { | |
| 484 | - title: CodebaseContextProvider.description.title, | |
| 485 | - }, | |
| 486 | - }, | |
| 487 | - ], | |
| 482 | + contextProviders: [new CodebaseContextProvider({})], | |
| 488 | 483 | }; |
| 489 | 484 | |
| 490 | - const result = testIndexer.testHasCodebaseContextProvider(); | |
| 485 | + const result = testIndexer.testHasIndexingProvider(); | |
| 491 | 486 | expect(result).toBe(true); |
| 492 | 487 | }); |
| 493 | 488 | |
| @@ -496,7 +491,7 @@ | ||
| 496 | 491 | contextProviders: undefined, |
| 497 | 492 | }; |
| 498 | 493 | |
| 499 | - const result = testIndexer.testHasCodebaseContextProvider(); | |
| 494 | + const result = testIndexer.testHasIndexingProvider(); | |
| 500 | 495 | expect(result).toBe(false); |
| 501 | 496 | }); |
| 502 | 497 | |
| @@ -511,7 +506,7 @@ | ||
| 511 | 506 | ], |
| 512 | 507 | }; |
| 513 | 508 | |
| 514 | - const result = testIndexer.testHasCodebaseContextProvider(); | |
| 509 | + const result = testIndexer.testHasIndexingProvider(); | |
| 515 | 510 | expect(result).toBe(false); |
| 516 | 511 | }); |
| 517 | 512 | |
| @@ -520,7 +515,7 @@ | ||
| 520 | 515 | contextProviders: [], |
| 521 | 516 | }; |
| 522 | 517 | |
| 523 | - const result = testIndexer.testHasCodebaseContextProvider(); | |
| 518 | + const result = testIndexer.testHasIndexingProvider(); | |
| 524 | 519 | expect(result).toBe(false); |
| 525 | 520 | }); |
| 526 | 521 | }); |
| @@ -535,9 +530,8 @@ | ||
| 535 | 530 | |
| 536 | 531 | await testIndexer.testHandleConfigUpdate(configResult); |
| 537 | 532 | |
| 538 | - // These get called once on init, so we want them to not get called again | |
| 539 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 540 | - expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); | |
| 533 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0); | |
| 534 | + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0); | |
| 541 | 535 | }); |
| 542 | 536 | |
| 543 | 537 | test("should return early when newConfig is undefined", async () => { |
| @@ -549,9 +543,8 @@ | ||
| 549 | 543 | |
| 550 | 544 | await testIndexer.testHandleConfigUpdate(configResult); |
| 551 | 545 | |
| 552 | - // These get called once on init, so we want them to not get called again | |
| 553 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 554 | - expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); | |
| 546 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0); | |
| 547 | + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0); | |
| 555 | 548 | }); |
| 556 | 549 | |
| 557 | 550 | test("should return early when no codebase context provider is present", async () => { |
| @@ -577,21 +570,14 @@ | ||
| 577 | 570 | |
| 578 | 571 | await testIndexer.testHandleConfigUpdate(configResult); |
| 579 | 572 | |
| 580 | - // These get called once on init, so we want them to not get called again | |
| 581 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 582 | - expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); | |
| 573 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0); | |
| 574 | + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0); | |
| 583 | 575 | }); |
| 584 | 576 | |
| 585 | 577 | test("should return early when no embed model is configured", async () => { |
| 586 | 578 | const configResult: ConfigResult<ContinueConfig> = { |
| 587 | 579 | config: { |
| 588 | - contextProviders: [ | |
| 589 | - { | |
| 590 | - description: { | |
| 591 | - title: CodebaseContextProvider.description.title, | |
| 592 | - }, | |
| 593 | - }, | |
| 594 | - ], | |
| 580 | + contextProviders: [new CodebaseContextProvider({})], | |
| 595 | 581 | selectedModelByRole: { |
| 596 | 582 | embed: undefined, |
| 597 | 583 | }, |
| @@ -602,21 +588,14 @@ | ||
| 602 | 588 | |
| 603 | 589 | await testIndexer.testHandleConfigUpdate(configResult); |
| 604 | 590 | |
| 605 | - // These get called once on init, so we want them to not get called again | |
| 606 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 607 | - expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); | |
| 591 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0); | |
| 592 | + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0); | |
| 608 | 593 | }); |
| 609 | 594 | |
| 610 | 595 | test("should call refreshCodebaseIndex when all conditions are met", async () => { |
| 611 | 596 | const configResult: ConfigResult<ContinueConfig> = { |
| 612 | 597 | config: { |
| 613 | - contextProviders: [ | |
| 614 | - { | |
| 615 | - description: { | |
| 616 | - title: CodebaseContextProvider.description.title, | |
| 617 | - }, | |
| 618 | - }, | |
| 619 | - ], | |
| 598 | + contextProviders: [new CodebaseContextProvider({})], | |
| 620 | 599 | selectedModelByRole: { |
| 621 | 600 | embed: { |
| 622 | 601 | model: "test-model", |
| @@ -630,9 +609,8 @@ | ||
| 630 | 609 | |
| 631 | 610 | await testIndexer.testHandleConfigUpdate(configResult); |
| 632 | 611 | |
| 633 | - // These get called once on init, and we want them to get called again | |
| 634 | - expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2); | |
| 635 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); | |
| 612 | + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); | |
| 613 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 636 | 614 | expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([ |
| 637 | 615 | "/test/workspace", |
| 638 | 616 | ]); |
| @@ -640,13 +618,7 @@ | ||
| 640 | 618 | |
| 641 | 619 | test("should set config property before checking conditions", async () => { |
| 642 | 620 | const testConfig = { |
| 643 | - contextProviders: [ | |
| 644 | - { | |
| 645 | - description: { | |
| 646 | - title: CodebaseContextProvider.description.title, | |
| 647 | - }, | |
| 648 | - }, | |
| 649 | - ], | |
| 621 | + contextProviders: [new CodebaseContextProvider({})], | |
| 650 | 622 | selectedModelByRole: { |
| 651 | 623 | embed: { |
| 652 | 624 | model: "test-model", |
| @@ -666,7 +638,7 @@ | ||
| 666 | 638 | // Verify that the config was set |
| 667 | 639 | expect((testIndexer as any).config).toBe(testConfig); |
| 668 | 640 | // These get called once on init, and we want them to get called again |
| 669 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); | |
| 641 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 670 | 642 | }); |
| 671 | 643 | |
| 672 | 644 | test("should handle multiple context providers correctly", async () => { |
| @@ -678,11 +650,7 @@ | ||
| 678 | 650 | title: "SomeOtherProvider", |
| 679 | 651 | }, |
| 680 | 652 | }, |
| 681 | - { | |
| 682 | - description: { | |
| 683 | - title: CodebaseContextProvider.description.title, | |
| 684 | - }, | |
| 685 | - }, | |
| 653 | + new CodebaseContextProvider({}), | |
| 686 | 654 | { |
| 687 | 655 | description: { |
| 688 | 656 | title: "AnotherProvider", |
| @@ -702,12 +670,160 @@ | ||
| 702 | 670 | |
| 703 | 671 | await testIndexer.testHandleConfigUpdate(configResult); |
| 704 | 672 | |
| 705 | - // These get called once on init, and we want them to get called again | |
| 706 | - expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); | |
| 673 | + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); | |
| 707 | 674 | expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([ |
| 708 | 675 | "/test/workspace", |
| 709 | 676 | ]); |
| 710 | 677 | }); |
| 711 | 678 | }); |
| 679 | + | |
| 680 | + describe("getIndexesToBuild", () => { | |
| 681 | + let indexer: CodebaseIndexer; | |
| 682 | + let mockConfig: any; | |
| 683 | + let mockEmbeddingsModel: any; | |
| 684 | + let mockIdeSettings: any; | |
| 685 | + | |
| 686 | + beforeEach(async () => { | |
| 687 | + indexer = new CodebaseIndexer( | |
| 688 | + testConfigHandler, | |
| 689 | + testIde, | |
| 690 | + mockMessenger as any, | |
| 691 | + false, | |
| 692 | + ); | |
| 693 | + | |
| 694 | + mockEmbeddingsModel = { | |
| 695 | + maxEmbeddingChunkSize: 1000, | |
| 696 | + model: "test-model", | |
| 697 | + provider: "test-provider", | |
| 698 | + }; | |
| 699 | + | |
| 700 | + mockIdeSettings = { | |
| 701 | + remoteConfigServerUrl: "http://test.com", | |
| 702 | + userToken: "test-token", | |
| 703 | + }; | |
| 704 | + | |
| 705 | + mockConfig = { | |
| 706 | + selectedModelByRole: { | |
| 707 | + embed: mockEmbeddingsModel, | |
| 708 | + }, | |
| 709 | + contextProviders: [], | |
| 710 | + }; | |
| 711 | + | |
| 712 | + jest | |
| 713 | + .spyOn(testIde, "getIdeSettings") | |
| 714 | + .mockResolvedValue(mockIdeSettings); | |
| 715 | + }); | |
| 716 | + | |
| 717 | + afterEach(() => { | |
| 718 | + jest.clearAllMocks(); | |
| 719 | + }); | |
| 720 | + | |
| 721 | + test("should create specific indexTypes for the requested context providers", async () => { | |
| 722 | + mockConfig.contextProviders = [ | |
| 723 | + { | |
| 724 | + description: { | |
| 725 | + dependsOnIndexing: ["chunk", "codeSnippets"], | |
| 726 | + }, | |
| 727 | + }, | |
| 728 | + ]; | |
| 729 | + | |
| 730 | + jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({ | |
| 731 | + config: mockConfig, | |
| 732 | + errors: [], | |
| 733 | + configLoadInterrupted: false, | |
| 734 | + }); | |
| 735 | + | |
| 736 | + const indexes = (await ( | |
| 737 | + indexer as any | |
| 738 | + ).getIndexesToBuild()) as CodebaseIndex[]; | |
| 739 | + | |
| 740 | + expect(indexes).toHaveLength(2); | |
| 741 | + expect(indexes[0].artifactId).toBe("chunks"); | |
| 742 | + expect(indexes[1].artifactId).toBe("codeSnippets"); | |
| 743 | + }); | |
| 744 | + | |
| 745 | + test("should handle duplicate contexts", async () => { | |
| 746 | + mockConfig.contextProviders = [ | |
| 747 | + { | |
| 748 | + description: { | |
| 749 | + dependsOnIndexing: ["codeSnippets"], | |
| 750 | + }, | |
| 751 | + }, | |
| 752 | + { | |
| 753 | + description: { | |
| 754 | + dependsOnIndexing: ["codeSnippets"], | |
| 755 | + }, | |
| 756 | + }, | |
| 757 | + ]; | |
| 758 | + | |
| 759 | + jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({ | |
| 760 | + config: mockConfig, | |
| 761 | + errors: [], | |
| 762 | + configLoadInterrupted: false, | |
| 763 | + }); | |
| 764 | + | |
| 765 | + const indexes = await (indexer as any).getIndexesToBuild(); | |
| 766 | + | |
| 767 | + expect(indexes).toHaveLength(1); | |
| 768 | + expect(indexes[0].artifactId).toBe("codeSnippets"); | |
| 769 | + }); | |
| 770 | + }); | |
| 771 | + }); | |
| 772 | + | |
| 773 | + describe("wasAnyOneIndexAdded", () => { | |
| 774 | + let testIndexer: TestCodebaseIndexer; | |
| 775 | + let mockGetIndexesToBuild: jest.MockedFunction<any>; | |
| 776 | + | |
| 777 | + beforeEach(() => { | |
| 778 | + testIndexer = new TestCodebaseIndexer( | |
| 779 | + testConfigHandler, | |
| 780 | + testIde, | |
| 781 | + mockMessenger as any, | |
| 782 | + false, | |
| 783 | + ); | |
| 784 | + | |
| 785 | + // Mock getIndexesToBuild to control what indexes should be built | |
| 786 | + mockGetIndexesToBuild = jest | |
| 787 | + .spyOn(testIndexer as any, "getIndexesToBuild") | |
| 788 | + .mockResolvedValue([]); | |
| 789 | + | |
| 790 | + jest | |
| 791 | + .spyOn(testIndexer, "refreshCodebaseIndex") | |
| 792 | + .mockImplementation(async () => {}); | |
| 793 | + }); | |
| 794 | + | |
| 795 | + afterEach(() => { | |
| 796 | + jest.clearAllMocks(); | |
| 797 | + }); | |
| 798 | + | |
| 799 | + test("should return true when indexes to build differ from built indexes", async () => { | |
| 800 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 801 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 802 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1]); | |
| 803 | + (testIndexer as any).builtIndexes = [mockIndex2]; | |
| 804 | + | |
| 805 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 806 | + expect(result).toBe(true); | |
| 807 | + }); | |
| 808 | + | |
| 809 | + test("should return true when there are more indexes to build than built indexes", async () => { | |
| 810 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 811 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 812 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1, mockIndex2]); | |
| 813 | + (testIndexer as any).builtIndexes = [mockIndex1]; | |
| 814 | + | |
| 815 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 816 | + expect(result).toBe(true); | |
| 817 | + }); | |
| 818 | + | |
| 819 | + test("should return false when there are fewer indexes to build than built indexes", async () => { | |
| 820 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 821 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 822 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1]); | |
| 823 | + (testIndexer as any).builtIndexes = [mockIndex1, mockIndex2]; | |
| 824 | + | |
| 825 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 826 | + expect(result).toBe(false); | |
| 827 | + }); | |
| 712 | 828 | }); |
| 713 | 829 | }); |
modified core/indexing/CodebaseIndexer.ts +51 −34
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | 4 | import { |
| 5 | + ContextIndexingType, | |
| 5 | 6 | ContinueConfig, |
| 6 | 7 | IDE, |
| 7 | 8 | IndexingProgressUpdate, |
| @@ -12,11 +13,9 @@ | ||
| 12 | 13 | import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; |
| 13 | 14 | import { Logger } from "../util/Logger.js"; |
| 14 | 15 | import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; |
| 15 | -import { Telemetry } from "../util/posthog.js"; | |
| 16 | 16 | import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; |
| 17 | 17 | |
| 18 | 18 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 19 | -import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js"; | |
| 20 | 19 | import { ContinueServerClient } from "../continueServer/stubs/client"; |
| 21 | 20 | import { LLMError } from "../llm/index.js"; |
| 22 | 21 | import { getRootCause } from "../util/errors.js"; |
| @@ -60,6 +59,7 @@ | ||
| 60 | 59 | private indexingCancellationController: AbortController; |
| 61 | 60 | private codebaseIndexingState: IndexingProgressUpdate; |
| 62 | 61 | private readonly pauseToken: PauseToken; |
| 62 | + private builtIndexes: CodebaseIndex[] = []; | |
| 63 | 63 | |
| 64 | 64 | private getUserFriendlyIndexName(artifactId: string): string { |
| 65 | 65 | if (artifactId === FullTextSearchCodebaseIndex.artifactId) |
| @@ -168,28 +168,46 @@ | ||
| 168 | 168 | return []; |
| 169 | 169 | } |
| 170 | 170 | |
| 171 | - const indexes: CodebaseIndex[] = [ | |
| 172 | - new ChunkCodebaseIndex( | |
| 173 | - this.ide.readFile.bind(this.ide), | |
| 174 | - continueServerClient, | |
| 175 | - embeddingsModel.maxEmbeddingChunkSize, | |
| 176 | - ), // Chunking must come first | |
| 177 | - ]; | |
| 178 | - | |
| 179 | - const lanceDbIndex = await LanceDbIndex.create( | |
| 180 | - embeddingsModel, | |
| 181 | - this.ide.readFile.bind(this.ide), | |
| 171 | + const indexTypesToBuild = new Set( // use set to remove duplicates | |
| 172 | + config.contextProviders | |
| 173 | + .map((provider) => provider.description.dependsOnIndexing) | |
| 174 | + .filter((indexType) => Array.isArray(indexType)) // remove undefined indexTypes | |
| 175 | + .flat(), | |
| 182 | 176 | ); |
| 183 | 177 | |
| 184 | - if (lanceDbIndex) { | |
| 185 | - indexes.push(lanceDbIndex); | |
| 186 | - } | |
| 178 | + const indexTypeToIndexerMapping: Record< | |
| 179 | + ContextIndexingType, | |
| 180 | + () => Promise<CodebaseIndex | null> | |
| 181 | + > = { | |
| 182 | + chunk: async () => | |
| 183 | + new ChunkCodebaseIndex( | |
| 184 | + this.ide.readFile.bind(this.ide), | |
| 185 | + continueServerClient, | |
| 186 | + embeddingsModel.maxEmbeddingChunkSize, | |
| 187 | + ), | |
| 188 | + codeSnippets: async () => new CodeSnippetsCodebaseIndex(this.ide), | |
| 189 | + fullTextSearch: async () => new FullTextSearchCodebaseIndex(), | |
| 190 | + embeddings: async () => { | |
| 191 | + const lanceDbIndex = await LanceDbIndex.create( | |
| 192 | + embeddingsModel, | |
| 193 | + this.ide.readFile.bind(this.ide), | |
| 194 | + ); | |
| 195 | + return lanceDbIndex; | |
| 196 | + }, | |
| 197 | + }; | |
| 187 | 198 | |
| 188 | - indexes.push( | |
| 189 | - new FullTextSearchCodebaseIndex(), | |
| 190 | - new CodeSnippetsCodebaseIndex(this.ide), | |
| 191 | - ); | |
| 199 | + const indexes: CodebaseIndex[] = []; | |
| 200 | + // not parallelizing to avoid race conditions in sqlite | |
| 201 | + for (const indexType of indexTypesToBuild) { | |
| 202 | + if (indexType && indexType in indexTypeToIndexerMapping) { | |
| 203 | + const index = await indexTypeToIndexerMapping[indexType](); | |
| 204 | + if (index) { | |
| 205 | + indexes.push(index); | |
| 206 | + } | |
| 207 | + } | |
| 208 | + } | |
| 192 | 209 | |
| 210 | + this.builtIndexes = indexes; | |
| 193 | 211 | return indexes; |
| 194 | 212 | } |
| 195 | 213 | |
| @@ -668,14 +686,6 @@ | ||
| 668 | 686 | update.desc, |
| 669 | 687 | update.debugInfo, |
| 670 | 688 | ); |
| 671 | - void Telemetry.capture( | |
| 672 | - "indexing_error", | |
| 673 | - { | |
| 674 | - error: update.desc, | |
| 675 | - stack: update.debugInfo, | |
| 676 | - }, | |
| 677 | - false, | |
| 678 | - ); | |
| 679 | 689 | } |
| 680 | 690 | |
| 681 | 691 | /** |
| @@ -704,6 +714,15 @@ | ||
| 704 | 714 | } |
| 705 | 715 | } |
| 706 | 716 | |
| 717 | + public async wasAnyOneIndexAdded() { | |
| 718 | + const indexes = await this.getIndexesToBuild(); | |
| 719 | + return !indexes.every((index) => | |
| 720 | + this.builtIndexes.some( | |
| 721 | + (builtIndex) => builtIndex.artifactId === index.artifactId, | |
| 722 | + ), | |
| 723 | + ); | |
| 724 | + } | |
| 725 | + | |
| 707 | 726 | public async refreshCodebaseIndex(paths: string[]) { |
| 708 | 727 | if (!this.indexingCancellationController.signal.aborted) { |
| 709 | 728 | this.indexingCancellationController.abort(); |
| @@ -804,11 +823,9 @@ | ||
| 804 | 823 | return this.codebaseIndexingState; |
| 805 | 824 | } |
| 806 | 825 | |
| 807 | - private hasCodebaseContextProvider() { | |
| 826 | + private hasIndexingContextProvider() { | |
| 808 | 827 | return !!this.config.contextProviders?.some( |
| 809 | - (provider) => | |
| 810 | - provider.description.title === | |
| 811 | - CodebaseContextProvider.description.title, | |
| 828 | + ({ description: { dependsOnIndexing } }) => dependsOnIndexing, | |
| 812 | 829 | ); |
| 813 | 830 | } |
| 814 | 831 | |
| @@ -837,8 +854,8 @@ | ||
| 837 | 854 | this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in |
| 838 | 855 | |
| 839 | 856 | // No point in indexing if no codebase context provider |
| 840 | - const hasCodebaseContextProvider = this.hasCodebaseContextProvider(); | |
| 841 | - if (!hasCodebaseContextProvider) { | |
| 857 | + const hasIndexingProviders = this.hasIndexingContextProvider(); | |
| 858 | + if (!hasIndexingProviders) { | |
| 842 | 859 | return; |
| 843 | 860 | } |
| 844 | 861 |
modified core/indexing/chunk/chunk.ts +16 −1
| @@ -22,7 +22,22 @@ | ||
| 22 | 22 | return; |
| 23 | 23 | } |
| 24 | 24 | const extension = getUriFileExtension(fileUri); |
| 25 | - if (extension in supportedLanguages) { | |
| 25 | + // Files that should use basicChunker despite having tree-sitter support | |
| 26 | + // These files don't have code structure (classes/functions) that codeChunker expects | |
| 27 | + const NON_CODE_EXTENSIONS = [ | |
| 28 | + "css", | |
| 29 | + "html", | |
| 30 | + "htm", | |
| 31 | + "json", | |
| 32 | + "toml", | |
| 33 | + "yaml", | |
| 34 | + "yml", | |
| 35 | + ]; | |
| 36 | + | |
| 37 | + if ( | |
| 38 | + extension in supportedLanguages && | |
| 39 | + !NON_CODE_EXTENSIONS.includes(extension) | |
| 40 | + ) { | |
| 26 | 41 | try { |
| 27 | 42 | for await (const chunk of codeChunker(fileUri, contents, maxChunkSize)) { |
| 28 | 43 | yield chunk; |
modified core/indexing/chunk/code.test.ts +58 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { ChunkWithoutID } from "../.."; |
| 2 | - | |
| 2 | +import { cleanupAsyncEncoders, countTokensAsync } from "../../llm/countTokens"; | |
| 3 | 3 | import { codeChunker } from "./code"; |
| 4 | 4 | |
| 5 | 5 | async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> { |
| @@ -71,3 +71,60 @@ | ||
| 71 | 71 | expect(chunks).toContain('def method20():\n return "Hello, 20!"'); |
| 72 | 72 | }); |
| 73 | 73 | }); |
| 74 | + | |
| 75 | +async function collectContents( | |
| 76 | + filepath: string, | |
| 77 | + contents: string, | |
| 78 | + maxChunkSize: number, | |
| 79 | +): Promise<string[]> { | |
| 80 | + const out: string[] = []; | |
| 81 | + for await (const c of codeChunker(filepath, contents, maxChunkSize)) { | |
| 82 | + out.push(c.content); | |
| 83 | + } | |
| 84 | + return out; | |
| 85 | +} | |
| 86 | + | |
| 87 | +describe("codeChunker function definition", () => { | |
| 88 | + afterAll(async () => await cleanupAsyncEncoders()); | |
| 89 | + | |
| 90 | + test("class methods never exceed maxChunkSize", async () => { | |
| 91 | + const body = Array.from( | |
| 92 | + { length: 200 }, | |
| 93 | + (_, i) => `console.log(${i});`, | |
| 94 | + ).join("\n"); | |
| 95 | + const contents = ` | |
| 96 | +class C { | |
| 97 | + a() { | |
| 98 | + ${body} | |
| 99 | + } | |
| 100 | + b() { | |
| 101 | + ${body} | |
| 102 | + } | |
| 103 | +} | |
| 104 | +`; | |
| 105 | + const max = 50; | |
| 106 | + const chunks = await collectContents("filename1.ts", contents, max); | |
| 107 | + const counts = await Promise.all(chunks.map((s) => countTokensAsync(s))); | |
| 108 | + counts.forEach((n) => expect(n).toBeLessThanOrEqual(max)); | |
| 109 | + }); | |
| 110 | + | |
| 111 | + test("top-level functions never exceed maxChunkSize", async () => { | |
| 112 | + const body = Array.from( | |
| 113 | + { length: 150 }, | |
| 114 | + (_, i) => `const x${i} = ${i};`, | |
| 115 | + ).join("\n"); | |
| 116 | + const contents = ` | |
| 117 | +function f() { | |
| 118 | + ${body} | |
| 119 | +} | |
| 120 | + | |
| 121 | +function g() { | |
| 122 | + ${body} | |
| 123 | +} | |
| 124 | +`; | |
| 125 | + const max = 60; | |
| 126 | + const chunks = await collectContents("filename2.ts", contents, max); | |
| 127 | + const counts = await Promise.all(chunks.map((s) => countTokensAsync(s))); | |
| 128 | + counts.forEach((n) => expect(n).toBeLessThanOrEqual(max)); | |
| 129 | + }); | |
| 130 | +}); |
modified core/indexing/chunk/code.ts +36 −15
| @@ -128,25 +128,46 @@ | ||
| 128 | 128 | maxChunkSize: number, |
| 129 | 129 | ): Promise<string> { |
| 130 | 130 | const bodyNode = node.children[node.children.length - 1]; |
| 131 | - const funcText = | |
| 132 | - code.slice(node.startIndex, bodyNode.startIndex) + | |
| 133 | - collapsedReplacement(bodyNode); | |
| 134 | - | |
| 135 | - if ( | |
| 131 | + const collapsedBody = collapsedReplacement(bodyNode); | |
| 132 | + const signature = code.slice(node.startIndex, bodyNode.startIndex); | |
| 133 | + const funcText = signature + collapsedBody; | |
| 134 | + | |
| 135 | + const isInClass = | |
| 136 | 136 | node.parent && |
| 137 | 137 | ["block", "declaration_list"].includes(node.parent.type) && |
| 138 | 138 | node.parent.parent && |
| 139 | - ["class_definition", "impl_item"].includes(node.parent.parent.type) | |
| 140 | - ) { | |
| 141 | - // If inside a class, include the class header | |
| 142 | - const classNode = node.parent.parent; | |
| 143 | - const classBlock = node.parent; | |
| 144 | - return `${code.slice( | |
| 145 | - classNode.startIndex, | |
| 146 | - classBlock.startIndex, | |
| 147 | - )}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`; | |
| 139 | + ["class_definition", "impl_item"].includes(node.parent.parent.type); | |
| 140 | + | |
| 141 | + if (isInClass) { | |
| 142 | + const classNode = node.parent!.parent!; | |
| 143 | + const classBlock = node.parent!; | |
| 144 | + const classHeader = code.slice(classNode.startIndex, classBlock.startIndex); | |
| 145 | + const indent = " ".repeat(node.startPosition.column); | |
| 146 | + const combined = `${classHeader}...\n\n${indent}${funcText}`; | |
| 147 | + | |
| 148 | + if ((await countTokensAsync(combined)) <= maxChunkSize) { | |
| 149 | + return combined; | |
| 150 | + } | |
| 151 | + if ((await countTokensAsync(funcText)) <= maxChunkSize) { | |
| 152 | + return funcText; | |
| 153 | + } | |
| 154 | + const firstLine = signature.split("\n")[0] ?? ""; | |
| 155 | + const minimal = `${firstLine} ${collapsedBody}`; | |
| 156 | + if ((await countTokensAsync(minimal)) <= maxChunkSize) { | |
| 157 | + return minimal; | |
| 158 | + } | |
| 159 | + return collapsedBody; | |
| 160 | + } | |
| 161 | + | |
| 162 | + if ((await countTokensAsync(funcText)) <= maxChunkSize) { | |
| 163 | + return funcText; | |
| 164 | + } | |
| 165 | + const firstLine = signature.split("\n")[0] ?? ""; | |
| 166 | + const minimal = `${firstLine} ${collapsedBody}`; | |
| 167 | + if ((await countTokensAsync(minimal)) <= maxChunkSize) { | |
| 168 | + return minimal; | |
| 148 | 169 | } |
| 149 | - return funcText; | |
| 170 | + return collapsedBody; | |
| 150 | 171 | } |
| 151 | 172 | |
| 152 | 173 | const collapsedNodeConstructors: { |
added core/indexing/continueignore.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import { IDE } from ".."; | |
| 3 | +import { getGlobalContinueIgnorePath } from "../util/paths"; | |
| 4 | +import { gitIgArrayFromFile } from "./ignore"; | |
| 5 | + | |
| 6 | +export const getGlobalContinueIgArray = () => { | |
| 7 | + const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8"); | |
| 8 | + return gitIgArrayFromFile(contents); | |
| 9 | +}; | |
| 10 | + | |
| 11 | +export const getWorkspaceContinueIgArray = async (ide: IDE) => { | |
| 12 | + const dirs = await ide.getWorkspaceDirs(); | |
| 13 | + return await dirs.reduce( | |
| 14 | + async (accPromise, dir) => { | |
| 15 | + const acc = await accPromise; | |
| 16 | + try { | |
| 17 | + const contents = await ide.readFile(`${dir}/.continueignore`); | |
| 18 | + return [...acc, ...gitIgArrayFromFile(contents)]; | |
| 19 | + } catch (err) { | |
| 20 | + console.error(err); | |
| 21 | + return acc; | |
| 22 | + } | |
| 23 | + }, | |
| 24 | + Promise.resolve([] as string[]), | |
| 25 | + ); | |
| 26 | +}; |
modified core/indexing/docs/DocsService.ts +23 −2
| @@ -272,7 +272,7 @@ | ||
| 272 | 272 | id: doc.startUrl, |
| 273 | 273 | isReindexing: false, |
| 274 | 274 | title: doc.title, |
| 275 | - debugInfo: `max depth: ${doc.maxDepth}`, | |
| 275 | + debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`, | |
| 276 | 276 | icon: doc.faviconUrl, |
| 277 | 277 | url: doc.startUrl, |
| 278 | 278 | }; |
| @@ -468,7 +468,7 @@ | ||
| 468 | 468 | embeddingsProviderId: provider.embeddingId, |
| 469 | 469 | isReindexing: forceReindex && indexExists, |
| 470 | 470 | title: siteIndexingConfig.title, |
| 471 | - debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, | |
| 471 | + debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`, | |
| 472 | 472 | icon: siteIndexingConfig.faviconUrl, |
| 473 | 473 | url: siteIndexingConfig.startUrl, |
| 474 | 474 | }; |
| @@ -858,6 +858,27 @@ | ||
| 858 | 858 | return docs.map(this.lanceDBRowToChunk); |
| 859 | 859 | } |
| 860 | 860 | |
| 861 | + async getIndexedPages(startUrl: string): Promise<Set<string>> { | |
| 862 | + try { | |
| 863 | + const table = await this.getOrCreateLanceTable({ | |
| 864 | + initializationVector: [], | |
| 865 | + startUrl, | |
| 866 | + }); | |
| 867 | + | |
| 868 | + const rows = (await table | |
| 869 | + .filter(`starturl = '${startUrl}'`) | |
| 870 | + .select(["path"]) // Only select path to minimize data transfer | |
| 871 | + .limit(99999999) // Default is 10, we want to show all | |
| 872 | + .execute()) as { path: string }[]; | |
| 873 | + | |
| 874 | + // Get unique paths (pages) | |
| 875 | + return new Set(rows.map((row) => row.path)); | |
| 876 | + } catch (e) { | |
| 877 | + console.warn(`Error getting page list for ${startUrl}:`, e); | |
| 878 | + return new Set(); | |
| 879 | + } | |
| 880 | + } | |
| 881 | + | |
| 861 | 882 | // SQLITE DB |
| 862 | 883 | private async getOrCreateSqliteDb() { |
| 863 | 884 | if (!this.sqliteDb) { |
modified core/indexing/docs/crawlers/DocsCrawler.test.ts +21 −3
| @@ -155,9 +155,27 @@ | ||
| 155 | 155 | test( |
| 156 | 156 | `Default crawler common site: ${url}`, |
| 157 | 157 | async () => { |
| 158 | - const { pages, crawler } = await runCrawl(url); | |
| 159 | - expect(pages.length).toBeGreaterThanOrEqual(1); | |
| 160 | - expect(crawler).toEqual("default"); | |
| 158 | + // Retry logic to handle flaky network requests to TRIAL_PROXY_URL | |
| 159 | + let lastError; | |
| 160 | + const maxRetries = 3; | |
| 161 | + | |
| 162 | + for (let attempt = 1; attempt <= maxRetries; attempt++) { | |
| 163 | + try { | |
| 164 | + const { pages, crawler } = await runCrawl(url); | |
| 165 | + expect(pages.length).toBeGreaterThanOrEqual(1); | |
| 166 | + expect(crawler).toEqual("default"); | |
| 167 | + return; // Test passed, exit retry loop | |
| 168 | + } catch (error) { | |
| 169 | + lastError = error; | |
| 170 | + if (attempt === maxRetries) { | |
| 171 | + throw error; // Final attempt failed, throw the error | |
| 172 | + } | |
| 173 | + // Wait before retrying (exponential backoff) | |
| 174 | + await new Promise((resolve) => | |
| 175 | + setTimeout(resolve, 1000 * attempt), | |
| 176 | + ); | |
| 177 | + } | |
| 178 | + } | |
| 161 | 179 | }, |
| 162 | 180 | TIMEOUT_MS, |
| 163 | 181 | ); |
modified core/indexing/ignore.ts +170 −44
| @@ -1,11 +1,101 @@ | ||
| 1 | -import fs from "fs"; | |
| 2 | - | |
| 3 | 1 | import ignore from "ignore"; |
| 4 | 2 | |
| 5 | -import { IDE } from ".."; | |
| 6 | -import { getGlobalContinueIgnorePath } from "../util/paths"; | |
| 3 | +import path from "path"; | |
| 4 | +import { fileURLToPath } from "url"; | |
| 5 | +import { ContinueError, ContinueErrorReason } from "../util/errors"; | |
| 7 | 6 | |
| 8 | -export const DEFAULT_IGNORE_FILETYPES = [ | |
| 7 | +// Security-focused ignore patterns - these should always be excluded for security reasons | |
| 8 | +export const DEFAULT_SECURITY_IGNORE_FILETYPES = [ | |
| 9 | + // Environment and configuration files with secrets | |
| 10 | + "*.env", | |
| 11 | + "*.env.*", | |
| 12 | + ".env*", | |
| 13 | + "config.json", | |
| 14 | + "config.yaml", | |
| 15 | + "config.yml", | |
| 16 | + "settings.json", | |
| 17 | + "appsettings.json", | |
| 18 | + "appsettings.*.json", | |
| 19 | + | |
| 20 | + // Certificate and key files | |
| 21 | + "*.key", | |
| 22 | + "*.pem", | |
| 23 | + "*.p12", | |
| 24 | + "*.pfx", | |
| 25 | + "*.crt", | |
| 26 | + "*.cer", | |
| 27 | + "*.jks", | |
| 28 | + "*.keystore", | |
| 29 | + "*.truststore", | |
| 30 | + | |
| 31 | + // Database files that may contain sensitive data | |
| 32 | + "*.db", | |
| 33 | + "*.sqlite", | |
| 34 | + "*.sqlite3", | |
| 35 | + "*.mdb", | |
| 36 | + "*.accdb", | |
| 37 | + | |
| 38 | + // Credential and secret files | |
| 39 | + "*.secret", | |
| 40 | + "*.secrets", | |
| 41 | + "credentials", | |
| 42 | + "credentials.*", | |
| 43 | + "auth.json", | |
| 44 | + "token", | |
| 45 | + "token.*", | |
| 46 | + "*.token", | |
| 47 | + | |
| 48 | + // Backup files that might contain sensitive data | |
| 49 | + "*.bak", | |
| 50 | + "*.backup", | |
| 51 | + "*.old", | |
| 52 | + "*.orig", | |
| 53 | + | |
| 54 | + // Docker secrets | |
| 55 | + "docker-compose.override.yml", | |
| 56 | + "docker-compose.override.yaml", | |
| 57 | + | |
| 58 | + // SSH and GPG | |
| 59 | + "id_rsa", | |
| 60 | + "id_dsa", | |
| 61 | + "id_ecdsa", | |
| 62 | + "id_ed25519", | |
| 63 | + "*.ppk", | |
| 64 | + "*.gpg", | |
| 65 | +]; | |
| 66 | + | |
| 67 | +export const DEFAULT_SECURITY_IGNORE_DIRS = [ | |
| 68 | + // Environment and configuration directories | |
| 69 | + ".env/", | |
| 70 | + "env/", | |
| 71 | + | |
| 72 | + // Cloud provider credential directories | |
| 73 | + ".aws/", | |
| 74 | + ".gcp/", | |
| 75 | + ".azure/", | |
| 76 | + ".kube/", | |
| 77 | + ".docker/", | |
| 78 | + | |
| 79 | + // Secret directories | |
| 80 | + "secrets/", | |
| 81 | + ".secrets/", | |
| 82 | + "private/", | |
| 83 | + ".private/", | |
| 84 | + "certs/", | |
| 85 | + "certificates/", | |
| 86 | + "keys/", | |
| 87 | + ".ssh/", | |
| 88 | + ".gnupg/", | |
| 89 | + ".gpg/", | |
| 90 | + | |
| 91 | + // Temporary directories that might contain sensitive data | |
| 92 | + "tmp/secrets/", | |
| 93 | + "temp/secrets/", | |
| 94 | + ".tmp/", | |
| 95 | +]; | |
| 96 | + | |
| 97 | +// Additional non-security patterns for general indexing exclusion | |
| 98 | +export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [ | |
| 9 | 99 | "*.DS_Store", |
| 10 | 100 | "*-lock.json", |
| 11 | 101 | "*.lock", |
| @@ -46,8 +136,6 @@ | ||
| 46 | 136 | "*.mpeg", |
| 47 | 137 | "*.mov", |
| 48 | 138 | "*.mp3", |
| 49 | - "*.mp4", | |
| 50 | - "*.mkv", | |
| 51 | 139 | "*.mkv", |
| 52 | 140 | "*.webm", |
| 53 | 141 | "*.jar", |
| @@ -56,20 +144,15 @@ | ||
| 56 | 144 | "*.pqt", |
| 57 | 145 | "*.wav", |
| 58 | 146 | "*.webp", |
| 59 | - "*.db", | |
| 60 | - "*.sqlite", | |
| 61 | 147 | "*.wasm", |
| 62 | 148 | "*.plist", |
| 63 | 149 | "*.profraw", |
| 64 | 150 | "*.gcda", |
| 65 | 151 | "*.gcno", |
| 66 | 152 | "go.sum", |
| 67 | - "*.env", | |
| 68 | 153 | "*.gitignore", |
| 69 | 154 | "*.gitkeep", |
| 70 | 155 | "*.continueignore", |
| 71 | - "config.json", | |
| 72 | - "config.yaml", | |
| 73 | 156 | "*.csv", |
| 74 | 157 | "*.uasset", |
| 75 | 158 | "*.pdb", |
| @@ -78,19 +161,13 @@ | ||
| 78 | 161 | "*.swp", |
| 79 | 162 | "*.jsonl", |
| 80 | 163 | // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt |
| 164 | + // Application specific | |
| 165 | + ".continue/", | |
| 81 | 166 | ]; |
| 82 | 167 | |
| 83 | -export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); | |
| 84 | -export const DEFAULT_IGNORE_DIRS = [ | |
| 168 | +export const ADDITIONAL_INDEXING_IGNORE_DIRS = [ | |
| 85 | 169 | ".git/", |
| 86 | 170 | ".svn/", |
| 87 | - ".vscode/", | |
| 88 | - ".idea/", | |
| 89 | - ".vs/", | |
| 90 | - "venv/", | |
| 91 | - ".venv/", | |
| 92 | - "env/", | |
| 93 | - ".env/", | |
| 94 | 171 | "node_modules/", |
| 95 | 172 | "dist/", |
| 96 | 173 | "build/", |
| @@ -100,7 +177,6 @@ | ||
| 100 | 177 | "bin/", |
| 101 | 178 | ".pytest_cache/", |
| 102 | 179 | ".vscode-test/", |
| 103 | - ".continue/", | |
| 104 | 180 | "__pycache__/", |
| 105 | 181 | "site-packages/", |
| 106 | 182 | ".gradle/", |
| @@ -108,42 +184,92 @@ | ||
| 108 | 184 | ".cache/", |
| 109 | 185 | "gems/", |
| 110 | 186 | "vendor/", |
| 187 | + | |
| 188 | + ".venv/", | |
| 189 | + "venv/", | |
| 190 | + | |
| 191 | + ".vscode/", | |
| 192 | + ".idea/", | |
| 193 | + ".vs/", | |
| 194 | +]; | |
| 195 | + | |
| 196 | +// Combined patterns: security + additional | |
| 197 | +export const DEFAULT_IGNORE_FILETYPES = [ | |
| 198 | + ...DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 199 | + ...ADDITIONAL_INDEXING_IGNORE_FILETYPES, | |
| 200 | +]; | |
| 201 | + | |
| 202 | +export const DEFAULT_IGNORE_DIRS = [ | |
| 203 | + ...DEFAULT_SECURITY_IGNORE_DIRS, | |
| 204 | + ...ADDITIONAL_INDEXING_IGNORE_DIRS, | |
| 205 | +]; | |
| 206 | + | |
| 207 | +export const DEFAULT_IGNORES = [ | |
| 208 | + ...DEFAULT_IGNORE_FILETYPES, | |
| 209 | + ...DEFAULT_IGNORE_DIRS, | |
| 111 | 210 | ]; |
| 112 | 211 | |
| 212 | +export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`; | |
| 213 | + | |
| 214 | +// Create ignore instances | |
| 215 | +export const defaultSecurityIgnoreFile = ignore().add( | |
| 216 | + DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 217 | +); | |
| 218 | +export const defaultSecurityIgnoreDir = ignore().add( | |
| 219 | + DEFAULT_SECURITY_IGNORE_DIRS, | |
| 220 | +); | |
| 221 | +export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); | |
| 113 | 222 | export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); |
| 114 | 223 | |
| 224 | +// String representations | |
| 225 | +export const DEFAULT_SECURITY_IGNORE = | |
| 226 | + DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") + | |
| 227 | + "\n" + | |
| 228 | + DEFAULT_SECURITY_IGNORE_DIRS.join("\n"); | |
| 229 | + | |
| 115 | 230 | export const DEFAULT_IGNORE = |
| 116 | 231 | DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); |
| 117 | 232 | |
| 233 | +// Combined ignore instances | |
| 234 | +export const defaultFileAndFolderSecurityIgnores = ignore() | |
| 235 | + .add(defaultSecurityIgnoreFile) | |
| 236 | + .add(defaultSecurityIgnoreDir); | |
| 237 | + | |
| 118 | 238 | export const defaultIgnoreFileAndDir = ignore() |
| 119 | 239 | .add(defaultIgnoreFile) |
| 120 | 240 | .add(defaultIgnoreDir); |
| 121 | 241 | |
| 242 | +export function isSecurityConcern(filePathOrUri: string) { | |
| 243 | + if (!filePathOrUri) { | |
| 244 | + return false; | |
| 245 | + } | |
| 246 | + let filepath = filePathOrUri; | |
| 247 | + try { | |
| 248 | + filepath = fileURLToPath(filePathOrUri); | |
| 249 | + } catch {} | |
| 250 | + if (path.isAbsolute(filepath)) { | |
| 251 | + const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? ""; | |
| 252 | + const basename = path.basename(filepath); | |
| 253 | + filepath = `${dir ? dir + "/" : ""}${basename}`; | |
| 254 | + } | |
| 255 | + if (!filepath) { | |
| 256 | + return false; | |
| 257 | + } | |
| 258 | + return defaultFileAndFolderSecurityIgnores.ignores(filepath); | |
| 259 | +} | |
| 260 | + | |
| 261 | +export function throwIfFileIsSecurityConcern(filepath: string) { | |
| 262 | + if (isSecurityConcern(filepath)) { | |
| 263 | + throw new ContinueError( | |
| 264 | + ContinueErrorReason.FileIsSecurityConcern, | |
| 265 | + `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.`, | |
| 266 | + ); | |
| 267 | + } | |
| 268 | +} | |
| 269 | + | |
| 122 | 270 | export function gitIgArrayFromFile(file: string) { |
| 123 | 271 | return file |
| 124 | 272 | .split(/\r?\n/) // Split on new line |
| 125 | 273 | .map((l) => l.trim()) // Remove whitespace |
| 126 | 274 | .filter((l) => !/^#|^$/.test(l)); // Remove empty lines |
| 127 | 275 | } |
| 128 | - | |
| 129 | -export const getGlobalContinueIgArray = () => { | |
| 130 | - const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8"); | |
| 131 | - return gitIgArrayFromFile(contents); | |
| 132 | -}; | |
| 133 | - | |
| 134 | -export const getWorkspaceContinueIgArray = async (ide: IDE) => { | |
| 135 | - const dirs = await ide.getWorkspaceDirs(); | |
| 136 | - return await dirs.reduce( | |
| 137 | - async (accPromise, dir) => { | |
| 138 | - const acc = await accPromise; | |
| 139 | - try { | |
| 140 | - const contents = await ide.readFile(`${dir}/.continueignore`); | |
| 141 | - return [...acc, ...gitIgArrayFromFile(contents)]; | |
| 142 | - } catch (err) { | |
| 143 | - console.error(err); | |
| 144 | - return acc; | |
| 145 | - } | |
| 146 | - }, | |
| 147 | - Promise.resolve([] as string[]), | |
| 148 | - ); | |
| 149 | -}; |
added core/indexing/ignore.vitest.ts +257 −0
| @@ -0,0 +1,257 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + DEFAULT_SECURITY_IGNORE_DIRS, | |
| 4 | + DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 5 | + defaultFileAndFolderSecurityIgnores, | |
| 6 | + isSecurityConcern, | |
| 7 | +} from "./ignore"; | |
| 8 | + | |
| 9 | +describe("isSecurityConcern", () => { | |
| 10 | + describe("Security file types", () => { | |
| 11 | + it("should detect environment files as security concerns", () => { | |
| 12 | + expect(isSecurityConcern(".env")).toBe(true); | |
| 13 | + expect(isSecurityConcern(".env.local")).toBe(true); | |
| 14 | + expect(isSecurityConcern(".env.production")).toBe(true); | |
| 15 | + expect(isSecurityConcern("config/.env")).toBe(true); | |
| 16 | + expect(isSecurityConcern("/path/to/.env")).toBe(true); | |
| 17 | + expect(isSecurityConcern("file:///path/to/.env")).toBe(true); | |
| 18 | + }); | |
| 19 | + | |
| 20 | + it("should detect configuration files as security concerns", () => { | |
| 21 | + expect(isSecurityConcern("config.json")).toBe(true); | |
| 22 | + expect(isSecurityConcern("config.yaml")).toBe(true); | |
| 23 | + expect(isSecurityConcern("config.yml")).toBe(true); | |
| 24 | + expect(isSecurityConcern("settings.json")).toBe(true); | |
| 25 | + expect(isSecurityConcern("appsettings.json")).toBe(true); | |
| 26 | + expect(isSecurityConcern("appsettings.development.json")).toBe(true); | |
| 27 | + expect(isSecurityConcern("appsettings.production.json")).toBe(true); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should detect certificate and key files as security concerns", () => { | |
| 31 | + expect(isSecurityConcern("private.key")).toBe(true); | |
| 32 | + expect(isSecurityConcern("certificate.pem")).toBe(true); | |
| 33 | + expect(isSecurityConcern("server.crt")).toBe(true); | |
| 34 | + expect(isSecurityConcern("keystore.jks")).toBe(true); | |
| 35 | + expect(isSecurityConcern("ssl/server.key")).toBe(true); | |
| 36 | + expect(isSecurityConcern("/etc/ssl/certs/server.pem")).toBe(true); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should detect database files as security concerns", () => { | |
| 40 | + expect(isSecurityConcern("database.db")).toBe(true); | |
| 41 | + expect(isSecurityConcern("users.sqlite")).toBe(true); | |
| 42 | + expect(isSecurityConcern("data.sqlite3")).toBe(true); | |
| 43 | + expect(isSecurityConcern("app.mdb")).toBe(true); | |
| 44 | + expect(isSecurityConcern("data/users.db")).toBe(true); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should detect credential files as security concerns", () => { | |
| 48 | + expect(isSecurityConcern("app.secret")).toBe(true); | |
| 49 | + expect(isSecurityConcern("api.secrets")).toBe(true); | |
| 50 | + expect(isSecurityConcern("credentials")).toBe(true); | |
| 51 | + expect(isSecurityConcern("credentials.json")).toBe(true); | |
| 52 | + expect(isSecurityConcern("auth.json")).toBe(true); | |
| 53 | + expect(isSecurityConcern("token")).toBe(true); | |
| 54 | + expect(isSecurityConcern("api.token")).toBe(true); | |
| 55 | + expect(isSecurityConcern("access.token")).toBe(true); | |
| 56 | + }); | |
| 57 | + | |
| 58 | + it("should detect backup files as security concerns", () => { | |
| 59 | + expect(isSecurityConcern("database.bak")).toBe(true); | |
| 60 | + expect(isSecurityConcern("config.backup")).toBe(true); | |
| 61 | + expect(isSecurityConcern("settings.old")).toBe(true); | |
| 62 | + expect(isSecurityConcern("app.orig")).toBe(true); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("should detect Docker override files as security concerns", () => { | |
| 66 | + expect(isSecurityConcern("docker-compose.override.yml")).toBe(true); | |
| 67 | + expect(isSecurityConcern("docker-compose.override.yaml")).toBe(true); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("should detect SSH and GPG files as security concerns", () => { | |
| 71 | + expect(isSecurityConcern("id_rsa")).toBe(true); | |
| 72 | + expect(isSecurityConcern("id_dsa")).toBe(true); | |
| 73 | + expect(isSecurityConcern("id_ecdsa")).toBe(true); | |
| 74 | + expect(isSecurityConcern("id_ed25519")).toBe(true); | |
| 75 | + expect(isSecurityConcern("private.ppk")).toBe(true); | |
| 76 | + expect(isSecurityConcern("secret.gpg")).toBe(true); | |
| 77 | + }); | |
| 78 | + }); | |
| 79 | + | |
| 80 | + describe("Security directories", () => { | |
| 81 | + it("should detect environment directories as security concerns", () => { | |
| 82 | + expect(isSecurityConcern(".env/")).toBe(true); | |
| 83 | + expect(isSecurityConcern("env/")).toBe(true); | |
| 84 | + expect(isSecurityConcern(".env/config")).toBe(true); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("should detect cloud provider directories as security concerns", () => { | |
| 88 | + expect(isSecurityConcern(".aws/")).toBe(true); | |
| 89 | + expect(isSecurityConcern(".gcp/")).toBe(true); | |
| 90 | + expect(isSecurityConcern(".azure/")).toBe(true); | |
| 91 | + expect(isSecurityConcern(".kube/")).toBe(true); | |
| 92 | + expect(isSecurityConcern(".docker/")).toBe(true); | |
| 93 | + expect(isSecurityConcern(".aws/credentials")).toBe(true); | |
| 94 | + expect(isSecurityConcern(".kube/config")).toBe(true); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should detect secret directories as security concerns", () => { | |
| 98 | + expect(isSecurityConcern("secrets/")).toBe(true); | |
| 99 | + expect(isSecurityConcern(".secrets/")).toBe(true); | |
| 100 | + expect(isSecurityConcern("private/")).toBe(true); | |
| 101 | + expect(isSecurityConcern(".private/")).toBe(true); | |
| 102 | + expect(isSecurityConcern("certs/")).toBe(true); | |
| 103 | + expect(isSecurityConcern("certificates/")).toBe(true); | |
| 104 | + expect(isSecurityConcern("keys/")).toBe(true); | |
| 105 | + expect(isSecurityConcern(".ssh/")).toBe(true); | |
| 106 | + expect(isSecurityConcern(".gnupg/")).toBe(true); | |
| 107 | + expect(isSecurityConcern(".gpg/")).toBe(true); | |
| 108 | + }); | |
| 109 | + | |
| 110 | + it("should detect continue directory as security concern", () => { | |
| 111 | + expect(isSecurityConcern(".continue/config.json")).toBe(true); | |
| 112 | + }); | |
| 113 | + | |
| 114 | + it("should detect temporary secret directories as security concerns", () => { | |
| 115 | + expect(isSecurityConcern("tmp/secrets/")).toBe(true); | |
| 116 | + expect(isSecurityConcern("temp/secrets/")).toBe(true); | |
| 117 | + expect(isSecurityConcern(".tmp/")).toBe(true); | |
| 118 | + expect(isSecurityConcern("tmp/secrets/api.key")).toBe(true); | |
| 119 | + }); | |
| 120 | + }); | |
| 121 | + | |
| 122 | + describe("Path variations", () => { | |
| 123 | + it("should handle absolute paths", () => { | |
| 124 | + expect(isSecurityConcern("/home/user/.env")).toBe(true); | |
| 125 | + expect(isSecurityConcern("/var/www/.secrets/")).toBe(true); | |
| 126 | + expect(isSecurityConcern("/etc/ssl/private.key")).toBe(true); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + it("should handle URI schemes", () => { | |
| 130 | + expect(isSecurityConcern("file:///home/user/.env")).toBe(true); | |
| 131 | + expect(isSecurityConcern("file:///var/secrets/api.key")).toBe(true); | |
| 132 | + }); | |
| 133 | + | |
| 134 | + it("should handle nested paths", () => { | |
| 135 | + expect(isSecurityConcern("project/config/.env")).toBe(true); | |
| 136 | + expect(isSecurityConcern("src/main/resources/application.secret")).toBe( | |
| 137 | + true, | |
| 138 | + ); | |
| 139 | + expect(isSecurityConcern("backend/certs/server.key")).toBe(true); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + // it("should handle Windows-style paths", () => { | |
| 143 | + // expect(isSecurityConcern("C:\\Users\\user\\.env")).toBe(true); | |
| 144 | + // expect(isSecurityConcern("D:\\projects\\app\\secrets\\")).toBe(true); | |
| 145 | + // }); | |
| 146 | + }); | |
| 147 | + | |
| 148 | + describe("Non-security files", () => { | |
| 149 | + it("should not flag regular source code files", () => { | |
| 150 | + expect(isSecurityConcern("src/main.js")).toBe(false); | |
| 151 | + expect(isSecurityConcern("components/App.tsx")).toBe(false); | |
| 152 | + expect(isSecurityConcern("utils/helper.py")).toBe(false); | |
| 153 | + expect(isSecurityConcern("models/User.java")).toBe(false); | |
| 154 | + expect(isSecurityConcern("styles/main.css")).toBe(false); | |
| 155 | + }); | |
| 156 | + | |
| 157 | + it("should not flag regular configuration files", () => { | |
| 158 | + expect(isSecurityConcern("package.json")).toBe(false); | |
| 159 | + expect(isSecurityConcern("tsconfig.json")).toBe(false); | |
| 160 | + expect(isSecurityConcern("webpack.config.js")).toBe(false); | |
| 161 | + expect(isSecurityConcern("babel.config.js")).toBe(false); | |
| 162 | + expect(isSecurityConcern("jest.config.js")).toBe(false); | |
| 163 | + }); | |
| 164 | + | |
| 165 | + it("should not flag documentation files", () => { | |
| 166 | + expect(isSecurityConcern("README.md")).toBe(false); | |
| 167 | + expect(isSecurityConcern("CHANGELOG.md")).toBe(false); | |
| 168 | + expect(isSecurityConcern("docs/api.md")).toBe(false); | |
| 169 | + expect(isSecurityConcern("LICENSE")).toBe(false); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + it("should not flag regular directories", () => { | |
| 173 | + expect(isSecurityConcern("src/")).toBe(false); | |
| 174 | + expect(isSecurityConcern("components/")).toBe(false); | |
| 175 | + expect(isSecurityConcern("utils/")).toBe(false); | |
| 176 | + expect(isSecurityConcern("tests/")).toBe(false); | |
| 177 | + expect(isSecurityConcern("docs/")).toBe(false); | |
| 178 | + }); | |
| 179 | + | |
| 180 | + it("should not flag files with similar names but different extensions", () => { | |
| 181 | + expect(isSecurityConcern("environment.js")).toBe(false); | |
| 182 | + expect(isSecurityConcern("config-template.json")).toBe(false); | |
| 183 | + expect(isSecurityConcern("secret-utils.js")).toBe(false); | |
| 184 | + expect(isSecurityConcern("token-validator.ts")).toBe(false); | |
| 185 | + }); | |
| 186 | + }); | |
| 187 | + | |
| 188 | + describe("Edge cases", () => { | |
| 189 | + it("should handle empty strings", () => { | |
| 190 | + expect(isSecurityConcern("")).toBe(false); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + it("should handle paths with only separators", () => { | |
| 194 | + expect(isSecurityConcern("/")).toBe(false); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should handle paths with multiple extensions", () => { | |
| 198 | + expect(isSecurityConcern("backup.env.old")).toBe(true); // matches *.old | |
| 199 | + expect(isSecurityConcern("config.json.bak")).toBe(true); // matches *.bak | |
| 200 | + expect(isSecurityConcern("server.key.backup")).toBe(true); // matches *.backup | |
| 201 | + }); | |
| 202 | + | |
| 203 | + it("should handle files in root vs subdirectories", () => { | |
| 204 | + expect(isSecurityConcern(".env")).toBe(true); | |
| 205 | + expect(isSecurityConcern("project/.env")).toBe(true); | |
| 206 | + expect(isSecurityConcern("deeply/nested/path/.env")).toBe(true); | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + describe("Pattern matching consistency", () => { | |
| 211 | + it("should match all defined security file patterns", () => { | |
| 212 | + // Test a sample from each category to ensure patterns work | |
| 213 | + DEFAULT_SECURITY_IGNORE_FILETYPES.forEach((pattern) => { | |
| 214 | + // Create a test file name that should match the pattern | |
| 215 | + let testFile: string; | |
| 216 | + if (pattern.startsWith("*.")) { | |
| 217 | + testFile = `test${pattern.substring(1)}`; | |
| 218 | + } else if (pattern.includes("*")) { | |
| 219 | + testFile = pattern.replace("*", "test"); | |
| 220 | + } else { | |
| 221 | + testFile = pattern; | |
| 222 | + } | |
| 223 | + | |
| 224 | + expect(isSecurityConcern(testFile)).toBe(true); | |
| 225 | + }); | |
| 226 | + }); | |
| 227 | + | |
| 228 | + it("should match all defined security directory patterns", () => { | |
| 229 | + DEFAULT_SECURITY_IGNORE_DIRS.forEach((pattern) => { | |
| 230 | + // Test the directory pattern directly | |
| 231 | + expect(isSecurityConcern(pattern)).toBe(true); | |
| 232 | + | |
| 233 | + // Test a file inside the directory | |
| 234 | + const fileInDir = `${pattern}testfile.txt`; | |
| 235 | + expect(isSecurityConcern(fileInDir)).toBe(true); | |
| 236 | + }); | |
| 237 | + }); | |
| 238 | + }); | |
| 239 | + | |
| 240 | + describe("Integration with ignore library", () => { | |
| 241 | + it("should use the same ignore instance as defaultFileAndFolderSecurityIgnores", () => { | |
| 242 | + // Test that our function uses the same logic as the exported ignore instance | |
| 243 | + const testFiles = [ | |
| 244 | + ".env", | |
| 245 | + "secrets/api.key", | |
| 246 | + ".aws/credentials", | |
| 247 | + "regular-file.js", | |
| 248 | + ]; | |
| 249 | + | |
| 250 | + testFiles.forEach((file) => { | |
| 251 | + const functionResult = isSecurityConcern(file); | |
| 252 | + const ignoreResult = defaultFileAndFolderSecurityIgnores.ignores(file); | |
| 253 | + expect(functionResult).toBe(ignoreResult); | |
| 254 | + }); | |
| 255 | + }); | |
| 256 | + }); | |
| 257 | +}); |
modified core/indexing/shouldIgnore.ts +2 −1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import ignore from "ignore"; |
| 2 | 2 | import type { FileType, IDE } from "../"; |
| 3 | 3 | import { findUriInDirs, getUriPathBasename } from "../util/uri"; |
| 4 | -import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; | |
| 4 | +import { getGlobalContinueIgArray } from "./continueignore"; | |
| 5 | +import { defaultIgnoreFileAndDir } from "./ignore"; | |
| 5 | 6 | import { getIgnoreContext } from "./walkDir"; |
| 6 | 7 | |
| 7 | 8 | /* |
modified core/indexing/walkDir.ts +2 −5
| @@ -3,11 +3,8 @@ | ||
| 3 | 3 | import type { FileType, IDE } from ".."; |
| 4 | 4 | |
| 5 | 5 | import { joinPathsToUri } from "../util/uri"; |
| 6 | -import { | |
| 7 | - defaultIgnoreFileAndDir, | |
| 8 | - getGlobalContinueIgArray, | |
| 9 | - gitIgArrayFromFile, | |
| 10 | -} from "./ignore"; | |
| 6 | +import { getGlobalContinueIgArray } from "./continueignore"; | |
| 7 | +import { defaultIgnoreFileAndDir, gitIgArrayFromFile } from "./ignore"; | |
| 11 | 8 | |
| 12 | 9 | export interface WalkerOptions { |
| 13 | 10 | include?: "dirs" | "files" | "both"; |
modified core/llm/autodetect.ts +54 −24
| @@ -1,4 +1,9 @@ | ||
| 1 | -import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; | |
| 1 | +import { | |
| 2 | + ChatMessage, | |
| 3 | + ModelCapability, | |
| 4 | + ModelDescription, | |
| 5 | + TemplateType, | |
| 6 | +} from "../index.js"; | |
| 2 | 7 | import { NEXT_EDIT_MODELS } from "./constants.js"; |
| 3 | 8 | |
| 4 | 9 | import { |
| @@ -40,6 +45,7 @@ | ||
| 40 | 45 | |
| 41 | 46 | const PROVIDER_HANDLES_TEMPLATING: string[] = [ |
| 42 | 47 | "lmstudio", |
| 48 | + "lemonade", | |
| 43 | 49 | "openai", |
| 44 | 50 | "nvidia", |
| 45 | 51 | "ollama", |
| @@ -62,6 +68,7 @@ | ||
| 62 | 68 | const PROVIDER_SUPPORTS_IMAGES: string[] = [ |
| 63 | 69 | "openai", |
| 64 | 70 | "ollama", |
| 71 | + "lemonade", | |
| 65 | 72 | "cohere", |
| 66 | 73 | "gemini", |
| 67 | 74 | "msty", |
| @@ -80,26 +87,24 @@ | ||
| 80 | 87 | "watsonx", |
| 81 | 88 | ]; |
| 82 | 89 | |
| 83 | -const MODEL_SUPPORTS_IMAGES: string[] = [ | |
| 84 | - "llava", | |
| 85 | - "gpt-4-turbo", | |
| 86 | - "gpt-4o", | |
| 87 | - "gpt-4o-mini", | |
| 88 | - "gpt-4-vision", | |
| 89 | - "claude-3", | |
| 90 | - "c4ai-aya-vision-8b", | |
| 91 | - "c4ai-aya-vision-32b", | |
| 92 | - "gemini-ultra", | |
| 93 | - "gemini-1.5-pro", | |
| 94 | - "gemini-1.5-flash", | |
| 95 | - "sonnet", | |
| 96 | - "opus", | |
| 97 | - "haiku", | |
| 98 | - "pixtral", | |
| 99 | - "llama3.2", | |
| 100 | - "llama-3.2", | |
| 101 | - "llama4", | |
| 102 | - "granite-vision", | |
| 90 | +const MODEL_SUPPORTS_IMAGES: RegExp[] = [ | |
| 91 | + /llava/, | |
| 92 | + /gpt-4-turbo/, | |
| 93 | + /gpt-4o/, | |
| 94 | + /gpt-4o-mini/, | |
| 95 | + /claude-3/, | |
| 96 | + /gemini-ultra/, | |
| 97 | + /gemini-1\.5-pro/, | |
| 98 | + /gemini-1\.5-flash/, | |
| 99 | + /sonnet/, | |
| 100 | + /opus/, | |
| 101 | + /haiku/, | |
| 102 | + /pixtral/, | |
| 103 | + /llama-?3\.2/, | |
| 104 | + /llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed | |
| 105 | + /\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't! | |
| 106 | + /\b(pali|med)gemma/, | |
| 107 | + /qwen(.*)vl/, | |
| 103 | 108 | ]; |
| 104 | 109 | |
| 105 | 110 | function modelSupportsImages( |
| @@ -115,10 +120,14 @@ | ||
| 115 | 120 | return false; |
| 116 | 121 | } |
| 117 | 122 | |
| 118 | - const lower = model.toLowerCase(); | |
| 123 | + const lowerModel = model.toLowerCase(); | |
| 124 | + const lowerTitle = title?.toLowerCase() ?? ""; | |
| 125 | + | |
| 119 | 126 | if ( |
| 127 | + lowerModel.includes("vision") || | |
| 128 | + lowerTitle.includes("vision") || | |
| 120 | 129 | MODEL_SUPPORTS_IMAGES.some( |
| 121 | - (modelName) => lower.includes(modelName) || title?.includes(modelName), | |
| 130 | + (modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle), | |
| 122 | 131 | ) |
| 123 | 132 | ) { |
| 124 | 133 | return true; |
| @@ -126,6 +135,26 @@ | ||
| 126 | 135 | |
| 127 | 136 | return false; |
| 128 | 137 | } |
| 138 | + | |
| 139 | +function modelSupportsReasoning( | |
| 140 | + model: ModelDescription | null | undefined, | |
| 141 | +): boolean { | |
| 142 | + if (!model) { | |
| 143 | + return false; | |
| 144 | + } | |
| 145 | + if ("anthropic" === model.underlyingProviderName) { | |
| 146 | + return true; | |
| 147 | + } | |
| 148 | + if (model.model.includes("deepseek-r")) { | |
| 149 | + return true; | |
| 150 | + } | |
| 151 | + if (model.completionOptions?.reasoning) { | |
| 152 | + // Reasoning support is forced at the config level. Model might not necessarily support it though! | |
| 153 | + return true; | |
| 154 | + } | |
| 155 | + return false; | |
| 156 | +} | |
| 157 | + | |
| 129 | 158 | const PARALLEL_PROVIDERS: string[] = [ |
| 130 | 159 | "anthropic", |
| 131 | 160 | "bedrock", |
| @@ -177,7 +206,7 @@ | ||
| 177 | 206 | // NOTE: When updating this list, |
| 178 | 207 | // update core/nextEdit/templating/NextEditPromptEngine.ts as well. |
| 179 | 208 | const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ |
| 180 | - NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, | |
| 209 | + NEXT_EDIT_MODELS.MERCURY_CODER, | |
| 181 | 210 | NEXT_EDIT_MODELS.INSTINCT, |
| 182 | 211 | ]; |
| 183 | 212 | |
| @@ -421,4 +450,5 @@ | ||
| 421 | 450 | llmCanGenerateInParallel, |
| 422 | 451 | modelSupportsImages, |
| 423 | 452 | modelSupportsNextEdit, |
| 453 | + modelSupportsReasoning, | |
| 424 | 454 | }; |
modified core/llm/autodetect.vitest.ts +12 −12
| @@ -220,7 +220,7 @@ | ||
| 220 | 220 | expect( |
| 221 | 221 | modelSupportsNextEdit( |
| 222 | 222 | { nextEdit: false }, |
| 223 | - "mercury-coder-nextedit", | |
| 223 | + "mercury-coder", | |
| 224 | 224 | "Mercury Coder", |
| 225 | 225 | ), |
| 226 | 226 | ).toBe(false); |
| @@ -231,7 +231,7 @@ | ||
| 231 | 231 | expect( |
| 232 | 232 | modelSupportsNextEdit( |
| 233 | 233 | { nextEdit: false }, |
| 234 | - "mercury-coder-nextedit", | |
| 234 | + "mercury-coder", | |
| 235 | 235 | "Mercury Coder", |
| 236 | 236 | ), |
| 237 | 237 | ).toBe(false); |
| @@ -239,10 +239,10 @@ | ||
| 239 | 239 | }); |
| 240 | 240 | |
| 241 | 241 | describe("when capabilities.nextEdit is undefined", () => { |
| 242 | - it("should return true for mercury-coder-nextedit model (case insensitive)", () => { | |
| 243 | - expect( | |
| 244 | - modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined), | |
| 245 | - ).toBe(true); | |
| 242 | + it("should return true for mercury-coder model (case insensitive)", () => { | |
| 243 | + expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe( | |
| 244 | + true, | |
| 245 | + ); | |
| 246 | 246 | }); |
| 247 | 247 | |
| 248 | 248 | it("should return true for instinct", () => { |
| @@ -255,7 +255,7 @@ | ||
| 255 | 255 | expect( |
| 256 | 256 | modelSupportsNextEdit( |
| 257 | 257 | undefined, |
| 258 | - "provider/mercury-coder-nextedit-v2", | |
| 258 | + "provider/mercury-coder-v2", | |
| 259 | 259 | undefined, |
| 260 | 260 | ), |
| 261 | 261 | ).toBe(true); |
| @@ -266,7 +266,7 @@ | ||
| 266 | 266 | modelSupportsNextEdit( |
| 267 | 267 | undefined, |
| 268 | 268 | "some-model", |
| 269 | - "This is mercury-coder-nextedit model", | |
| 269 | + "This is mercury-coder model", | |
| 270 | 270 | ), |
| 271 | 271 | ).toBe(true); |
| 272 | 272 | }); |
| @@ -312,14 +312,14 @@ | ||
| 312 | 312 | }); |
| 313 | 313 | |
| 314 | 314 | it("should handle undefined title gracefully", () => { |
| 315 | - expect( | |
| 316 | - modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined), | |
| 317 | - ).toBe(true); | |
| 315 | + expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe( | |
| 316 | + true, | |
| 317 | + ); | |
| 318 | 318 | }); |
| 319 | 319 | |
| 320 | 320 | it("should handle case sensitivity correctly", () => { |
| 321 | 321 | expect( |
| 322 | - modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"), | |
| 322 | + modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"), | |
| 323 | 323 | ).toBe(true); |
| 324 | 324 | }); |
| 325 | 325 |
modified core/llm/constants.ts +1 −1
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | } |
| 21 | 21 | |
| 22 | 22 | export enum NEXT_EDIT_MODELS { |
| 23 | - MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", | |
| 23 | + MERCURY_CODER = "mercury-coder", | |
| 24 | 24 | INSTINCT = "instinct", |
| 25 | 25 | } |
| 26 | 26 |
modified core/llm/countTokens.ts +1 −1
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | |
| 86 | 86 | function countImageTokens(content: MessagePart): number { |
| 87 | 87 | if (content.type === "imageUrl") { |
| 88 | - return 85; | |
| 88 | + return 1024; | |
| 89 | 89 | } |
| 90 | 90 | throw new Error("Non-image content type"); |
| 91 | 91 | } |
modified core/llm/defaultSystemMessages.ts +11 −1
| @@ -46,6 +46,8 @@ | ||
| 46 | 46 | of changes unless the user specifically asks for code only. |
| 47 | 47 | `; |
| 48 | 48 | |
| 49 | +const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`; | |
| 50 | + | |
| 49 | 51 | export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ |
| 50 | 52 | <important_rules> |
| 51 | 53 | You are in chat mode. |
| @@ -64,6 +66,11 @@ | ||
| 64 | 66 | If you need to use multiple tools, you can call multiple read only tools simultaneously. |
| 65 | 67 | |
| 66 | 68 | ${CODEBLOCK_FORMATTING_INSTRUCTIONS} |
| 69 | + | |
| 70 | +${BRIEF_LAZY_INSTRUCTIONS} | |
| 71 | + | |
| 72 | +However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools. | |
| 73 | + | |
| 67 | 74 | </important_rules>`; |
| 68 | 75 | |
| 69 | 76 | // The note about read-only tools is for MCP servers |
| @@ -75,7 +82,10 @@ | ||
| 75 | 82 | If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates. |
| 76 | 83 | |
| 77 | 84 | ${CODEBLOCK_FORMATTING_INSTRUCTIONS} |
| 78 | -${EDIT_CODE_INSTRUCTIONS} | |
| 85 | + | |
| 86 | +${BRIEF_LAZY_INSTRUCTIONS} | |
| 87 | + | |
| 88 | +However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode. | |
| 79 | 89 | |
| 80 | 90 | In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan. |
| 81 | 91 | </important_rules>`; |
modified core/llm/index.test.ts +21 −0
| @@ -95,10 +95,31 @@ | ||
| 95 | 95 | test("should return true when modelSupportsImages returns true", () => { |
| 96 | 96 | baseLLM.model = "gpt-4-vision"; |
| 97 | 97 | expect(baseLLM.supportsImages()).toBe(true); |
| 98 | + | |
| 99 | + baseLLM.model = "fancy-vision-model"; | |
| 100 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 101 | + | |
| 102 | + baseLLM.model = "gemma3:4b"; | |
| 103 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 104 | + | |
| 105 | + baseLLM.model = "google/gemma-3-270m"; | |
| 106 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 107 | + | |
| 108 | + baseLLM.model = "foo/paligemma-custom-100"; | |
| 109 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 110 | + | |
| 111 | + baseLLM.model = "foo/medgemma_4b_it_16Q"; | |
| 112 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 113 | + | |
| 114 | + baseLLM.model = "qwen2.5vl"; | |
| 115 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 98 | 116 | }); |
| 99 | 117 | |
| 100 | 118 | test("should return false when modelSupportsImages returns false", () => { |
| 101 | 119 | expect(baseLLM.supportsImages()).toBe(false); |
| 120 | + | |
| 121 | + baseLLM.model = "gemma3n"; | |
| 122 | + expect(baseLLM.supportsImages()).toBe(false); | |
| 102 | 123 | }); |
| 103 | 124 | }); |
| 104 | 125 |
modified core/llm/index.ts +49 −30
| @@ -9,7 +9,6 @@ | ||
| 9 | 9 | import Handlebars from "handlebars"; |
| 10 | 10 | |
| 11 | 11 | import { DevDataSqliteDb } from "../data/devdataSqlite.js"; |
| 12 | -import { Logger } from "../util/Logger.js"; | |
| 13 | 12 | import { DataLogger } from "../data/log.js"; |
| 14 | 13 | import { |
| 15 | 14 | CacheBehavior, |
| @@ -31,10 +30,12 @@ | ||
| 31 | 30 | TemplateType, |
| 32 | 31 | Usage, |
| 33 | 32 | } from "../index.js"; |
| 33 | +import { isLemonadeInstalled } from "../util/lemonadeHelper.js"; | |
| 34 | +import { Logger } from "../util/Logger.js"; | |
| 34 | 35 | import mergeJson from "../util/merge.js"; |
| 35 | 36 | import { renderChatMessage } from "../util/messageContent.js"; |
| 36 | 37 | import { isOllamaInstalled } from "../util/ollamaHelper.js"; |
| 37 | -import { Telemetry } from "../util/posthog.js"; | |
| 38 | +import { TokensBatchingService } from "../util/TokensBatchingService.js"; | |
| 38 | 39 | import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; |
| 39 | 40 | |
| 40 | 41 | import { |
| @@ -191,6 +192,8 @@ | ||
| 191 | 192 | //URI to local block defining this LLM |
| 192 | 193 | sourceFile?: string; |
| 193 | 194 | |
| 195 | + isFromAutoDetect?: boolean; | |
| 196 | + | |
| 194 | 197 | private _llmOptions: LLMOptions; |
| 195 | 198 | |
| 196 | 199 | protected openaiAdapter?: BaseLlmApi; |
| @@ -294,6 +297,7 @@ | ||
| 294 | 297 | |
| 295 | 298 | this.autocompleteOptions = options.autocompleteOptions; |
| 296 | 299 | this.sourceFile = options.sourceFile; |
| 300 | + this.isFromAutoDetect = options.isFromAutoDetect; | |
| 297 | 301 | } |
| 298 | 302 | |
| 299 | 303 | get contextLength() { |
| @@ -343,15 +347,11 @@ | ||
| 343 | 347 | let generatedTokens = this.countTokens(completion); |
| 344 | 348 | let thinkingTokens = thinking ? this.countTokens(thinking) : 0; |
| 345 | 349 | |
| 346 | - void Telemetry.capture( | |
| 347 | - "tokens_generated", | |
| 348 | - { | |
| 349 | - model: model, | |
| 350 | - provider: this.providerName, | |
| 351 | - promptTokens: promptTokens, | |
| 352 | - generatedTokens: generatedTokens, | |
| 353 | - }, | |
| 354 | - true, | |
| 350 | + TokensBatchingService.getInstance().addTokens( | |
| 351 | + model, | |
| 352 | + this.providerName, | |
| 353 | + promptTokens, | |
| 354 | + generatedTokens, | |
| 355 | 355 | ); |
| 356 | 356 | |
| 357 | 357 | void DevDataSqliteDb.logTokensGenerated( |
| @@ -371,8 +371,17 @@ | ||
| 371 | 371 | }, |
| 372 | 372 | }); |
| 373 | 373 | |
| 374 | - if (error !== undefined) { | |
| 375 | - if (error === "cancel" || error.name === "AbortError") { | |
| 374 | + if (typeof error === "undefined") { | |
| 375 | + interaction?.logItem({ | |
| 376 | + kind: "success", | |
| 377 | + promptTokens, | |
| 378 | + generatedTokens, | |
| 379 | + thinkingTokens, | |
| 380 | + usage, | |
| 381 | + }); | |
| 382 | + return "success"; | |
| 383 | + } else { | |
| 384 | + if (error === "cancel" || error?.name?.includes("AbortError")) { | |
| 376 | 385 | interaction?.logItem({ |
| 377 | 386 | kind: "cancel", |
| 378 | 387 | promptTokens, |
| @@ -394,15 +403,6 @@ | ||
| 394 | 403 | }); |
| 395 | 404 | return "error"; |
| 396 | 405 | } |
| 397 | - } else { | |
| 398 | - interaction?.logItem({ | |
| 399 | - kind: "success", | |
| 400 | - promptTokens, | |
| 401 | - generatedTokens, | |
| 402 | - thinkingTokens, | |
| 403 | - usage, | |
| 404 | - }); | |
| 405 | - return "success"; | |
| 406 | 406 | } |
| 407 | 407 | } |
| 408 | 408 | |
| @@ -504,6 +504,24 @@ | ||
| 504 | 504 | : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running."; |
| 505 | 505 | throw new Error(message); |
| 506 | 506 | } |
| 507 | + if ( | |
| 508 | + e.code === "ECONNREFUSED" && | |
| 509 | + e.message.includes("http://localhost:8000") | |
| 510 | + ) { | |
| 511 | + const isInstalled = await isLemonadeInstalled(); | |
| 512 | + let message: string; | |
| 513 | + if (process.platform === "linux") { | |
| 514 | + // On Linux, isLemonadeInstalled checks if it's running (via health endpoint) | |
| 515 | + message = | |
| 516 | + "Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions."; | |
| 517 | + } else { | |
| 518 | + // On Windows, we can check if it's installed | |
| 519 | + message = isInstalled | |
| 520 | + ? "Unable to connect to local Lemonade instance. Lemonade server may not be running." | |
| 521 | + : "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running."; | |
| 522 | + } | |
| 523 | + throw new Error(message); | |
| 524 | + } | |
| 507 | 525 | } |
| 508 | 526 | throw e; |
| 509 | 527 | } |
| @@ -538,18 +556,14 @@ | ||
| 538 | 556 | } |
| 539 | 557 | |
| 540 | 558 | private _formatChatMessage(msg: ChatMessage): string { |
| 541 | - let contentToShow = ""; | |
| 542 | - if (msg.role === "tool") { | |
| 543 | - contentToShow = msg.content; | |
| 544 | - } else if (msg.role === "assistant" && msg.toolCalls?.length) { | |
| 545 | - contentToShow = msg.toolCalls | |
| 559 | + let contentToShow = renderChatMessage(msg); | |
| 560 | + if (msg.role === "assistant" && msg.toolCalls?.length) { | |
| 561 | + contentToShow += msg.toolCalls | |
| 546 | 562 | ?.map( |
| 547 | 563 | (toolCall) => |
| 548 | 564 | `${toolCall.function?.name}(${toolCall.function?.arguments})`, |
| 549 | 565 | ) |
| 550 | 566 | .join("\n"); |
| 551 | - } else if ("content" in msg) { | |
| 552 | - contentToShow = renderChatMessage(msg); | |
| 553 | 567 | } |
| 554 | 568 | |
| 555 | 569 | return `<${msg.role}>\n${contentToShow}\n\n`; |
| @@ -616,6 +630,7 @@ | ||
| 616 | 630 | kind: "chunk", |
| 617 | 631 | chunk: formattedContent, |
| 618 | 632 | }); |
| 633 | + | |
| 619 | 634 | completion += formattedContent; |
| 620 | 635 | yield content; |
| 621 | 636 | } |
| @@ -631,6 +646,7 @@ | ||
| 631 | 646 | kind: "chunk", |
| 632 | 647 | chunk, |
| 633 | 648 | }); |
| 649 | + | |
| 634 | 650 | completion += chunk; |
| 635 | 651 | yield chunk; |
| 636 | 652 | } |
| @@ -1040,6 +1056,10 @@ | ||
| 1040 | 1056 | const msg = fromChatResponse(response); |
| 1041 | 1057 | yield msg; |
| 1042 | 1058 | completion = this._formatChatMessage(msg); |
| 1059 | + interaction?.logItem({ | |
| 1060 | + kind: "message", | |
| 1061 | + message: msg, | |
| 1062 | + }); | |
| 1043 | 1063 | } else { |
| 1044 | 1064 | // Stream true |
| 1045 | 1065 | const stream = this.openaiAdapter.chatCompletionStream( |
| @@ -1143,7 +1163,6 @@ | ||
| 1143 | 1163 | modelProvider: this.underlyingProviderName, |
| 1144 | 1164 | prompt, |
| 1145 | 1165 | completion, |
| 1146 | - completionOptions, | |
| 1147 | 1166 | }; |
| 1148 | 1167 | } |
| 1149 | 1168 |
modified core/llm/llm-pre-fetch.vitest.ts +0 −3
| @@ -19,9 +19,6 @@ | ||
| 19 | 19 | await gen.next(); |
| 20 | 20 | await gen.return({ |
| 21 | 21 | completion: "", |
| 22 | - completionOptions: { | |
| 23 | - model: "", | |
| 24 | - }, | |
| 25 | 22 | modelTitle: "", |
| 26 | 23 | modelProvider: "", |
| 27 | 24 | prompt: "", |
modified core/llm/llm.test.ts +12 −2
| @@ -145,6 +145,7 @@ | ||
| 145 | 145 | description: "Say Hello", |
| 146 | 146 | parameters: { |
| 147 | 147 | type: "object", |
| 148 | + required: ["name"], | |
| 148 | 149 | properties: { |
| 149 | 150 | name: { |
| 150 | 151 | type: "string", |
| @@ -165,7 +166,7 @@ | ||
| 165 | 166 | }, |
| 166 | 167 | )) { |
| 167 | 168 | const typedChunk = chunk as AssistantChatMessage; |
| 168 | - if (!typedChunk.toolCalls) { | |
| 169 | + if (!typedChunk.toolCalls || typedChunk.toolCalls.length === 0) { | |
| 169 | 170 | continue; |
| 170 | 171 | } |
| 171 | 172 | const toolCall = typedChunk.toolCalls[0]; |
| @@ -182,6 +183,15 @@ | ||
| 182 | 183 | } |
| 183 | 184 | } |
| 184 | 185 | |
| 186 | + // For Mistral, if no tool calls were received, skip the test | |
| 187 | + // as it may not support forced tool use | |
| 188 | + if (args === "" && llm.constructor.name === "Mistral") { | |
| 189 | + console.log( | |
| 190 | + "Mistral did not return tool calls, skipping assertion", | |
| 191 | + ); | |
| 192 | + return; | |
| 193 | + } | |
| 194 | + | |
| 185 | 195 | const parsedArgs = JSON.parse(args); |
| 186 | 196 | expect(parsedArgs.name).toBe("Nate"); |
| 187 | 197 | }), |
| @@ -203,7 +213,7 @@ | ||
| 203 | 213 | |
| 204 | 214 | testLLM( |
| 205 | 215 | new Anthropic({ |
| 206 | - model: "claude-3-5-sonnet-latest", | |
| 216 | + model: "claude-sonnet-4-0", | |
| 207 | 217 | apiKey: process.env.ANTHROPIC_API_KEY, |
| 208 | 218 | }), |
| 209 | 219 | { skip: false, testToolCall: true }, |
modified core/llm/llms/Anthropic.ts +31 −6
| @@ -68,6 +68,17 @@ | ||
| 68 | 68 | return finalOptions; |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | + private buildTextPart(text: string, addCaching: boolean) { | |
| 72 | + const part: any = { | |
| 73 | + type: "text", | |
| 74 | + text, | |
| 75 | + }; | |
| 76 | + if (addCaching) { | |
| 77 | + part.cache_control = { type: "ephemeral" }; | |
| 78 | + } | |
| 79 | + return part; | |
| 80 | + } | |
| 81 | + | |
| 71 | 82 | private convertMessage(message: ChatMessage, addCaching: boolean): any { |
| 72 | 83 | if (message.role === "tool") { |
| 73 | 84 | return { |
| @@ -81,14 +92,30 @@ | ||
| 81 | 92 | ], |
| 82 | 93 | }; |
| 83 | 94 | } else if (message.role === "assistant" && message.toolCalls) { |
| 84 | - return { | |
| 85 | - role: "assistant", | |
| 86 | - content: message.toolCalls.map((toolCall) => ({ | |
| 95 | + const parts: any[] = []; | |
| 96 | + if (message.content) { | |
| 97 | + if (typeof message.content === "string") { | |
| 98 | + parts.push(this.buildTextPart(message.content, addCaching)); | |
| 99 | + } else if (message.content.length > 0) { | |
| 100 | + const textContent = message.content.filter((p) => p.type === "text"); | |
| 101 | + const textParts = textContent.map((part, idx) => { | |
| 102 | + const cache = idx === textContent.length - 1 && addCaching; | |
| 103 | + return this.buildTextPart(part.text, cache); | |
| 104 | + }); | |
| 105 | + parts.push(...textParts); | |
| 106 | + } | |
| 107 | + } | |
| 108 | + parts.push( | |
| 109 | + ...message.toolCalls.map((toolCall) => ({ | |
| 87 | 110 | type: "tool_use", |
| 88 | 111 | id: toolCall.id, |
| 89 | 112 | name: toolCall.function?.name, |
| 90 | 113 | input: safeParseToolCallArgs(toolCall), |
| 91 | 114 | })), |
| 115 | + ); | |
| 116 | + return { | |
| 117 | + role: "assistant", | |
| 118 | + content: parts, | |
| 92 | 119 | }; |
| 93 | 120 | } else if (message.role === "thinking" && !message.redactedThinking) { |
| 94 | 121 | return { |
| @@ -154,9 +181,7 @@ | ||
| 154 | 181 | |
| 155 | 182 | public convertMessages(msgs: ChatMessage[]): any[] { |
| 156 | 183 | // should be public for use within VertexAI |
| 157 | - const filteredmessages = msgs.filter( | |
| 158 | - (m) => m.role !== "system" && !!m.content, | |
| 159 | - ); | |
| 184 | + const filteredmessages = msgs.filter((m) => m.role !== "system"); | |
| 160 | 185 | const lastTwoUserMsgIndices = filteredmessages |
| 161 | 186 | .map((msg, index) => (msg.role === "user" ? index : -1)) |
| 162 | 187 | .filter((index) => index !== -1) |
modified core/llm/llms/Bedrock.test.ts +91 −1
| @@ -532,7 +532,7 @@ | ||
| 532 | 532 | ); |
| 533 | 533 | }); |
| 534 | 534 | |
| 535 | - it("should add cache points for prompt caching when needed", () => { | |
| 535 | + it("should add cache points when cacheBehavior.cacheConversation is enabled", () => { | |
| 536 | 536 | // Create a test instance with caching behavior enabled |
| 537 | 537 | const bedrockWithCaching = new TestBedrock({ |
| 538 | 538 | apiKey: "test-key", |
| @@ -576,5 +576,95 @@ | ||
| 576 | 576 | const userMessageText = converted[0].content?.[0].text; |
| 577 | 577 | expect(userMessageText).toMatch(/First message.+/); |
| 578 | 578 | }); |
| 579 | + | |
| 580 | + it("should add cache points when completionOptions.promptCaching is enabled", () => { | |
| 581 | + // Create a test instance with prompt caching enabled via completionOptions | |
| 582 | + const bedrockWithPromptCaching = new TestBedrock({ | |
| 583 | + apiKey: "test-key", | |
| 584 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 585 | + region: "us-east-1", | |
| 586 | + }); | |
| 587 | + | |
| 588 | + // Set completionOptions.promptCaching (without cacheBehavior) | |
| 589 | + bedrockWithPromptCaching.completionOptions = { | |
| 590 | + ...bedrockWithPromptCaching.completionOptions, | |
| 591 | + promptCaching: true, | |
| 592 | + }; | |
| 593 | + | |
| 594 | + const messages: ChatMessage[] = [ | |
| 595 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 596 | + { role: "assistant", content: "First response" }, | |
| 597 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 598 | + ]; | |
| 599 | + | |
| 600 | + const availableTools = new Set<string>(); | |
| 601 | + const converted = bedrockWithPromptCaching["_convertMessages"]( | |
| 602 | + messages, | |
| 603 | + availableTools, | |
| 604 | + ); | |
| 605 | + | |
| 606 | + // The last two user messages should have cache points | |
| 607 | + expect(converted.length).toBe(3); | |
| 608 | + expect(converted[0].role).toBe("user"); | |
| 609 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 610 | + true, | |
| 611 | + ); | |
| 612 | + expect(converted[1].role).toBe("assistant"); | |
| 613 | + expect(converted[2].role).toBe("user"); | |
| 614 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 615 | + true, | |
| 616 | + ); | |
| 617 | + | |
| 618 | + // Verify that text content includes a cache ID suffix | |
| 619 | + const userMessageText = converted[0].content?.[0].text; | |
| 620 | + expect(userMessageText).toMatch(/First message.+/); | |
| 621 | + }); | |
| 622 | + | |
| 623 | + it("should not add cache points when both caching options are disabled", () => { | |
| 624 | + // Create a test instance with no caching enabled | |
| 625 | + const bedrockNoCaching = new TestBedrock({ | |
| 626 | + apiKey: "test-key", | |
| 627 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 628 | + region: "us-east-1", | |
| 629 | + }); | |
| 630 | + | |
| 631 | + // Explicitly set no caching | |
| 632 | + bedrockNoCaching.cacheBehavior = { | |
| 633 | + cacheConversation: false, | |
| 634 | + cacheSystemMessage: false, | |
| 635 | + }; | |
| 636 | + bedrockNoCaching.completionOptions = { | |
| 637 | + ...bedrockNoCaching.completionOptions, | |
| 638 | + promptCaching: false, | |
| 639 | + }; | |
| 640 | + | |
| 641 | + const messages: ChatMessage[] = [ | |
| 642 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 643 | + { role: "assistant", content: "First response" }, | |
| 644 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 645 | + ]; | |
| 646 | + | |
| 647 | + const availableTools = new Set<string>(); | |
| 648 | + const converted = bedrockNoCaching["_convertMessages"]( | |
| 649 | + messages, | |
| 650 | + availableTools, | |
| 651 | + ); | |
| 652 | + | |
| 653 | + // No cache points should be added | |
| 654 | + expect(converted.length).toBe(3); | |
| 655 | + expect(converted[0].role).toBe("user"); | |
| 656 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 657 | + false, | |
| 658 | + ); | |
| 659 | + expect(converted[1].role).toBe("assistant"); | |
| 660 | + expect(converted[2].role).toBe("user"); | |
| 661 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 662 | + false, | |
| 663 | + ); | |
| 664 | + | |
| 665 | + // Verify that text content doesn't include a cache ID suffix | |
| 666 | + const userMessageText = converted[0].content?.[0].text; | |
| 667 | + expect(userMessageText).toBe("First message"); | |
| 668 | + }); | |
| 579 | 669 | }); |
| 580 | 670 | }); |
modified core/llm/llms/Bedrock.ts +71 −78
| @@ -1,13 +1,19 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | BedrockRuntimeClient, |
| 3 | 3 | ContentBlock, |
| 4 | + ContentBlockDelta, | |
| 5 | + ContentBlockStart, | |
| 6 | + ContentBlockStartEvent, | |
| 4 | 7 | ConversationRole, |
| 5 | 8 | ConverseStreamCommand, |
| 6 | 9 | ConverseStreamCommandOutput, |
| 7 | 10 | ImageFormat, |
| 8 | 11 | InvokeModelCommand, |
| 9 | 12 | Message, |
| 13 | + ReasoningContentBlockDelta, | |
| 10 | 14 | ToolConfiguration, |
| 15 | + ToolUseBlock, | |
| 16 | + ToolUseBlockDelta, | |
| 11 | 17 | } from "@aws-sdk/client-bedrock-runtime"; |
| 12 | 18 | import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; |
| 13 | 19 | |
| @@ -25,15 +31,6 @@ | ||
| 25 | 31 | extractEmbeddings: (responseBody: any) => number[][]; |
| 26 | 32 | } |
| 27 | 33 | |
| 28 | -/** | |
| 29 | - * Interface for tool use state tracking | |
| 30 | - */ | |
| 31 | -interface ToolUseState { | |
| 32 | - toolUseId: string; | |
| 33 | - name: string; | |
| 34 | - input: string; | |
| 35 | -} | |
| 36 | - | |
| 37 | 34 | /** |
| 38 | 35 | * Interface for prompt caching metrics |
| 39 | 36 | */ |
| @@ -50,7 +47,6 @@ | ||
| 50 | 47 | profile: "bedrock", |
| 51 | 48 | }; |
| 52 | 49 | |
| 53 | - private _currentToolResponse: Partial<ToolUseState> | null = null; | |
| 54 | 50 | private _promptCachingMetrics: PromptCachingMetrics = { |
| 55 | 51 | cacheReadInputTokens: 0, |
| 56 | 52 | cacheWriteInputTokens: 0, |
| @@ -149,108 +145,99 @@ | ||
| 149 | 145 | console.log(`${JSON.stringify(chunk.metadata.usage)}`); |
| 150 | 146 | } |
| 151 | 147 | |
| 152 | - if (chunk.contentBlockDelta?.delta) { | |
| 153 | - const delta: any = chunk.contentBlockDelta.delta; | |
| 154 | - | |
| 148 | + const contentBlockDelta: ContentBlockDelta | undefined = | |
| 149 | + chunk.contentBlockDelta?.delta; | |
| 150 | + if (contentBlockDelta) { | |
| 155 | 151 | // Handle text content |
| 156 | - if (chunk.contentBlockDelta.delta.text) { | |
| 152 | + if (contentBlockDelta.text) { | |
| 157 | 153 | yield { |
| 158 | 154 | role: "assistant", |
| 159 | - content: chunk.contentBlockDelta.delta.text, | |
| 160 | - }; | |
| 161 | - continue; | |
| 162 | - } | |
| 163 | - | |
| 164 | - // Handle text content | |
| 165 | - if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { | |
| 166 | - yield { | |
| 167 | - role: "thinking", | |
| 168 | - content: (chunk.contentBlockDelta.delta as any).reasoningContent | |
| 169 | - .text, | |
| 155 | + content: contentBlockDelta.text, | |
| 170 | 156 | }; |
| 171 | 157 | continue; |
| 172 | 158 | } |
| 173 | - | |
| 174 | - // Handle signature for thinking | |
| 175 | - if (delta.reasoningContent?.signature) { | |
| 159 | + if (contentBlockDelta.reasoningContent?.text) { | |
| 176 | 160 | yield { |
| 177 | 161 | role: "thinking", |
| 178 | - content: "", | |
| 179 | - signature: delta.reasoningContent.signature, | |
| 162 | + content: contentBlockDelta.reasoningContent.text, | |
| 180 | 163 | }; |
| 181 | 164 | continue; |
| 182 | 165 | } |
| 183 | - | |
| 184 | - // Handle redacted thinking | |
| 185 | - if (delta.redactedReasoning?.data) { | |
| 166 | + if (contentBlockDelta.reasoningContent?.signature) { | |
| 186 | 167 | yield { |
| 187 | 168 | role: "thinking", |
| 188 | 169 | content: "", |
| 189 | - redactedThinking: delta.redactedReasoning.data, | |
| 170 | + signature: contentBlockDelta.reasoningContent.signature, | |
| 190 | 171 | }; |
| 191 | 172 | continue; |
| 192 | 173 | } |
| 193 | - | |
| 194 | - if ( | |
| 195 | - chunk.contentBlockDelta.delta.toolUse?.input && | |
| 196 | - this._currentToolResponse | |
| 197 | - ) { | |
| 198 | - // Append the new input to the existing string | |
| 199 | - if (this._currentToolResponse.input === undefined) { | |
| 200 | - this._currentToolResponse.input = ""; | |
| 201 | - } | |
| 202 | - this._currentToolResponse.input += | |
| 203 | - chunk.contentBlockDelta.delta.toolUse.input; | |
| 204 | - continue; | |
| 205 | - } | |
| 206 | 174 | } |
| 207 | 175 | |
| 208 | - if (chunk.contentBlockStart?.start) { | |
| 209 | - const start: any = chunk.contentBlockStart.start; | |
| 210 | - if (start.redactedReasoning) { | |
| 176 | + const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk | |
| 177 | + .contentBlockDelta?.delta as ReasoningContentBlockDelta; | |
| 178 | + if (reasoningDelta) { | |
| 179 | + if (reasoningDelta.redactedContent) { | |
| 211 | 180 | yield { |
| 212 | 181 | role: "thinking", |
| 213 | 182 | content: "", |
| 214 | - redactedThinking: start.redactedReasoning.data, | |
| 183 | + redactedThinking: reasoningDelta.text, | |
| 215 | 184 | }; |
| 216 | 185 | continue; |
| 217 | 186 | } |
| 187 | + } | |
| 218 | 188 | |
| 219 | - const toolUse = chunk.contentBlockStart.start.toolUse; | |
| 220 | - if (toolUse?.toolUseId && toolUse?.name) { | |
| 221 | - this._currentToolResponse = { | |
| 222 | - toolUseId: toolUse.toolUseId, | |
| 223 | - name: toolUse.name, | |
| 224 | - input: "", | |
| 225 | - }; | |
| 226 | - } | |
| 189 | + const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk | |
| 190 | + .contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta; | |
| 191 | + const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta | |
| 192 | + ?.delta?.toolUse as ToolUseBlock; | |
| 193 | + if (toolUseBlockDelta && toolUseBlock) { | |
| 194 | + yield { | |
| 195 | + role: "assistant", | |
| 196 | + content: "", | |
| 197 | + toolCalls: [ | |
| 198 | + { | |
| 199 | + id: toolUseBlock.toolUseId, | |
| 200 | + type: "function", | |
| 201 | + function: { | |
| 202 | + name: toolUseBlock.name, | |
| 203 | + arguments: toolUseBlockDelta.input, | |
| 204 | + }, | |
| 205 | + }, | |
| 206 | + ], | |
| 207 | + }; | |
| 227 | 208 | continue; |
| 228 | 209 | } |
| 229 | 210 | |
| 230 | - if (chunk.contentBlockStop) { | |
| 231 | - if (this._currentToolResponse) { | |
| 232 | - yield { | |
| 233 | - role: "assistant", | |
| 234 | - content: "", | |
| 235 | - toolCalls: [ | |
| 236 | - { | |
| 237 | - id: this._currentToolResponse.toolUseId, | |
| 238 | - type: "function", | |
| 239 | - function: { | |
| 240 | - name: this._currentToolResponse.name, | |
| 241 | - arguments: this._currentToolResponse.input, | |
| 211 | + const contentBlockStart: ContentBlockStartEvent | undefined = | |
| 212 | + chunk.contentBlockStart as ContentBlockStartEvent; | |
| 213 | + if (contentBlockStart) { | |
| 214 | + const start: ContentBlockStart | undefined = chunk.contentBlockStart | |
| 215 | + ?.start as ContentBlockStart; | |
| 216 | + if (start) { | |
| 217 | + const toolUseBlock: ToolUseBlock | undefined = | |
| 218 | + start.toolUse as ToolUseBlock; | |
| 219 | + if (toolUseBlock?.toolUseId && toolUseBlock?.name) { | |
| 220 | + yield { | |
| 221 | + role: "assistant", | |
| 222 | + content: "", | |
| 223 | + toolCalls: [ | |
| 224 | + { | |
| 225 | + id: toolUseBlock.toolUseId, | |
| 226 | + type: "function", | |
| 227 | + function: { | |
| 228 | + name: toolUseBlock.name, | |
| 229 | + arguments: "", | |
| 230 | + }, | |
| 242 | 231 | }, |
| 243 | - }, | |
| 244 | - ], | |
| 245 | - }; | |
| 246 | - this._currentToolResponse = null; | |
| 232 | + ], | |
| 233 | + }; | |
| 234 | + continue; | |
| 235 | + } | |
| 247 | 236 | } |
| 248 | - continue; | |
| 249 | 237 | } |
| 250 | 238 | } |
| 251 | 239 | } catch (error: unknown) { |
| 252 | 240 | // Clean up state and let the original error bubble up to the retry decorator |
| 253 | - this._currentToolResponse = null; | |
| 254 | 241 | throw error; |
| 255 | 242 | } |
| 256 | 243 | } |
| @@ -348,6 +335,9 @@ | ||
| 348 | 335 | budget_tokens: options.reasoningBudgetTokens, |
| 349 | 336 | } |
| 350 | 337 | : undefined, |
| 338 | + anthropic_beta: options.model.includes("claude") | |
| 339 | + ? ["fine-grained-tool-streaming-2025-05-14"] | |
| 340 | + : undefined, | |
| 351 | 341 | }, |
| 352 | 342 | }; |
| 353 | 343 | } |
| @@ -513,7 +503,10 @@ | ||
| 513 | 503 | // The second-to-last because it retrieves potentially already cached contents, |
| 514 | 504 | // The last one because we want it cached for later retrieval. |
| 515 | 505 | // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html |
| 516 | - if (this.cacheBehavior?.cacheConversation) { | |
| 506 | + if ( | |
| 507 | + this.cacheBehavior?.cacheConversation || | |
| 508 | + this.completionOptions.promptCaching | |
| 509 | + ) { | |
| 517 | 510 | this._addCachingToLastTwoUserMessages(converted); |
| 518 | 511 | } |
| 519 | 512 |
modified core/llm/llms/Inception.ts +123 −1
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | -import { CompletionOptions, LLMOptions } from "../../index.js"; | |
| 2 | +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; | |
| 3 | 3 | |
| 4 | +import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; | |
| 5 | +import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js"; | |
| 6 | +import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; | |
| 4 | 7 | import OpenAI from "./OpenAI.js"; |
| 5 | 8 | |
| 6 | 9 | /** |
| @@ -32,6 +35,26 @@ | ||
| 32 | 35 | return true; |
| 33 | 36 | } |
| 34 | 37 | |
| 38 | + // It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't. | |
| 39 | + // protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ | |
| 40 | + // "chat", | |
| 41 | + // "embed", | |
| 42 | + // "list", | |
| 43 | + // "rerank", | |
| 44 | + // "streamChat", | |
| 45 | + // "streamFim", | |
| 46 | + // ]; | |
| 47 | + | |
| 48 | + protected modifyChatBody( | |
| 49 | + body: ChatCompletionCreateParams, | |
| 50 | + ): ChatCompletionCreateParams { | |
| 51 | + const hasNextEditCapability = this.capabilities?.nextEdit ?? false; | |
| 52 | + | |
| 53 | + // Add the nextEdit parameter for Inception-specific routing. | |
| 54 | + (body as any).nextEdit = hasNextEditCapability; | |
| 55 | + return body; | |
| 56 | + } | |
| 57 | + | |
| 35 | 58 | async *_streamFim( |
| 36 | 59 | prefix: string, |
| 37 | 60 | suffix: string, |
| @@ -67,6 +90,105 @@ | ||
| 67 | 90 | yield chunk.choices[0].text; |
| 68 | 91 | } |
| 69 | 92 | } |
| 93 | + | |
| 94 | + protected async *_streamChat( | |
| 95 | + messages: ChatMessage[], | |
| 96 | + signal: AbortSignal, | |
| 97 | + options: CompletionOptions, | |
| 98 | + ): AsyncGenerator<ChatMessage> { | |
| 99 | + if (this.isNextEdit(messages)) { | |
| 100 | + messages = this.removeToken(messages, UNIQUE_TOKEN); | |
| 101 | + yield* this.streamSpecialEndpoint( | |
| 102 | + "edit/completions", | |
| 103 | + messages, | |
| 104 | + signal, | |
| 105 | + options, | |
| 106 | + ); | |
| 107 | + } else if (this.isApply(messages)) { | |
| 108 | + messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN); | |
| 109 | + yield* this.streamSpecialEndpoint( | |
| 110 | + "apply/completions", | |
| 111 | + messages, | |
| 112 | + signal, | |
| 113 | + options, | |
| 114 | + ); | |
| 115 | + } else { | |
| 116 | + // Use regular chat/completions endpoint - call parent OpenAI implementation. | |
| 117 | + yield* super._streamChat(messages, signal, options); | |
| 118 | + } | |
| 119 | + } | |
| 120 | + | |
| 121 | + private isNextEdit(messages: ChatMessage[]): boolean { | |
| 122 | + // Check if any message contains the unique next edit token. | |
| 123 | + return messages.some( | |
| 124 | + (message) => | |
| 125 | + typeof message.content === "string" && | |
| 126 | + message.content.endsWith(UNIQUE_TOKEN), | |
| 127 | + ); | |
| 128 | + } | |
| 129 | + | |
| 130 | + private isApply(messages: ChatMessage[]): boolean { | |
| 131 | + return messages.some( | |
| 132 | + (message) => | |
| 133 | + typeof message.content === "string" && | |
| 134 | + message.content.endsWith(APPLY_UNIQUE_TOKEN), | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + | |
| 138 | + private removeToken(messages: ChatMessage[], token: string): ChatMessage[] { | |
| 139 | + const lastMessage = messages[messages.length - 1]; | |
| 140 | + | |
| 141 | + if ( | |
| 142 | + typeof lastMessage?.content === "string" && | |
| 143 | + lastMessage.content.endsWith(token) | |
| 144 | + ) { | |
| 145 | + const cleanedMessages = [...messages]; | |
| 146 | + cleanedMessages[cleanedMessages.length - 1] = { | |
| 147 | + ...lastMessage, | |
| 148 | + content: lastMessage.content.slice(0, -token.length), | |
| 149 | + }; | |
| 150 | + return cleanedMessages; | |
| 151 | + } | |
| 152 | + | |
| 153 | + return messages; | |
| 154 | + } | |
| 155 | + | |
| 156 | + private async *streamSpecialEndpoint( | |
| 157 | + path: string, | |
| 158 | + messages: ChatMessage[], | |
| 159 | + signal: AbortSignal, | |
| 160 | + options: CompletionOptions, | |
| 161 | + ): AsyncGenerator<ChatMessage> { | |
| 162 | + const endpoint = new URL(path, this.apiBase); | |
| 163 | + | |
| 164 | + const resp = await this.fetch(endpoint, { | |
| 165 | + method: "POST", | |
| 166 | + body: JSON.stringify({ | |
| 167 | + model: options.model, | |
| 168 | + messages, | |
| 169 | + max_tokens: options.maxTokens, | |
| 170 | + temperature: options.temperature, | |
| 171 | + top_p: options.topP, | |
| 172 | + frequency_penalty: options.frequencyPenalty, | |
| 173 | + presence_penalty: options.presencePenalty, | |
| 174 | + stop: options.stop, | |
| 175 | + stream: true, | |
| 176 | + }), | |
| 177 | + headers: { | |
| 178 | + "Content-Type": "application/json", | |
| 179 | + Accept: "application/json", | |
| 180 | + Authorization: `Bearer ${this.apiKey}`, | |
| 181 | + }, | |
| 182 | + signal, | |
| 183 | + }); | |
| 184 | + | |
| 185 | + for await (const chunk of streamSse(resp)) { | |
| 186 | + const content = chunk.choices?.[0]?.delta?.content; | |
| 187 | + if (content) { | |
| 188 | + yield { role: "assistant", content }; | |
| 189 | + } | |
| 190 | + } | |
| 191 | + } | |
| 70 | 192 | } |
| 71 | 193 | |
| 72 | 194 | export default Inception; |
added core/llm/llms/Lemonade.ts +12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +import { LLMOptions } from "../../index.js"; | |
| 2 | + | |
| 3 | +import OpenAI from "./OpenAI.js"; | |
| 4 | + | |
| 5 | +class Lemonade extends OpenAI { | |
| 6 | + static providerName = "lemonade"; | |
| 7 | + static defaultOptions: Partial<LLMOptions> = { | |
| 8 | + apiBase: "http://localhost:8000/api/v1/", | |
| 9 | + }; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export default Lemonade; |
modified core/llm/llms/Ollama.ts +42 −20
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | CompletionOptions, |
| 10 | 10 | LLMOptions, |
| 11 | 11 | ModelInstaller, |
| 12 | + ThinkingChatMessage, | |
| 12 | 13 | } from "../../index.js"; |
| 13 | 14 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 14 | 15 | import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; |
| @@ -18,6 +19,7 @@ | ||
| 18 | 19 | role: ChatMessageRole; |
| 19 | 20 | content: string; |
| 20 | 21 | images?: string[] | null; |
| 22 | + thinking?: string; | |
| 21 | 23 | tool_calls?: { |
| 22 | 24 | function: { |
| 23 | 25 | name: string; |
| @@ -85,6 +87,7 @@ | ||
| 85 | 87 | tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory |
| 86 | 88 | // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false |
| 87 | 89 | // And correspondingly, tool calls in OllamaChatMessage |
| 90 | + think?: boolean; // if true the model will be prompted to think about the response before generating it | |
| 88 | 91 | } |
| 89 | 92 | |
| 90 | 93 | type OllamaBaseResponse = { |
| @@ -144,7 +147,6 @@ | ||
| 144 | 147 | private static modelsBeingInstalledMutex = new Mutex(); |
| 145 | 148 | |
| 146 | 149 | private fimSupported: boolean = false; |
| 147 | - | |
| 148 | 150 | constructor(options: LLMOptions) { |
| 149 | 151 | super(options); |
| 150 | 152 | |
| @@ -267,6 +269,11 @@ | ||
| 267 | 269 | return this.modelMap[this.model] ?? this.model; |
| 268 | 270 | } |
| 269 | 271 | |
| 272 | + get contextLength() { | |
| 273 | + const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185 | |
| 274 | + return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH; | |
| 275 | + } | |
| 276 | + | |
| 270 | 277 | private _getModelFileParams( |
| 271 | 278 | options: CompletionOptions, |
| 272 | 279 | ): OllamaModelFileParams { |
| @@ -391,6 +398,7 @@ | ||
| 391 | 398 | model: this._getModel(), |
| 392 | 399 | messages: ollamaMessages, |
| 393 | 400 | options: this._getModelFileParams(options), |
| 401 | + think: options.reasoning, | |
| 394 | 402 | keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes |
| 395 | 403 | stream: options.stream, |
| 396 | 404 | // format: options.format, // Not currently in base completion options |
| @@ -420,24 +428,35 @@ | ||
| 420 | 428 | signal, |
| 421 | 429 | }); |
| 422 | 430 | |
| 423 | - function convertChatMessage(res: OllamaChatResponse): ChatMessage { | |
| 431 | + function convertChatMessage(res: OllamaChatResponse): ChatMessage[] { | |
| 424 | 432 | if ("error" in res) { |
| 425 | 433 | throw new Error(res.error); |
| 426 | 434 | } |
| 427 | - if (res.message.role === "tool") { | |
| 435 | + | |
| 436 | + const { role, content, thinking, tool_calls: toolCalls } = res.message; | |
| 437 | + | |
| 438 | + if (role === "tool") { | |
| 428 | 439 | throw new Error( |
| 429 | - "Unexpected message received from ollama with role = tool", | |
| 440 | + "Unexpected message received from Ollama with role = tool", | |
| 430 | 441 | ); |
| 431 | 442 | } |
| 432 | - if (res.message.role === "assistant") { | |
| 433 | - const chatMessage: ChatMessage = { | |
| 434 | - role: "assistant", | |
| 435 | - content: res.message.content, | |
| 436 | - }; | |
| 437 | - if (res.message.tool_calls) { | |
| 443 | + | |
| 444 | + if (role === "assistant") { | |
| 445 | + const thinkingMessage: ThinkingChatMessage | null = thinking | |
| 446 | + ? { role: "thinking", content: thinking } | |
| 447 | + : null; | |
| 448 | + | |
| 449 | + if (thinkingMessage && !content) { | |
| 450 | + // When Streaming you can't have both thinking and content | |
| 451 | + return [thinkingMessage]; | |
| 452 | + } | |
| 453 | + // Either not thinking, or not streaming | |
| 454 | + const chatMessage: ChatMessage = { role: "assistant", content }; | |
| 455 | + | |
| 456 | + if (toolCalls?.length) { | |
| 438 | 457 | // Continue handles the response as a tool call delta but |
| 439 | 458 | // But ollama returns the full object in one response with no streaming |
| 440 | - chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({ | |
| 459 | + chatMessage.toolCalls = toolCalls.map((tc) => ({ | |
| 441 | 460 | type: "function", |
| 442 | 461 | id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix |
| 443 | 462 | function: { |
| @@ -446,13 +465,13 @@ | ||
| 446 | 465 | }, |
| 447 | 466 | })); |
| 448 | 467 | } |
| 449 | - return chatMessage; | |
| 450 | - } else { | |
| 451 | - return { | |
| 452 | - role: res.message.role, | |
| 453 | - content: res.message.content, | |
| 454 | - }; | |
| 468 | + | |
| 469 | + // Return both thinking and chat messages if applicable | |
| 470 | + return thinkingMessage ? [thinkingMessage, chatMessage] : [chatMessage]; | |
| 455 | 471 | } |
| 472 | + | |
| 473 | + // Fallback for all other roles | |
| 474 | + return [{ role, content }]; | |
| 456 | 475 | } |
| 457 | 476 | |
| 458 | 477 | if (chatOptions.stream === false) { |
| @@ -460,7 +479,9 @@ | ||
| 460 | 479 | return; // Aborted by user |
| 461 | 480 | } |
| 462 | 481 | const json = (await response.json()) as OllamaChatResponse; |
| 463 | - yield convertChatMessage(json); | |
| 482 | + for (const msg of convertChatMessage(json)) { | |
| 483 | + yield msg; | |
| 484 | + } | |
| 464 | 485 | } else { |
| 465 | 486 | let buffer = ""; |
| 466 | 487 | for await (const value of streamResponse(response)) { |
| @@ -475,8 +496,9 @@ | ||
| 475 | 496 | if (chunk.trim() !== "") { |
| 476 | 497 | try { |
| 477 | 498 | const j = JSON.parse(chunk) as OllamaChatResponse; |
| 478 | - const chatMessage = convertChatMessage(j); | |
| 479 | - yield chatMessage; | |
| 499 | + for (const msg of convertChatMessage(j)) { | |
| 500 | + yield msg; | |
| 501 | + } | |
| 480 | 502 | } catch (e) { |
| 481 | 503 | throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); |
| 482 | 504 | } |
modified core/llm/llms/OpenAI.ts +1 −1
| @@ -174,7 +174,7 @@ | ||
| 174 | 174 | protected _getHeaders() { |
| 175 | 175 | return { |
| 176 | 176 | "Content-Type": "application/json", |
| 177 | - Authorization: `Bearer ${this.apiKey}`, | |
| 177 | + ...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }), | |
| 178 | 178 | "api-key": this.apiKey ?? "", // For Azure |
| 179 | 179 | }; |
| 180 | 180 | } |
modified core/llm/llms/Scaleway.ts +8 −1
| @@ -7,16 +7,23 @@ | ||
| 7 | 7 | static providerName = "scaleway"; |
| 8 | 8 | static defaultOptions: Partial<LLMOptions> = { |
| 9 | 9 | apiBase: "https://api.scaleway.ai/v1/", |
| 10 | - model: "qwen2.5-coder-32b-instruct", | |
| 10 | + model: "qwen3-coder-30b-a3b-instruct", | |
| 11 | 11 | useLegacyCompletionsEndpoint: false, |
| 12 | 12 | }; |
| 13 | 13 | |
| 14 | 14 | private static MODEL_IDS: { [name: string]: string } = { |
| 15 | 15 | "llama3.1-8b": "llama-3.1-8b-instruct", |
| 16 | 16 | "llama3.3-70b": "llama-3.3-70b-instruct", |
| 17 | + "pixtral-12b": "pixtral-12b-2409", | |
| 17 | 18 | "mistral-small3.1": "mistral-small-3.1-24b-instruct-2503", |
| 19 | + "mistral-small3.2": "mistral-small-3.2-24b-instruct-2506", | |
| 20 | + "devstral-small": "devstral-small-2505", | |
| 18 | 21 | "deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b", |
| 19 | 22 | "qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct", |
| 23 | + "qwen3-coder-30b-a3b": "qwen3-coder-30b-a3b-instruct", | |
| 24 | + "qwen3-235b-a22b": "qwen3-235b-a22b-instruct-2507", | |
| 25 | + "gemma-3-27b": "gemma-3-27b-it", | |
| 26 | + "gpt-oss-120b": "gpt-oss-120b", | |
| 20 | 27 | }; |
| 21 | 28 | |
| 22 | 29 | protected _convertModelName(model: string) { |
added core/llm/llms/TARS.ts +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +import { LLMOptions } from "../../index.js"; | |
| 2 | +import { osModelsEditPrompt } from "../templates/edit.js"; | |
| 3 | + | |
| 4 | +import OpenAI from "./OpenAI.js"; | |
| 5 | + | |
| 6 | +class TARS extends OpenAI { | |
| 7 | + static providerName = "tars"; | |
| 8 | + static defaultOptions: Partial<LLMOptions> = { | |
| 9 | + apiBase: "https://api.router.tetrate.ai/v1", | |
| 10 | + model: "gpt-5-mini", | |
| 11 | + promptTemplates: { | |
| 12 | + edit: osModelsEditPrompt, | |
| 13 | + }, | |
| 14 | + useLegacyCompletionsEndpoint: false, | |
| 15 | + }; | |
| 16 | +} | |
| 17 | + | |
| 18 | +export default TARS; |
modified core/llm/llms/Vllm.ts +2 −2
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | constructor(options: LLMOptions) { |
| 26 | 26 | super(options); |
| 27 | 27 | |
| 28 | - if (options.model === "AUTODETECT") { | |
| 28 | + if (options.isFromAutoDetect) { | |
| 29 | 29 | this._setupCompletionOptions(); |
| 30 | 30 | } |
| 31 | 31 | } |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | // vLLM uses 'results' array instead of 'data' |
| 46 | 46 | if (results.results && Array.isArray(results.results)) { |
| 47 | 47 | const sortedResults = results.results.sort((a, b) => a.index - b.index); |
| 48 | - return sortedResults.map((result) => result.index); | |
| 48 | + return sortedResults.map((result) => result.relevance_score); | |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 51 | throw new Error( |
modified core/llm/llms/index.ts +4 −0
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | import LlamaCpp from "./LlamaCpp"; |
| 34 | 34 | import Llamafile from "./Llamafile"; |
| 35 | 35 | import LlamaStack from "./LlamaStack"; |
| 36 | +import Lemonade from "./Lemonade"; | |
| 36 | 37 | import LMStudio from "./LMStudio"; |
| 37 | 38 | import Mistral from "./Mistral"; |
| 38 | 39 | import MockLLM from "./Mock"; |
| @@ -53,6 +54,7 @@ | ||
| 53 | 54 | import Scaleway from "./Scaleway"; |
| 54 | 55 | import SiliconFlow from "./SiliconFlow"; |
| 55 | 56 | import ContinueProxy from "./stubs/ContinueProxy"; |
| 57 | +import TARS from "./TARS"; | |
| 56 | 58 | import TestLLM from "./Test"; |
| 57 | 59 | import TextGenWebUI from "./TextGenWebUI"; |
| 58 | 60 | import Together from "./Together"; |
| @@ -81,6 +83,7 @@ | ||
| 81 | 83 | LlamaCpp, |
| 82 | 84 | OpenAI, |
| 83 | 85 | OVHcloud, |
| 86 | + Lemonade, | |
| 84 | 87 | LMStudio, |
| 85 | 88 | Mistral, |
| 86 | 89 | Bedrock, |
| @@ -116,6 +119,7 @@ | ||
| 116 | 119 | Inception, |
| 117 | 120 | Voyage, |
| 118 | 121 | LlamaStack, |
| 122 | + TARS, | |
| 119 | 123 | ]; |
| 120 | 124 | |
| 121 | 125 | export async function llmFromDescription( |
modified core/llm/openaiTypeConverters.ts +36 −19
| @@ -101,15 +101,17 @@ | ||
| 101 | 101 | }; |
| 102 | 102 | |
| 103 | 103 | if (options.tools?.length) { |
| 104 | - params.tools = options.tools.map((tool) => ({ | |
| 105 | - type: tool.type, | |
| 106 | - function: { | |
| 107 | - name: tool.function.name, | |
| 108 | - description: tool.function.description, | |
| 109 | - parameters: tool.function.parameters, | |
| 110 | - strict: tool.function.strict, | |
| 111 | - }, | |
| 112 | - })); | |
| 104 | + params.tools = options.tools | |
| 105 | + .filter((tool) => !tool.type || tool.type === "function") | |
| 106 | + .map((tool) => ({ | |
| 107 | + type: tool.type, | |
| 108 | + function: { | |
| 109 | + name: tool.function.name, | |
| 110 | + description: tool.function.description, | |
| 111 | + parameters: tool.function.parameters, | |
| 112 | + strict: tool.function.strict, | |
| 113 | + }, | |
| 114 | + })); | |
| 113 | 115 | } |
| 114 | 116 | |
| 115 | 117 | return params; |
| @@ -158,7 +160,16 @@ | ||
| 158 | 160 | return { |
| 159 | 161 | role: "assistant", |
| 160 | 162 | content: "", |
| 161 | - toolCalls: message.tool_calls, | |
| 163 | + toolCalls: message.tool_calls | |
| 164 | + ?.filter((tc) => !tc.type || tc.type === "function") | |
| 165 | + .map((tc) => ({ | |
| 166 | + id: tc.id, | |
| 167 | + type: "function" as const, | |
| 168 | + function: { | |
| 169 | + name: (tc as any).function?.name, | |
| 170 | + arguments: (tc as any).function?.arguments, | |
| 171 | + }, | |
| 172 | + })), | |
| 162 | 173 | }; |
| 163 | 174 | } |
| 164 | 175 | |
| @@ -179,18 +190,24 @@ | ||
| 179 | 190 | content: delta.content, |
| 180 | 191 | }; |
| 181 | 192 | } else if (delta?.tool_calls) { |
| 182 | - return { | |
| 183 | - role: "assistant", | |
| 184 | - content: "", | |
| 185 | - toolCalls: delta?.tool_calls.map((tool_call) => ({ | |
| 193 | + const toolCalls = delta?.tool_calls | |
| 194 | + .filter((tool_call) => !tool_call.type || tool_call.type === "function") | |
| 195 | + .map((tool_call) => ({ | |
| 186 | 196 | id: tool_call.id, |
| 187 | - type: tool_call.type, | |
| 197 | + type: "function" as const, | |
| 188 | 198 | function: { |
| 189 | - name: tool_call.function?.name, | |
| 190 | - arguments: tool_call.function?.arguments, | |
| 199 | + name: (tool_call as any).function?.name, | |
| 200 | + arguments: (tool_call as any).function?.arguments, | |
| 191 | 201 | }, |
| 192 | - })), | |
| 193 | - }; | |
| 202 | + })); | |
| 203 | + | |
| 204 | + if (toolCalls.length > 0) { | |
| 205 | + return { | |
| 206 | + role: "assistant", | |
| 207 | + content: "", | |
| 208 | + toolCalls, | |
| 209 | + }; | |
| 210 | + } | |
| 194 | 211 | } |
| 195 | 212 | |
| 196 | 213 | return undefined; |
modified core/llm/rules/nestedDirectoryRules.vitest.ts +1 −1
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | // A global rule for comparison |
| 21 | 21 | const globalRule: RuleWithSource = { |
| 22 | 22 | name: "Global Rule", |
| 23 | - rule: "SOLID Design Principles - Coding Assistant Guidelines", | |
| 23 | + rule: "SOLID Design Principles - Coding Agent Guidelines", | |
| 24 | 24 | source: "rules-block", |
| 25 | 25 | ruleFile: ".continue/rules.md", |
| 26 | 26 | }; |
modified core/llm/streamChat.ts +1 −1
| @@ -95,7 +95,7 @@ | ||
| 95 | 95 | ...init, |
| 96 | 96 | signal: abortController.signal, |
| 97 | 97 | }, |
| 98 | - config.requestOptions, | |
| 98 | + model.requestOptions, | |
| 99 | 99 | ), |
| 100 | 100 | completionOptions, |
| 101 | 101 | abortController, |
modified core/llm/templates/edit.ts +1 −1
| @@ -164,7 +164,7 @@ | ||
| 164 | 164 | \`\`\`{{{language}}} |
| 165 | 165 | `; |
| 166 | 166 | |
| 167 | -const xWinCoderEditPrompt = `<system>: You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request. | |
| 167 | +const xWinCoderEditPrompt = `<system>: You are an AI coding agent that helps people with programming. Write a response that appropriately completes the user's request. | |
| 168 | 168 | <user>: Please rewrite the following code with these instructions: "{{{userInput}}}" |
| 169 | 169 | \`\`\`{{{language}}} |
| 170 | 170 | {{{codeToEdit}}} |
modified core/llm/templates/edit/gpt.ts +7 −0
| @@ -71,3 +71,10 @@ | ||
| 71 | 71 | |
| 72 | 72 | return paragraphs.join("\n\n"); |
| 73 | 73 | }; |
| 74 | + | |
| 75 | +export const defaultApplyPrompt: PromptTemplateFunction = ( | |
| 76 | + history, | |
| 77 | + otherData, | |
| 78 | +) => { | |
| 79 | + 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.`; | |
| 80 | +}; |
modified core/llm/toolSupport.test.ts +38 −0
| @@ -280,6 +280,43 @@ | ||
| 280 | 280 | }); |
| 281 | 281 | }); |
| 282 | 282 | |
| 283 | + describe("novita", () => { | |
| 284 | + const supportsFn = PROVIDER_TOOL_SUPPORT["novita"]; | |
| 285 | + | |
| 286 | + it("should return true for exact match models", () => { | |
| 287 | + expect(supportsFn("deepseek/deepseek-r1-0528")).toBe(true); | |
| 288 | + expect(supportsFn("deepseek/deepseek-r1-turbo")).toBe(true); | |
| 289 | + expect(supportsFn("deepseek/deepseek-v3-0324")).toBe(true); | |
| 290 | + expect(supportsFn("deepseek/deepseek-v3-turbo")).toBe(true); | |
| 291 | + expect(supportsFn("meta-llama/llama-3.3-70b-instruct")).toBe(true); | |
| 292 | + expect(supportsFn("qwen/qwen-2.5-72b-instruct")).toBe(true); | |
| 293 | + expect(supportsFn("zai-org/glm-4.5")).toBe(true); | |
| 294 | + expect(supportsFn("moonshotai/kimi-k2-instruct")).toBe(true); | |
| 295 | + }); | |
| 296 | + | |
| 297 | + it("should return true for prefix match models", () => { | |
| 298 | + expect(supportsFn("qwen/qwen3-235b-a22b-instruct-2507")).toBe(true); | |
| 299 | + expect(supportsFn("openai/gpt-oss-20b")).toBe(true); | |
| 300 | + expect(supportsFn("openai/gpt-oss-120b")).toBe(true); | |
| 301 | + }); | |
| 302 | + | |
| 303 | + it("should return false for unsupported models", () => { | |
| 304 | + expect(supportsFn("deepseek/deepseek-chat")).toBe(false); | |
| 305 | + expect(supportsFn("meta-llama/llama-2-7b")).toBe(false); | |
| 306 | + expect(supportsFn("qwen/qwen-2.0-7b")).toBe(false); | |
| 307 | + expect(supportsFn("openai/gpt-4")).toBe(false); | |
| 308 | + }); | |
| 309 | + }); | |
| 310 | + | |
| 311 | + describe("openrouter", () => { | |
| 312 | + const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"]; | |
| 313 | + | |
| 314 | + it("should return false for moonshotai/kimi-k2:free model", () => { | |
| 315 | + // This fixes issue #6619 | |
| 316 | + expect(supportsFn("moonshotai/kimi-k2:free")).toBe(false); | |
| 317 | + }); | |
| 318 | + }); | |
| 319 | + | |
| 283 | 320 | describe("edge cases", () => { |
| 284 | 321 | it("should handle empty model names", () => { |
| 285 | 322 | expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false); |
| @@ -288,6 +325,7 @@ | ||
| 288 | 325 | expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false); |
| 289 | 326 | expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false); |
| 290 | 327 | expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false); |
| 328 | + expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false); | |
| 291 | 329 | }); |
| 292 | 330 | |
| 293 | 331 | it("should handle non-existent provider", () => { |
modified core/llm/toolSupport.ts +41 −2
| @@ -124,6 +124,7 @@ | ||
| 124 | 124 | "nova-pro", |
| 125 | 125 | "nova-micro", |
| 126 | 126 | "nova-premier", |
| 127 | + "gpt-oss", | |
| 127 | 128 | ].some((part) => model.toLowerCase().includes(part)) |
| 128 | 129 | ) { |
| 129 | 130 | return true; |
| @@ -239,6 +240,13 @@ | ||
| 239 | 240 | }, |
| 240 | 241 | openrouter: (model) => { |
| 241 | 242 | // https://openrouter.ai/models?fmt=cards&supported_parameters=tools |
| 243 | + | |
| 244 | + // Specific free models that don't support tools | |
| 245 | + // Fixes issue #6619 - moonshotai/kimi-k2:free causing 400 errors | |
| 246 | + if (model.toLowerCase() === "moonshotai/kimi-k2:free") { | |
| 247 | + return false; | |
| 248 | + } | |
| 249 | + | |
| 242 | 250 | if ( |
| 243 | 251 | ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( |
| 244 | 252 | (part) => model.toLowerCase().includes(part), |
| @@ -295,6 +303,7 @@ | ||
| 295 | 303 | "meta-llama/llama-3-70b-instruct", |
| 296 | 304 | "arcee-ai/caller-large", |
| 297 | 305 | "nousresearch/hermes-3-llama-3.1-70b", |
| 306 | + "moonshotai/kimi-k2", | |
| 298 | 307 | ]; |
| 299 | 308 | for (const model of specificModels) { |
| 300 | 309 | if (model.toLowerCase() === model) { |
| @@ -325,6 +334,36 @@ | ||
| 325 | 334 | return true; |
| 326 | 335 | } |
| 327 | 336 | |
| 337 | + return false; | |
| 338 | + }, | |
| 339 | + novita: (model) => { | |
| 340 | + const lower = model.toLowerCase(); | |
| 341 | + | |
| 342 | + // Exact match models | |
| 343 | + const exactMatches = [ | |
| 344 | + "deepseek/deepseek-r1-0528", | |
| 345 | + "deepseek/deepseek-r1-turbo", | |
| 346 | + "deepseek/deepseek-v3-0324", | |
| 347 | + "deepseek/deepseek-v3-turbo", | |
| 348 | + "meta-llama/llama-3.3-70b-instruct", | |
| 349 | + "qwen/qwen-2.5-72b-instruct", | |
| 350 | + "zai-org/glm-4.5", | |
| 351 | + "moonshotai/kimi-k2-instruct", | |
| 352 | + ]; | |
| 353 | + | |
| 354 | + if (exactMatches.includes(lower)) { | |
| 355 | + return true; | |
| 356 | + } | |
| 357 | + | |
| 358 | + // Prefix match models | |
| 359 | + const prefixMatches = ["qwen/qwen3", "openai/gpt-oss"]; | |
| 360 | + | |
| 361 | + for (const prefix of prefixMatches) { | |
| 362 | + if (lower.startsWith(prefix)) { | |
| 363 | + return true; | |
| 364 | + } | |
| 365 | + } | |
| 366 | + | |
| 328 | 367 | return false; |
| 329 | 368 | }, |
| 330 | 369 | }; |
| @@ -335,8 +374,8 @@ | ||
| 335 | 374 | [/o[134]/], |
| 336 | 375 | [/deepseek/, /r1|reasoner/], |
| 337 | 376 | [/gemini/, /2\.5/, /pro/], |
| 338 | - [/gpt/, /4/], | |
| 339 | - [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], | |
| 377 | + [/gpt-5/], | |
| 378 | + [/claude/, /sonnet/, /3\.7|3-7|-4/], | |
| 340 | 379 | [/claude/, /opus/, /-4/], |
| 341 | 380 | ]; |
| 342 | 381 | for (const combo of recs) { |
modified core/nextEdit/NextEditEditableRegionCalculator.ts +4 −0
| @@ -13,6 +13,10 @@ | ||
| 13 | 13 | Static = "static", |
| 14 | 14 | } |
| 15 | 15 | |
| 16 | +/** | |
| 17 | + * This was an attempt to find next edit locations deterministically. | |
| 18 | + * I was intending to use this in tandem with the prefetching logic, but we are not using it anymore. | |
| 19 | + */ | |
| 16 | 20 | export async function getNextEditableRegion( |
| 17 | 21 | strategy: EditableRegionStrategy, |
| 18 | 22 | ctx: any, |
modified core/nextEdit/NextEditLoggingService.ts +110 −1
| @@ -11,6 +11,16 @@ | ||
| 11 | 11 | private _abortControllers = new Map<string, AbortController>(); |
| 12 | 12 | private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>(); |
| 13 | 13 | private _outcomes = new Map<string, NextEditOutcome>(); |
| 14 | + // Track minimal data for completions that get aborted before we have full outcome. | |
| 15 | + private _pendingCompletions = new Map< | |
| 16 | + string, | |
| 17 | + { | |
| 18 | + startTime: number; | |
| 19 | + modelName?: string; | |
| 20 | + modelProvider?: string; | |
| 21 | + filepath?: string; | |
| 22 | + } | |
| 23 | + >(); | |
| 14 | 24 | _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = |
| 15 | 25 | undefined; |
| 16 | 26 | |
| @@ -26,21 +36,54 @@ | ||
| 26 | 36 | public createAbortController(completionId: string): AbortController { |
| 27 | 37 | const abortController = new AbortController(); |
| 28 | 38 | this._abortControllers.set(completionId, abortController); |
| 39 | + this.trackPendingCompletion(completionId); | |
| 29 | 40 | return abortController; |
| 30 | 41 | } |
| 31 | 42 | |
| 32 | 43 | public deleteAbortController(completionId: string) { |
| 33 | 44 | this._abortControllers.delete(completionId); |
| 45 | + this._pendingCompletions.delete(completionId); | |
| 46 | + } | |
| 47 | + | |
| 48 | + // Keep track of a new completion request. | |
| 49 | + public trackPendingCompletion(completionId: string) { | |
| 50 | + this._pendingCompletions.set(completionId, { | |
| 51 | + startTime: Date.now(), | |
| 52 | + }); | |
| 53 | + } | |
| 54 | + | |
| 55 | + // Update pending completion info as it becomes available. | |
| 56 | + public updatePendingCompletion( | |
| 57 | + completionId: string, | |
| 58 | + data: { | |
| 59 | + modelName?: string; | |
| 60 | + modelProvider?: string; | |
| 61 | + filepath?: string; | |
| 62 | + }, | |
| 63 | + ) { | |
| 64 | + const pending = this._pendingCompletions.get(completionId); | |
| 65 | + if (pending) { | |
| 66 | + this._pendingCompletions.set(completionId, { ...pending, ...data }); | |
| 67 | + } else { | |
| 68 | + // If we haven't tracked it yet, create new entry with provided data. | |
| 69 | + this._pendingCompletions.set(completionId, { | |
| 70 | + startTime: Date.now(), | |
| 71 | + ...data, | |
| 72 | + }); | |
| 73 | + } | |
| 34 | 74 | } |
| 35 | 75 | |
| 36 | 76 | public cancel() { |
| 37 | - this._abortControllers.forEach((abortController, id) => { | |
| 77 | + this._abortControllers.forEach((abortController, completionId) => { | |
| 78 | + this.handleAbort(completionId); | |
| 38 | 79 | abortController.abort(); |
| 39 | 80 | }); |
| 40 | 81 | this._abortControllers.clear(); |
| 41 | 82 | } |
| 42 | 83 | |
| 43 | 84 | public accept(completionId: string): NextEditOutcome | undefined { |
| 85 | + this._pendingCompletions.delete(completionId); | |
| 86 | + | |
| 44 | 87 | if (this._logRejectionTimeouts.has(completionId)) { |
| 45 | 88 | clearTimeout(this._logRejectionTimeouts.get(completionId)); |
| 46 | 89 | this._logRejectionTimeouts.delete(completionId); |
| @@ -48,6 +91,7 @@ | ||
| 48 | 91 | if (this._outcomes.has(completionId)) { |
| 49 | 92 | const outcome = this._outcomes.get(completionId)!; |
| 50 | 93 | outcome.accepted = true; |
| 94 | + outcome.aborted = false; | |
| 51 | 95 | this.logNextEditOutcome(outcome); |
| 52 | 96 | this._outcomes.delete(completionId); |
| 53 | 97 | return outcome; |
| @@ -55,6 +99,8 @@ | ||
| 55 | 99 | } |
| 56 | 100 | |
| 57 | 101 | public reject(completionId: string): NextEditOutcome | undefined { |
| 102 | + this._pendingCompletions.delete(completionId); | |
| 103 | + | |
| 58 | 104 | if (this._logRejectionTimeouts.has(completionId)) { |
| 59 | 105 | clearTimeout(this._logRejectionTimeouts.get(completionId)); |
| 60 | 106 | this._logRejectionTimeouts.delete(completionId); |
| @@ -63,6 +109,7 @@ | ||
| 63 | 109 | if (this._outcomes.has(completionId)) { |
| 64 | 110 | const outcome = this._outcomes.get(completionId)!; |
| 65 | 111 | outcome.accepted = false; |
| 112 | + outcome.aborted = false; | |
| 66 | 113 | this.logNextEditOutcome(outcome); |
| 67 | 114 | this._outcomes.delete(completionId); |
| 68 | 115 | return outcome; |
| @@ -86,12 +133,19 @@ | ||
| 86 | 133 | } |
| 87 | 134 | |
| 88 | 135 | public markDisplayed(completionId: string, outcome: NextEditOutcome) { |
| 136 | + // Remove from pending since we now have full data. | |
| 137 | + this._pendingCompletions.delete(completionId); | |
| 138 | + outcome.aborted = false; | |
| 139 | + | |
| 89 | 140 | const logRejectionTimeout = setTimeout(() => { |
| 90 | 141 | // Wait 10 seconds, then assume it wasn't accepted |
| 91 | 142 | outcome.accepted = false; |
| 143 | + outcome.aborted = false; | |
| 92 | 144 | this.logNextEditOutcome(outcome); |
| 93 | 145 | this._logRejectionTimeouts.delete(completionId); |
| 146 | + this._outcomes.delete(completionId); | |
| 94 | 147 | }, COUNT_COMPLETION_REJECTED_AFTER); |
| 148 | + | |
| 95 | 149 | this._outcomes.set(completionId, outcome); |
| 96 | 150 | this._logRejectionTimeouts.set(completionId, logRejectionTimeout); |
| 97 | 151 | |
| @@ -124,7 +178,62 @@ | ||
| 124 | 178 | }; |
| 125 | 179 | } |
| 126 | 180 | |
| 181 | + public handleAbort(completionId: string) { | |
| 182 | + // Clear any pending rejection timeout. | |
| 183 | + if (this._logRejectionTimeouts.has(completionId)) { | |
| 184 | + clearTimeout(this._logRejectionTimeouts.get(completionId)); | |
| 185 | + this._logRejectionTimeouts.delete(completionId); | |
| 186 | + } | |
| 187 | + | |
| 188 | + // If we have the full outcome, log it as aborted. | |
| 189 | + if (this._outcomes.has(completionId)) { | |
| 190 | + const outcome = this._outcomes.get(completionId)!; | |
| 191 | + outcome.accepted = false; | |
| 192 | + outcome.aborted = true; | |
| 193 | + this.logNextEditOutcome(outcome); | |
| 194 | + this._outcomes.delete(completionId); | |
| 195 | + } else { | |
| 196 | + // Log minimal abort event for requests that never got displayed. | |
| 197 | + const pendingData = this._pendingCompletions.get(completionId); | |
| 198 | + | |
| 199 | + const minimalAbortOutcome: Partial<NextEditOutcome> = { | |
| 200 | + completionId, | |
| 201 | + accepted: false, | |
| 202 | + aborted: true, | |
| 203 | + timestamp: Date.now(), | |
| 204 | + uniqueId: completionId, | |
| 205 | + elapsed: pendingData ? Date.now() - pendingData.startTime : 0, | |
| 206 | + modelName: pendingData?.modelName || "unknown", | |
| 207 | + modelProvider: pendingData?.modelProvider || "unknown", | |
| 208 | + fileUri: pendingData?.filepath || "unknown", | |
| 209 | + | |
| 210 | + // Empty/default values for fields we don't have. | |
| 211 | + completion: "", | |
| 212 | + prompt: "", | |
| 213 | + userEdits: "", | |
| 214 | + userExcerpts: "", | |
| 215 | + originalEditableRange: "", | |
| 216 | + workspaceDirUri: "", | |
| 217 | + cursorPosition: { line: -1, character: -1 }, | |
| 218 | + finalCursorPosition: { line: -1, character: -1 }, | |
| 219 | + editableRegionStartLine: -1, | |
| 220 | + editableRegionEndLine: -1, | |
| 221 | + diffLines: [], | |
| 222 | + completionOptions: {}, | |
| 223 | + }; | |
| 224 | + | |
| 225 | + this.logNextEditOutcome(minimalAbortOutcome as NextEditOutcome); | |
| 226 | + } | |
| 227 | + | |
| 228 | + // Clean up. | |
| 229 | + this._pendingCompletions.delete(completionId); | |
| 230 | + } | |
| 231 | + | |
| 127 | 232 | private logNextEditOutcome(outcome: NextEditOutcome) { |
| 233 | + if (outcome.aborted === undefined) { | |
| 234 | + outcome.aborted = false; | |
| 235 | + } | |
| 236 | + | |
| 128 | 237 | void DataLogger.getInstance().logDevData({ |
| 129 | 238 | name: "nextEditOutcome", |
| 130 | 239 | data: outcome, |
modified core/nextEdit/NextEditPrefetchQueue.ts +8 −0
| @@ -7,6 +7,14 @@ | ||
| 7 | 7 | outcome: NextEditOutcome; // Result from the model |
| 8 | 8 | } |
| 9 | 9 | |
| 10 | +/** | |
| 11 | + * Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts | |
| 12 | + */ | |
| 13 | +/** | |
| 14 | + * This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain. | |
| 15 | + * I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background. | |
| 16 | + * Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea. | |
| 17 | + */ | |
| 10 | 18 | export class PrefetchQueue { |
| 11 | 19 | private static instance: PrefetchQueue | null = null; |
| 12 | 20 |
modified core/nextEdit/NextEditProvider.ts +128 −622
| @@ -1,15 +1,6 @@ | ||
| 1 | -import * as path from "path"; | |
| 2 | 1 | import { v4 as uuidv4 } from "uuid"; |
| 3 | 2 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | -import { | |
| 5 | - ChatMessage, | |
| 6 | - DiffLine, | |
| 7 | - IDE, | |
| 8 | - ILLM, | |
| 9 | - Position, | |
| 10 | - Range, | |
| 11 | - RangeInFile, | |
| 12 | -} from "../index.js"; | |
| 3 | +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; | |
| 13 | 4 | import OpenAI from "../llm/llms/OpenAI.js"; |
| 14 | 5 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; |
| 15 | 6 | |
| @@ -18,10 +9,7 @@ | ||
| 18 | 9 | import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; |
| 19 | 10 | import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; |
| 20 | 11 | import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; |
| 21 | -import { | |
| 22 | - getAllSnippetsWithoutRace, | |
| 23 | - SnippetPayload, | |
| 24 | -} from "../autocomplete/snippets/index.js"; | |
| 12 | +import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; | |
| 25 | 13 | import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; |
| 26 | 14 | import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; |
| 27 | 15 | import { getAst } from "../autocomplete/util/ast.js"; |
| @@ -29,37 +17,22 @@ | ||
| 29 | 17 | import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; |
| 30 | 18 | import { HelperVars } from "../autocomplete/util/HelperVars.js"; |
| 31 | 19 | import { AutocompleteInput } from "../autocomplete/util/types.js"; |
| 32 | -import { myersDiff } from "../diff/myers.js"; | |
| 20 | +import { isSecurityConcern } from "../indexing/ignore.js"; | |
| 33 | 21 | import { modelSupportsNextEdit } from "../llm/autodetect.js"; |
| 34 | -import { countTokens } from "../llm/countTokens.js"; | |
| 35 | 22 | import { localPathOrUriToPath } from "../util/pathToUri.js"; |
| 36 | -import { | |
| 37 | - INSTINCT_SYSTEM_PROMPT, | |
| 38 | - MERCURY_CODE_TO_EDIT_OPEN, | |
| 39 | - MERCURY_SYSTEM_PROMPT, | |
| 40 | - MODEL_WINDOW_SIZES, | |
| 41 | -} from "./constants.js"; | |
| 42 | 23 | import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; |
| 43 | -import { | |
| 44 | - calculateFinalCursorPosition, | |
| 45 | - DiffGroup, | |
| 46 | - groupDiffLines, | |
| 47 | -} from "./diff/diff.js"; | |
| 48 | 24 | import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; |
| 49 | 25 | import { NextEditLoggingService } from "./NextEditLoggingService.js"; |
| 50 | 26 | import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; |
| 27 | +import { NextEditProviderFactory } from "./NextEditProviderFactory.js"; | |
| 28 | +import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js"; | |
| 51 | 29 | import { |
| 52 | - renderDefaultSystemPrompt, | |
| 53 | - renderDefaultUserPrompt, | |
| 54 | - renderPrompt, | |
| 55 | -} from "./templating/NextEditPromptEngine.js"; | |
| 56 | -import { | |
| 30 | + ModelSpecificContext, | |
| 57 | 31 | NextEditOutcome, |
| 58 | 32 | Prompt, |
| 59 | 33 | PromptMetadata, |
| 60 | 34 | RecentlyEditedRange, |
| 61 | 35 | } from "./types.js"; |
| 62 | -import { isWhitespaceOnlyDeletion } from "./utils.js"; | |
| 63 | 36 | |
| 64 | 37 | const autocompleteCache = AutocompleteLruCache.get(); |
| 65 | 38 | |
| @@ -71,6 +44,14 @@ | ||
| 71 | 44 | "operation was aborted", |
| 72 | 45 | ]; |
| 73 | 46 | |
| 47 | +/** | |
| 48 | + * This is the next edit analogue to autocomplete's CompletionProvider. | |
| 49 | + * You will see a lot of similar if not identical methods to CompletionProvider methods. | |
| 50 | + * All logic used to live inside this class, but that became untenable quickly. | |
| 51 | + * I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it. | |
| 52 | + * Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc. | |
| 53 | + * There being a singleton also gives a lot of guarantees about the state of the next edit state machine. | |
| 54 | + */ | |
| 74 | 55 | export class NextEditProvider { |
| 75 | 56 | private static instance: NextEditProvider | null = null; |
| 76 | 57 | |
| @@ -88,7 +69,9 @@ | ||
| 88 | 69 | private currentEditChainId: string | null = null; |
| 89 | 70 | private previousRequest: AutocompleteInput | null = null; |
| 90 | 71 | private previousCompletions: NextEditOutcome[] = []; |
| 91 | - // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; | |
| 72 | + | |
| 73 | + // Model-specific provider instance. | |
| 74 | + private modelProvider: BaseNextEditModelProvider | null = null; | |
| 92 | 75 | |
| 93 | 76 | private constructor( |
| 94 | 77 | private readonly configHandler: ConfigHandler, |
| @@ -246,14 +229,14 @@ | ||
| 246 | 229 | |
| 247 | 230 | this.currentEditChainId = null; |
| 248 | 231 | this.previousCompletions = []; |
| 249 | - // TODO: this should be cleaned up in the prefetch queue. | |
| 250 | - // this.nextEditableRegionsInTheCurrentChain = []; | |
| 251 | 232 | |
| 252 | 233 | if (this.previousRequest) { |
| 253 | 234 | const fileContent = ( |
| 254 | 235 | await this.ide.readFile(this.previousRequest.filepath) |
| 255 | 236 | ).toString(); |
| 237 | + | |
| 256 | 238 | const ast = await getAst(this.previousRequest.filepath, fileContent); |
| 239 | + | |
| 257 | 240 | if (ast) { |
| 258 | 241 | DocumentHistoryTracker.getInstance().push( |
| 259 | 242 | localPathOrUriToPath(this.previousRequest.filepath), |
| @@ -276,6 +259,9 @@ | ||
| 276 | 259 | return this.previousCompletions.length === 1; |
| 277 | 260 | } |
| 278 | 261 | |
| 262 | + /** | |
| 263 | + * This is the main entry point to this class. | |
| 264 | + */ | |
| 279 | 265 | public async provideInlineCompletionItems( |
| 280 | 266 | input: AutocompleteInput, |
| 281 | 267 | token: AbortSignal | undefined, |
| @@ -284,6 +270,9 @@ | ||
| 284 | 270 | usingFullFileDiff: boolean; |
| 285 | 271 | }, |
| 286 | 272 | ): Promise<NextEditOutcome | undefined> { |
| 273 | + if (isSecurityConcern(input.filepath)) { | |
| 274 | + return undefined; | |
| 275 | + } | |
| 287 | 276 | try { |
| 288 | 277 | this.previousRequest = input; |
| 289 | 278 | const { |
| @@ -293,28 +282,23 @@ | ||
| 293 | 282 | } = await this._initializeCompletionRequest(input, token); |
| 294 | 283 | if (!helper) return undefined; |
| 295 | 284 | |
| 285 | + // Create model-specific provider based on the model name. | |
| 286 | + this.modelProvider = NextEditProviderFactory.createProvider( | |
| 287 | + helper.modelName, | |
| 288 | + ); | |
| 289 | + | |
| 296 | 290 | const { editableRegionStartLine, editableRegionEndLine, prompts } = |
| 297 | 291 | await this._generatePrompts(helper, opts); |
| 298 | 292 | |
| 299 | - if (this.endpointType === "default") { | |
| 300 | - return await this._handleDefaultEndpointCompletion( | |
| 301 | - helper, | |
| 302 | - prompts, | |
| 303 | - abortToken, | |
| 304 | - startTime, | |
| 305 | - editableRegionEndLine, | |
| 306 | - ); | |
| 307 | - } else { | |
| 308 | - return await this._handleFineTunedEndpointCompletion( | |
| 309 | - helper, | |
| 310 | - prompts, | |
| 311 | - abortToken, | |
| 312 | - startTime, | |
| 313 | - editableRegionStartLine, | |
| 314 | - editableRegionEndLine, | |
| 315 | - opts, | |
| 316 | - ); | |
| 317 | - } | |
| 293 | + return await this._handleCompletion( | |
| 294 | + helper, | |
| 295 | + prompts, | |
| 296 | + abortToken, | |
| 297 | + startTime, | |
| 298 | + editableRegionStartLine, | |
| 299 | + editableRegionEndLine, | |
| 300 | + opts, | |
| 301 | + ); | |
| 318 | 302 | } catch (e: any) { |
| 319 | 303 | this.onError(e); |
| 320 | 304 | } finally { |
| @@ -330,17 +314,21 @@ | ||
| 330 | 314 | startTime: number; |
| 331 | 315 | helper: HelperVars | undefined; |
| 332 | 316 | }> { |
| 333 | - // Create abort signal if not given. | |
| 317 | + // Create abort signal if not given | |
| 334 | 318 | if (!token) { |
| 335 | 319 | const controller = this.loggingService.createAbortController( |
| 336 | 320 | input.completionId, |
| 337 | 321 | ); |
| 338 | 322 | token = controller.signal; |
| 323 | + } else { | |
| 324 | + // Token was provided externally, just track the completion. | |
| 325 | + this.loggingService.trackPendingCompletion(input.completionId); | |
| 339 | 326 | } |
| 327 | + | |
| 340 | 328 | const startTime = Date.now(); |
| 341 | 329 | const options = await this._getAutocompleteOptions(); |
| 342 | 330 | |
| 343 | - // Debounce. | |
| 331 | + // Debounce | |
| 344 | 332 | if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { |
| 345 | 333 | return { token, startTime, helper: undefined }; |
| 346 | 334 | } |
| @@ -350,9 +338,14 @@ | ||
| 350 | 338 | return { token, startTime, helper: undefined }; |
| 351 | 339 | } |
| 352 | 340 | |
| 353 | - // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts. | |
| 354 | - // For other editors, this check should be done in their respective config reloaders. | |
| 355 | - // This is left for a final check. | |
| 341 | + // Update pending completion with model info. | |
| 342 | + this.loggingService.updatePendingCompletion(input.completionId, { | |
| 343 | + modelName: llm.model, | |
| 344 | + modelProvider: llm.providerName, | |
| 345 | + filepath: input.filepath, | |
| 346 | + }); | |
| 347 | + | |
| 348 | + // Check model capabilities | |
| 356 | 349 | if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) { |
| 357 | 350 | console.error(`${llm.model} is not capable of next edit.`); |
| 358 | 351 | return { token, startTime, helper: undefined }; |
| @@ -382,6 +375,12 @@ | ||
| 382 | 375 | editableRegionEndLine: number; |
| 383 | 376 | prompts: Prompt[]; |
| 384 | 377 | }> { |
| 378 | + if (!this.modelProvider) { | |
| 379 | + throw new Error("Model provider not initialized"); | |
| 380 | + } | |
| 381 | + | |
| 382 | + // NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets. | |
| 383 | + // Use getAllSnippets if snippet gathering becomes noticably slow. | |
| 385 | 384 | const [snippetPayload, workspaceDirs] = await Promise.all([ |
| 386 | 385 | getAllSnippetsWithoutRace({ |
| 387 | 386 | helper, |
| @@ -392,277 +391,41 @@ | ||
| 392 | 391 | this.ide.getWorkspaceDirs(), |
| 393 | 392 | ]); |
| 394 | 393 | |
| 395 | - const modelName = helper.modelName.includes("mercury-coder-nextedit") | |
| 396 | - ? "mercury-coder-nextedit" | |
| 397 | - : "instinct"; | |
| 398 | - | |
| 394 | + // Calculate editable region based on model and options. | |
| 399 | 395 | const { editableRegionStartLine, editableRegionEndLine } = |
| 400 | - opts?.usingFullFileDiff | |
| 401 | - ? this._calculateOptimalEditableRegion(helper, "tokenizer") | |
| 402 | - : { | |
| 403 | - editableRegionStartLine: Math.max( | |
| 404 | - helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin, | |
| 405 | - 0, | |
| 406 | - ), | |
| 407 | - editableRegionEndLine: Math.min( | |
| 408 | - helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin, | |
| 409 | - helper.fileLines.length - 1, | |
| 410 | - ), | |
| 411 | - }; | |
| 412 | - | |
| 413 | - // const editableRegionStartLine = opts?.usingFullFileDiff | |
| 414 | - // ? 0 | |
| 415 | - // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); | |
| 416 | - | |
| 417 | - // const editableRegionEndLine = opts?.usingFullFileDiff | |
| 418 | - // ? helper.fileLines.length - 1 | |
| 419 | - // : Math.min( | |
| 420 | - // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, | |
| 421 | - // helper.fileLines.length - 1, | |
| 422 | - // ); | |
| 423 | - | |
| 424 | - const prompts: Prompt[] = []; | |
| 425 | - | |
| 426 | - if (this.endpointType === "default") { | |
| 427 | - prompts.push(renderDefaultSystemPrompt()); | |
| 428 | - prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); | |
| 429 | - } else { | |
| 430 | - prompts.push( | |
| 431 | - ...(await this._generateFineTunedPrompts( | |
| 432 | - helper, | |
| 433 | - snippetPayload, | |
| 434 | - editableRegionStartLine, | |
| 435 | - editableRegionEndLine, | |
| 436 | - )), | |
| 396 | + this.modelProvider.calculateEditableRegion( | |
| 397 | + helper, | |
| 398 | + opts?.usingFullFileDiff ?? false, | |
| 437 | 399 | ); |
| 438 | - } | |
| 439 | - | |
| 440 | - return { editableRegionStartLine, editableRegionEndLine, prompts }; | |
| 441 | - } | |
| 442 | - | |
| 443 | - private _calculateOptimalEditableRegion( | |
| 444 | - helper: HelperVars, | |
| 445 | - heuristic: "fourChars" | "tokenizer" = "tokenizer", | |
| 446 | - ): { | |
| 447 | - editableRegionStartLine: number; | |
| 448 | - editableRegionEndLine: number; | |
| 449 | - } { | |
| 450 | - const cursorLine = helper.pos.line; | |
| 451 | - const fileLines = helper.fileLines; | |
| 452 | - const MAX_TOKENS = 512; | |
| 453 | - | |
| 454 | - // Initialize with cursor line. | |
| 455 | - let editableRegionStartLine = cursorLine; | |
| 456 | - let editableRegionEndLine = cursorLine; | |
| 457 | - | |
| 458 | - // Get initial content and token count. | |
| 459 | - let currentContent = fileLines[cursorLine]; | |
| 460 | - let totalTokens = | |
| 461 | - heuristic === "tokenizer" | |
| 462 | - ? countTokens(currentContent, helper.modelName) | |
| 463 | - : Math.ceil(currentContent.length / 4); | |
| 464 | - | |
| 465 | - // Expand outward alternating between adding lines above and below. | |
| 466 | - let addingAbove = true; | |
| 467 | - | |
| 468 | - while (totalTokens < MAX_TOKENS) { | |
| 469 | - let addedLine = false; | |
| 470 | - | |
| 471 | - if (addingAbove) { | |
| 472 | - // Try to add a line above. | |
| 473 | - if (editableRegionStartLine > 0) { | |
| 474 | - editableRegionStartLine--; | |
| 475 | - const lineContent = fileLines[editableRegionStartLine]; | |
| 476 | - const lineTokens = | |
| 477 | - heuristic === "tokenizer" | |
| 478 | - ? countTokens(lineContent, helper.modelName) | |
| 479 | - : Math.ceil(lineContent.length / 4); | |
| 480 | - | |
| 481 | - totalTokens += lineTokens; | |
| 482 | - addedLine = true; | |
| 483 | - } | |
| 484 | - } else { | |
| 485 | - // Try to add a line below. | |
| 486 | - if (editableRegionEndLine < fileLines.length - 1) { | |
| 487 | - editableRegionEndLine++; | |
| 488 | - const lineContent = fileLines[editableRegionEndLine]; | |
| 489 | - const lineTokens = | |
| 490 | - heuristic === "tokenizer" | |
| 491 | - ? countTokens(lineContent, helper.modelName) | |
| 492 | - : Math.ceil(lineContent.length / 4); | |
| 493 | - | |
| 494 | - totalTokens += lineTokens; | |
| 495 | - addedLine = true; | |
| 496 | - } | |
| 497 | - } | |
| 498 | - | |
| 499 | - // If we can't add in the current direction, try the other. | |
| 500 | - if (!addedLine) { | |
| 501 | - // If we're already at both file boundaries, we're done. | |
| 502 | - if ( | |
| 503 | - editableRegionStartLine === 0 && | |
| 504 | - editableRegionEndLine === fileLines.length - 1 | |
| 505 | - ) { | |
| 506 | - break; | |
| 507 | - } | |
| 508 | - | |
| 509 | - // If we couldn't add in one direction, force the next attempt in the other direction. | |
| 510 | - addingAbove = !addingAbove; | |
| 511 | - continue; | |
| 512 | - } | |
| 513 | - | |
| 514 | - // If we exceeded the token limit, revert the last addition. | |
| 515 | - if (totalTokens > MAX_TOKENS) { | |
| 516 | - if (addingAbove) { | |
| 517 | - editableRegionStartLine++; | |
| 518 | - } else { | |
| 519 | - editableRegionEndLine--; | |
| 520 | - } | |
| 521 | - break; | |
| 522 | - } | |
| 523 | - | |
| 524 | - // Alternate between adding above and below for balanced context. | |
| 525 | - addingAbove = !addingAbove; | |
| 526 | - } | |
| 527 | 400 | |
| 528 | - return { | |
| 401 | + // Build context for model-specific prompt generation. | |
| 402 | + const context: ModelSpecificContext = { | |
| 403 | + helper, | |
| 404 | + snippetPayload, | |
| 529 | 405 | editableRegionStartLine, |
| 530 | 406 | editableRegionEndLine, |
| 407 | + diffContext: this.diffContext, | |
| 408 | + autocompleteContext: this.autocompleteContext, | |
| 409 | + historyDiff: createDiff({ | |
| 410 | + beforeContent: | |
| 411 | + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( | |
| 412 | + localPathOrUriToPath(helper.filepath), | |
| 413 | + ) ?? "", | |
| 414 | + afterContent: helper.fileContents, | |
| 415 | + filePath: helper.filepath, | |
| 416 | + diffType: DiffFormatType.Unified, | |
| 417 | + contextLines: 3, | |
| 418 | + }), | |
| 531 | 419 | }; |
| 532 | - } | |
| 533 | - | |
| 534 | - private async _generateFineTunedPrompts( | |
| 535 | - helper: HelperVars, | |
| 536 | - snippetPayload: SnippetPayload, | |
| 537 | - editableRegionStartLine: number, | |
| 538 | - editableRegionEndLine: number, | |
| 539 | - ): Promise<Prompt[]> { | |
| 540 | - const historyDiff = createDiff({ | |
| 541 | - beforeContent: | |
| 542 | - DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( | |
| 543 | - localPathOrUriToPath(helper.filepath), | |
| 544 | - ) ?? "", | |
| 545 | - afterContent: helper.fileContents, | |
| 546 | - filePath: helper.filepath, | |
| 547 | - diffType: DiffFormatType.Unified, | |
| 548 | - contextLines: 3, | |
| 549 | - }); | |
| 550 | - | |
| 551 | - const modelName = helper.modelName; | |
| 552 | - let ctx: any; | |
| 553 | - | |
| 554 | - if (modelName.includes("mercury-coder-nextedit")) { | |
| 555 | - ctx = { | |
| 556 | - recentlyViewedCodeSnippets: | |
| 557 | - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ | |
| 558 | - filepath: snip.filepath, | |
| 559 | - content: snip.content, | |
| 560 | - })) ?? [], | |
| 561 | - currentFileContent: helper.fileContents, | |
| 562 | - editableRegionStartLine, | |
| 563 | - editableRegionEndLine, | |
| 564 | - editDiffHistory: this.diffContext, | |
| 565 | - currentFilePath: helper.filepath, | |
| 566 | - }; | |
| 567 | - } else if (modelName.includes("instinct")) { | |
| 568 | - // Calculate the window around the cursor position (25 lines above and below). | |
| 569 | - const windowStart = Math.max(0, helper.pos.line - 25); | |
| 570 | - const windowEnd = Math.min( | |
| 571 | - helper.fileLines.length - 1, | |
| 572 | - helper.pos.line + 25, | |
| 573 | - ); | |
| 574 | - | |
| 575 | - // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). | |
| 576 | - // const actualEditableStart = Math.max( | |
| 577 | - // 0, | |
| 578 | - // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, | |
| 579 | - // ); | |
| 580 | - // const actualEditableEnd = Math.min( | |
| 581 | - // helper.fileLines.length - 1, | |
| 582 | - // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, | |
| 583 | - // ); | |
| 584 | - | |
| 585 | - // Ensure editable region boundaries are within the window. | |
| 586 | - const adjustedEditableStart = Math.max( | |
| 587 | - windowStart, | |
| 588 | - editableRegionStartLine, | |
| 589 | - ); | |
| 590 | - const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine); | |
| 591 | - ctx = { | |
| 592 | - contextSnippets: this.autocompleteContext, | |
| 593 | - currentFileContent: helper.fileContents, | |
| 594 | - windowStart, | |
| 595 | - windowEnd, | |
| 596 | - editableRegionStartLine: adjustedEditableStart, | |
| 597 | - editableRegionEndLine: adjustedEditableEnd, | |
| 598 | - editDiffHistory: this.diffContext, | |
| 599 | - currentFilePath: helper.filepath, | |
| 600 | - languageShorthand: helper.lang.name, | |
| 601 | - }; | |
| 602 | - } else { | |
| 603 | - ctx = {}; | |
| 604 | - } | |
| 605 | - | |
| 606 | - const promptMetadata = await renderPrompt(helper, ctx); | |
| 607 | - this.promptMetadata = promptMetadata; | |
| 608 | - | |
| 609 | - const systemPrompt: Prompt = { | |
| 610 | - role: "system", | |
| 611 | - content: modelName.includes("mercury-coder-nextedit") | |
| 612 | - ? MERCURY_SYSTEM_PROMPT | |
| 613 | - : INSTINCT_SYSTEM_PROMPT, | |
| 614 | - }; | |
| 615 | - | |
| 616 | - return [systemPrompt, promptMetadata.prompt]; | |
| 617 | - } | |
| 618 | - | |
| 619 | - private async _handleDefaultEndpointCompletion( | |
| 620 | - helper: HelperVars, | |
| 621 | - prompts: Prompt[], | |
| 622 | - token: AbortSignal, | |
| 623 | - startTime: number, | |
| 624 | - editableRegionEndLine: number, | |
| 625 | - ): Promise<NextEditOutcome | undefined> { | |
| 626 | - const llm = await this._prepareLlm(); | |
| 627 | - if (!llm) return undefined; | |
| 628 | - | |
| 629 | - const msg: ChatMessage = await llm.chat(prompts, token); | |
| 630 | 420 | |
| 631 | - if (typeof msg.content === "string") { | |
| 632 | - const nextCompletion = JSON.parse(msg.content).newCode; | |
| 633 | - const finalCursorPos: Position = { | |
| 634 | - line: editableRegionEndLine, | |
| 635 | - character: 0, | |
| 636 | - }; | |
| 637 | - | |
| 638 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 639 | - helper, | |
| 640 | - startTime, | |
| 641 | - llm, | |
| 642 | - promptContent: prompts.join("\n"), | |
| 643 | - completion: nextCompletion, | |
| 644 | - finalCursorPosition: finalCursorPos, | |
| 645 | - editableRegionStartLine: 0, | |
| 646 | - editableRegionEndLine: 0, | |
| 647 | - userEdits: "", | |
| 648 | - userExcerpts: "", | |
| 649 | - originalEditableRange: "", | |
| 650 | - diffLines: [], | |
| 651 | - }); | |
| 652 | - | |
| 653 | - // Mark as displayed for JetBrains extension | |
| 654 | - await this._markDisplayedIfJetBrains( | |
| 655 | - helper.input.completionId, | |
| 656 | - outcomeNext, | |
| 657 | - ); | |
| 421 | + const prompts = await this.modelProvider.generatePrompts(context); | |
| 658 | 422 | |
| 659 | - return outcomeNext; | |
| 660 | - } | |
| 423 | + this.promptMetadata = this.modelProvider.buildPromptMetadata(context); | |
| 661 | 424 | |
| 662 | - return undefined; | |
| 425 | + return { editableRegionStartLine, editableRegionEndLine, prompts }; | |
| 663 | 426 | } |
| 664 | 427 | |
| 665 | - private async _handleFineTunedEndpointCompletion( | |
| 428 | + private async _handleCompletion( | |
| 666 | 429 | helper: HelperVars, |
| 667 | 430 | prompts: Prompt[], |
| 668 | 431 | token: AbortSignal, |
| @@ -674,338 +437,75 @@ | ||
| 674 | 437 | usingFullFileDiff: boolean; |
| 675 | 438 | }, |
| 676 | 439 | ): Promise<NextEditOutcome | undefined> { |
| 440 | + if (!this.modelProvider) { | |
| 441 | + throw new Error("Model provider not initialized"); | |
| 442 | + } | |
| 443 | + | |
| 677 | 444 | const llm = await this._prepareLlm(); |
| 678 | 445 | if (!llm) return undefined; |
| 679 | 446 | |
| 680 | - const msg: ChatMessage = await llm.chat(prompts, token); | |
| 681 | - console.log("message"); | |
| 682 | - console.log(msg.content); | |
| 447 | + // Inject unique token if needed (for Mercury models). | |
| 448 | + if (this.modelProvider.shouldInjectUniqueToken()) { | |
| 449 | + const uniqueToken = this.modelProvider.getUniqueToken(); | |
| 450 | + if (uniqueToken) { | |
| 451 | + const lastPrompt = prompts[prompts.length - 1]; | |
| 452 | + if (lastPrompt && typeof lastPrompt.content === "string") { | |
| 453 | + lastPrompt.content += uniqueToken; | |
| 454 | + } | |
| 455 | + } | |
| 456 | + } | |
| 457 | + | |
| 458 | + // Send prompts to LLM (using only user prompt for fine-tuned models). | |
| 459 | + // prompts[1] extracts the user prompt from the system-user prompt pair. | |
| 460 | + // NOTE: Stream is currently set to false, but this should ideally be a per-model flag. | |
| 461 | + // Mercury Coder currently does not support streaming. | |
| 462 | + const msg: ChatMessage = await llm.chat([prompts[1]], token, { | |
| 463 | + stream: false, | |
| 464 | + }); | |
| 683 | 465 | |
| 684 | 466 | if (typeof msg.content !== "string") { |
| 685 | 467 | return undefined; |
| 686 | 468 | } |
| 687 | 469 | |
| 688 | - // const nextCompletion = msg.content.split( | |
| 689 | - // `${MERCURY_CODE_TO_EDIT_OPEN}\n`, | |
| 690 | - // )[1] | |
| 691 | - // ? replaceEscapedCharacters( | |
| 692 | - // msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], | |
| 693 | - // ).replace(/\n$/, "") | |
| 694 | - // : replaceEscapedCharacters(msg.content); | |
| 695 | - const nextCompletion = | |
| 696 | - msg.content | |
| 697 | - .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] | |
| 698 | - .replace(/\n$/, "") ?? msg.content; | |
| 470 | + // Extract completion using model-specific logic. | |
| 471 | + const nextCompletion = this.modelProvider.extractCompletion(msg.content); | |
| 699 | 472 | |
| 473 | + let outcome: NextEditOutcome | undefined; | |
| 474 | + | |
| 475 | + // Handle based on diff type. | |
| 700 | 476 | if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { |
| 701 | - return await this._handlePartialFileDiff( | |
| 702 | - // we could use fillFileDiff | |
| 477 | + outcome = await this.modelProvider.handlePartialFileDiff( | |
| 703 | 478 | helper, |
| 704 | 479 | editableRegionStartLine, |
| 705 | 480 | editableRegionEndLine, |
| 706 | 481 | startTime, |
| 707 | 482 | llm, |
| 708 | 483 | nextCompletion, |
| 484 | + this.promptMetadata!, | |
| 485 | + this.ide, | |
| 709 | 486 | ); |
| 710 | 487 | } else { |
| 711 | - return await this._handleFullFileDiff( | |
| 488 | + outcome = await this.modelProvider.handleFullFileDiff( | |
| 712 | 489 | helper, |
| 713 | 490 | editableRegionStartLine, |
| 714 | 491 | editableRegionEndLine, |
| 715 | 492 | startTime, |
| 716 | 493 | llm, |
| 717 | 494 | nextCompletion, |
| 495 | + this.promptMetadata!, | |
| 496 | + this.ide, | |
| 718 | 497 | ); |
| 719 | 498 | } |
| 720 | - } | |
| 721 | - | |
| 722 | - private async _handlePartialFileDiff( | |
| 723 | - helper: HelperVars, | |
| 724 | - editableRegionStartLine: number, | |
| 725 | - editableRegionEndLine: number, | |
| 726 | - startTime: number, | |
| 727 | - llm: ILLM, | |
| 728 | - nextCompletion: string, | |
| 729 | - ): Promise<NextEditOutcome | undefined> { | |
| 730 | - const oldEditRangeSlice = helper.fileContents | |
| 731 | - .split("\n") | |
| 732 | - .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 733 | - .join("\n"); | |
| 734 | - | |
| 735 | - const finalCursorPos = calculateFinalCursorPosition( | |
| 736 | - helper.pos, | |
| 737 | - editableRegionStartLine, | |
| 738 | - oldEditRangeSlice, | |
| 739 | - nextCompletion, | |
| 740 | - ); | |
| 741 | - | |
| 742 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 743 | - helper, | |
| 744 | - startTime, | |
| 745 | - llm, | |
| 746 | - promptContent: this.promptMetadata!.prompt.content, | |
| 747 | - completion: nextCompletion, | |
| 748 | - finalCursorPosition: finalCursorPos, | |
| 749 | - editableRegionStartLine, | |
| 750 | - editableRegionEndLine, | |
| 751 | - userEdits: this.promptMetadata!.userEdits, | |
| 752 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 753 | - originalEditableRange: oldEditRangeSlice, | |
| 754 | - diffLines: [], | |
| 755 | - }); | |
| 756 | - | |
| 757 | - this.previousCompletions.push(outcomeNext); | |
| 758 | - | |
| 759 | - // Mark as displayed for JetBrains extension | |
| 760 | - await this._markDisplayedIfJetBrains( | |
| 761 | - helper.input.completionId, | |
| 762 | - outcomeNext, | |
| 763 | - ); | |
| 764 | - | |
| 765 | - return outcomeNext; | |
| 766 | - } | |
| 767 | - | |
| 768 | - private async _handleFullFileDiff( | |
| 769 | - helper: HelperVars, | |
| 770 | - editableRegionStartLine: number, | |
| 771 | - editableRegionEndLine: number, | |
| 772 | - startTime: number, | |
| 773 | - llm: ILLM, | |
| 774 | - nextCompletion: string, | |
| 775 | - ): Promise<NextEditOutcome | undefined> { | |
| 776 | - const fileSlice = helper.fileLines | |
| 777 | - .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 778 | - .join("\n"); | |
| 779 | - const diffLines = myersDiff(fileSlice, nextCompletion); | |
| 780 | - const diffGroups = groupDiffLines( | |
| 781 | - diffLines, | |
| 782 | - editableRegionStartLine, | |
| 783 | - 5, | |
| 784 | - ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); | |
| 785 | - const currentLine = helper.pos.line; | |
| 786 | - const prefetchQueue = PrefetchQueue.getInstance(); | |
| 787 | - | |
| 788 | - // Process diff groups and find the one containing the cursor | |
| 789 | - const cursorLocalDiffGroup = await this._processDiffGroups( | |
| 790 | - diffGroups, | |
| 791 | - currentLine, | |
| 792 | - helper, | |
| 793 | - startTime, | |
| 794 | - llm, | |
| 795 | - prefetchQueue, | |
| 796 | - ); | |
| 797 | - | |
| 798 | - // Handle the diff group containing the cursor if found | |
| 799 | - if (cursorLocalDiffGroup) { | |
| 800 | - return await this._createOutcomeFromDiffGroup( | |
| 801 | - cursorLocalDiffGroup, | |
| 802 | - helper, | |
| 803 | - startTime, | |
| 804 | - llm, | |
| 805 | - helper.input.completionId, | |
| 806 | - true, | |
| 807 | - ); | |
| 808 | - // } else if (diffGroups.length > 0) { | |
| 809 | - // // Fallback to first diff group if cursor's group not found | |
| 810 | - // return await this._createOutcomeFromDiffGroup( | |
| 811 | - // diffGroups[0], | |
| 812 | - // helper, | |
| 813 | - // startTime, | |
| 814 | - // llm, | |
| 815 | - // helper.input.completionId, | |
| 816 | - // false, | |
| 817 | - // ); | |
| 818 | - } | |
| 819 | 499 | |
| 820 | - return undefined; | |
| 821 | - } | |
| 500 | + if (outcome) { | |
| 501 | + // Handle NextEditProvider-specific state. | |
| 502 | + this.previousCompletions.push(outcome); | |
| 822 | 503 | |
| 823 | - private async _processDiffGroups( | |
| 824 | - diffGroups: DiffGroup[], | |
| 825 | - currentLine: number, | |
| 826 | - helper: HelperVars, | |
| 827 | - startTime: number, | |
| 828 | - llm: ILLM, | |
| 829 | - prefetchQueue: PrefetchQueue, | |
| 830 | - ): Promise<DiffGroup | undefined> { | |
| 831 | - let cursorGroup: DiffGroup | undefined; | |
| 832 | - | |
| 833 | - console.log("diffGroups:"); | |
| 834 | - console.log(diffGroups); | |
| 835 | - | |
| 836 | - for (const group of diffGroups) { | |
| 837 | - if (currentLine >= group.startLine && currentLine <= group.endLine) { | |
| 838 | - cursorGroup = group; | |
| 839 | - } else { | |
| 840 | - // Add non-cursor groups to prefetch queue | |
| 841 | - await this._addDiffGroupToPrefetchQueue( | |
| 842 | - group, | |
| 843 | - helper, | |
| 844 | - startTime, | |
| 845 | - llm, | |
| 846 | - prefetchQueue, | |
| 847 | - ); | |
| 848 | - } | |
| 504 | + // Mark as displayed for JetBrains | |
| 505 | + await this._markDisplayedIfJetBrains(helper.input.completionId, outcome); | |
| 849 | 506 | } |
| 850 | 507 | |
| 851 | - return cursorGroup; | |
| 852 | - } | |
| 853 | - | |
| 854 | - private async _addDiffGroupToPrefetchQueue( | |
| 855 | - group: DiffGroup, | |
| 856 | - helper: HelperVars, | |
| 857 | - startTime: number, | |
| 858 | - llm: ILLM, | |
| 859 | - prefetchQueue: PrefetchQueue, | |
| 860 | - ): Promise<void> { | |
| 861 | - const groupContent = group.lines | |
| 862 | - .filter((l) => l.type !== "old") | |
| 863 | - .map((l) => l.line) | |
| 864 | - .join("\n"); | |
| 865 | - | |
| 866 | - // Create a range for this diff group | |
| 867 | - const rangeInFile: RangeInFile = { | |
| 868 | - filepath: helper.filepath, | |
| 869 | - range: { | |
| 870 | - start: { line: group.startLine, character: 0 }, | |
| 871 | - end: { | |
| 872 | - line: group.endLine, | |
| 873 | - character: group.lines[group.lines.length - 1].line.length, | |
| 874 | - }, | |
| 875 | - }, | |
| 876 | - }; | |
| 877 | - | |
| 878 | - const originalContent = group.lines | |
| 879 | - .filter((l) => l.type !== "new") | |
| 880 | - .map((l) => l.line) | |
| 881 | - .join("\n"); | |
| 882 | - | |
| 883 | - // Build outcome for this diff group | |
| 884 | - const groupOutcome = await this._createNextEditOutcome({ | |
| 885 | - helper, | |
| 886 | - startTime, | |
| 887 | - llm, | |
| 888 | - promptContent: this.promptMetadata!.prompt.content, | |
| 889 | - completion: groupContent, | |
| 890 | - finalCursorPosition: { | |
| 891 | - line: group.endLine, | |
| 892 | - character: group.lines[group.lines.length - 1].line.length, | |
| 893 | - }, | |
| 894 | - editableRegionStartLine: group.startLine, | |
| 895 | - editableRegionEndLine: group.endLine, | |
| 896 | - userEdits: this.promptMetadata!.userEdits, | |
| 897 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 898 | - originalEditableRange: originalContent, | |
| 899 | - cursorPosition: { line: group.startLine, character: 0 }, | |
| 900 | - completionId: uuidv4(), // Generate a new ID for this prefetched item | |
| 901 | - diffLines: group.lines, | |
| 902 | - }); | |
| 903 | - | |
| 904 | - // Add to prefetch queue | |
| 905 | - prefetchQueue.enqueueProcessed({ | |
| 906 | - location: rangeInFile, | |
| 907 | - outcome: groupOutcome, | |
| 908 | - }); | |
| 909 | - } | |
| 910 | - | |
| 911 | - private async _createOutcomeFromDiffGroup( | |
| 912 | - diffGroup: DiffGroup, | |
| 913 | - helper: HelperVars, | |
| 914 | - startTime: number, | |
| 915 | - llm: ILLM, | |
| 916 | - completionId: string, | |
| 917 | - isCurrentCursorGroup: boolean, | |
| 918 | - ): Promise<NextEditOutcome> { | |
| 919 | - const groupContent = diffGroup.lines | |
| 920 | - .filter((l) => l.type !== "old") | |
| 921 | - .map((line) => line.line) | |
| 922 | - .join("\n"); | |
| 923 | - | |
| 924 | - const originalContent = diffGroup.lines | |
| 925 | - .filter((l) => l.type !== "new") | |
| 926 | - .map((l) => l.line) | |
| 927 | - .join("\n"); | |
| 928 | - | |
| 929 | - // Use the actual cursor position if this is the group containing the cursor | |
| 930 | - // Otherwise use the start of the diff group | |
| 931 | - const cursorPos = isCurrentCursorGroup | |
| 932 | - ? helper.pos | |
| 933 | - : { line: diffGroup.startLine, character: 0 }; | |
| 934 | - | |
| 935 | - const finalCursorPos = calculateFinalCursorPosition( | |
| 936 | - cursorPos, | |
| 937 | - diffGroup.startLine, | |
| 938 | - originalContent, | |
| 939 | - groupContent, | |
| 940 | - ); | |
| 941 | - | |
| 942 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 943 | - helper, | |
| 944 | - startTime, | |
| 945 | - llm, | |
| 946 | - promptContent: this.promptMetadata!.prompt.content, | |
| 947 | - completion: groupContent, | |
| 948 | - finalCursorPosition: finalCursorPos, | |
| 949 | - editableRegionStartLine: diffGroup.startLine, | |
| 950 | - editableRegionEndLine: diffGroup.endLine, | |
| 951 | - userEdits: this.promptMetadata!.userEdits, | |
| 952 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 953 | - originalEditableRange: originalContent, | |
| 954 | - cursorPosition: cursorPos, | |
| 955 | - completionId, | |
| 956 | - diffLines: diffGroup.lines, | |
| 957 | - }); | |
| 958 | - | |
| 959 | - this.previousCompletions.push(outcomeNext); | |
| 960 | - | |
| 961 | - // Mark as displayed for JetBrains | |
| 962 | - await this._markDisplayedIfJetBrains(completionId, outcomeNext); | |
| 963 | - | |
| 964 | - return outcomeNext; | |
| 965 | - } | |
| 966 | - | |
| 967 | - private async _createNextEditOutcome(outcomeCtx: { | |
| 968 | - helper: HelperVars; | |
| 969 | - startTime: number; | |
| 970 | - llm: ILLM; | |
| 971 | - promptContent: string; | |
| 972 | - completion: string; | |
| 973 | - finalCursorPosition: Position; | |
| 974 | - editableRegionStartLine: number; | |
| 975 | - editableRegionEndLine: number; | |
| 976 | - userEdits: string; | |
| 977 | - userExcerpts: string; | |
| 978 | - originalEditableRange: string; | |
| 979 | - cursorPosition?: Position; | |
| 980 | - completionId?: string; | |
| 981 | - diffLines: DiffLine[]; | |
| 982 | - }): Promise<NextEditOutcome> { | |
| 983 | - return { | |
| 984 | - elapsed: Date.now() - outcomeCtx.startTime, | |
| 985 | - modelProvider: outcomeCtx.llm.underlyingProviderName, | |
| 986 | - modelName: outcomeCtx.llm.model + ":zetaDataset", | |
| 987 | - completionOptions: null, | |
| 988 | - completionId: | |
| 989 | - outcomeCtx.completionId || outcomeCtx.helper.input.completionId, | |
| 990 | - gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath), | |
| 991 | - uniqueId: await this.ide.getUniqueId(), | |
| 992 | - timestamp: Date.now(), | |
| 993 | - fileUri: outcomeCtx.helper.filepath, | |
| 994 | - workspaceDirUri: | |
| 995 | - outcomeCtx.helper.workspaceUris[0] ?? | |
| 996 | - path.dirname(outcomeCtx.helper.filepath), | |
| 997 | - prompt: outcomeCtx.promptContent, | |
| 998 | - userEdits: outcomeCtx.userEdits ?? "", | |
| 999 | - userExcerpts: outcomeCtx.userExcerpts ?? "", | |
| 1000 | - originalEditableRange: outcomeCtx.originalEditableRange ?? "", | |
| 1001 | - completion: outcomeCtx.completion, | |
| 1002 | - cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, | |
| 1003 | - finalCursorPosition: outcomeCtx.finalCursorPosition, | |
| 1004 | - editableRegionStartLine: outcomeCtx.editableRegionStartLine, | |
| 1005 | - editableRegionEndLine: outcomeCtx.editableRegionEndLine, | |
| 1006 | - diffLines: outcomeCtx.diffLines, | |
| 1007 | - ...outcomeCtx.helper.options, | |
| 1008 | - }; | |
| 508 | + return outcome; | |
| 1009 | 509 | } |
| 1010 | 510 | |
| 1011 | 511 | private async _markDisplayedIfJetBrains( |
| @@ -1018,6 +518,12 @@ | ||
| 1018 | 518 | } |
| 1019 | 519 | } |
| 1020 | 520 | |
| 521 | + /** | |
| 522 | + * This is a wrapper around provideInlineCompletionItems. | |
| 523 | + * This is invoked when we call the model in the background using prefetch. | |
| 524 | + * It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch. | |
| 525 | + * You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`. | |
| 526 | + */ | |
| 1021 | 527 | public async provideInlineCompletionItemsWithChain( |
| 1022 | 528 | ctx: { |
| 1023 | 529 | completionId: string; |
deleted core/nextEdit/NextEditProvider.vitest.ts +0 −259
| @@ -1,259 +0,0 @@ | ||
| 1 | -import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | -import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; | |
| 3 | -import { HelperVars } from "../autocomplete/util/HelperVars.js"; | |
| 4 | -import { ConfigHandler } from "../config/ConfigHandler.js"; | |
| 5 | -import { IDE, ILLM } from "../index.js"; | |
| 6 | -import { NextEditProvider } from "./NextEditProvider.js"; | |
| 7 | - | |
| 8 | -// Mock the countTokens function | |
| 9 | -vi.mock("../llm/countTokens.js", () => ({ | |
| 10 | - countTokens: (text: string) => { | |
| 11 | - // Simple mock that counts 1 token per character for predictable tests | |
| 12 | - return text.length; | |
| 13 | - }, | |
| 14 | -})); | |
| 15 | - | |
| 16 | -// Create a helper function to set up the test context | |
| 17 | -function createMockHelper( | |
| 18 | - fileContents: string, | |
| 19 | - cursorLine: number, | |
| 20 | -): HelperVars { | |
| 21 | - const fileLines = fileContents.split("\n"); | |
| 22 | - | |
| 23 | - return { | |
| 24 | - fileLines, | |
| 25 | - fileContents, | |
| 26 | - pos: { line: cursorLine, character: 0 }, | |
| 27 | - modelName: "gpt-4", | |
| 28 | - lang: { name: "typescript" }, | |
| 29 | - filepath: "test/file.ts", | |
| 30 | - workspaceUris: ["test/workspace"], | |
| 31 | - options: {}, | |
| 32 | - input: { completionId: "test-completion-id" }, | |
| 33 | - } as unknown as HelperVars; | |
| 34 | -} | |
| 35 | - | |
| 36 | -// TODO: Add more tests for other methods. | |
| 37 | -describe("_calculateOptimalEditableRegion", () => { | |
| 38 | - let nextEditProvider: NextEditProvider; | |
| 39 | - let mockConfigHandler: ConfigHandler; | |
| 40 | - let mockIde: IDE; | |
| 41 | - let mockGetLlm: () => Promise<ILLM | undefined>; | |
| 42 | - let mockOnError: (e: any) => void; | |
| 43 | - let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction; | |
| 44 | - | |
| 45 | - beforeEach(() => { | |
| 46 | - // Create comprehensive mocks for all dependencies | |
| 47 | - mockConfigHandler = { | |
| 48 | - loadConfig: vi.fn().mockResolvedValue({ config: {} }), | |
| 49 | - } as unknown as ConfigHandler; | |
| 50 | - | |
| 51 | - mockIde = { | |
| 52 | - readFile: vi.fn().mockResolvedValue(""), | |
| 53 | - getWorkspaceDirs: vi.fn().mockResolvedValue([]), | |
| 54 | - getRepoName: vi.fn().mockResolvedValue("test-repo"), | |
| 55 | - getUniqueId: vi.fn().mockResolvedValue("test-id"), | |
| 56 | - getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }), | |
| 57 | - onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => { | |
| 58 | - // Return a disposable object that does nothing when disposed | |
| 59 | - return { | |
| 60 | - dispose: () => {}, | |
| 61 | - }; | |
| 62 | - }), | |
| 63 | - } as unknown as IDE; | |
| 64 | - | |
| 65 | - mockGetLlm = vi.fn().mockResolvedValue({ | |
| 66 | - model: "gpt-4", | |
| 67 | - providerName: "openai", | |
| 68 | - underlyingProviderName: "openai", | |
| 69 | - completionOptions: {}, | |
| 70 | - chat: vi.fn(), | |
| 71 | - }); | |
| 72 | - | |
| 73 | - mockOnError = vi.fn(); | |
| 74 | - mockGetDefinitionsFromLsp = vi.fn(); | |
| 75 | - | |
| 76 | - // Initialize NextEditProvider with mocked dependencies | |
| 77 | - nextEditProvider = NextEditProvider.initialize( | |
| 78 | - mockConfigHandler, | |
| 79 | - mockIde, | |
| 80 | - mockGetLlm, | |
| 81 | - mockOnError, | |
| 82 | - mockGetDefinitionsFromLsp, | |
| 83 | - "default", | |
| 84 | - ); | |
| 85 | - | |
| 86 | - // Expose the private method for testing | |
| 87 | - // This is a bit of a hack, but necessary for testing private methods | |
| 88 | - (nextEditProvider as any)._calculateOptimalEditableRegion = ( | |
| 89 | - NextEditProvider.prototype as any | |
| 90 | - )._calculateOptimalEditableRegion.bind(nextEditProvider); | |
| 91 | - }); | |
| 92 | - | |
| 93 | - // Test cases remain the same as before... | |
| 94 | - it("should include only the cursor line when it already exceeds token limit", () => { | |
| 95 | - // Create a mock helper with a very long cursor line (>500 characters) | |
| 96 | - const longLine = "X".repeat(600); | |
| 97 | - const helper = createMockHelper(longLine, 0); | |
| 98 | - | |
| 99 | - //@ts-ignore | |
| 100 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 101 | - helper, | |
| 102 | - "tokenizer", | |
| 103 | - ); | |
| 104 | - | |
| 105 | - expect(result.editableRegionStartLine).toBe(0); | |
| 106 | - expect(result.editableRegionEndLine).toBe(0); | |
| 107 | - }); | |
| 108 | - | |
| 109 | - it("should expand symmetrically when possible", () => { | |
| 110 | - // Create content with identical lines and cursor in the middle | |
| 111 | - const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each | |
| 112 | - const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5) | |
| 113 | - | |
| 114 | - //@ts-ignore | |
| 115 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 116 | - helper, | |
| 117 | - "tokenizer", | |
| 118 | - ); | |
| 119 | - | |
| 120 | - // Should expand 5 lines in each direction (total 11 lines) for symmetry | |
| 121 | - expect(result.editableRegionStartLine).toBe(0); | |
| 122 | - expect(result.editableRegionEndLine).toBe(10); | |
| 123 | - }); | |
| 124 | - | |
| 125 | - it("should expand asymmetrically when hitting a file boundary", () => { | |
| 126 | - // Create content with cursor near the top | |
| 127 | - const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each | |
| 128 | - const helper = createMockHelper(lines, 1); // Cursor near the top (line 1) | |
| 129 | - | |
| 130 | - //@ts-ignore | |
| 131 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 132 | - helper, | |
| 133 | - "tokenizer", | |
| 134 | - ); | |
| 135 | - | |
| 136 | - // Should include more lines below since it can't expand much above | |
| 137 | - expect(result.editableRegionStartLine).toBe(0); | |
| 138 | - // Should include many more lines below to reach token limit | |
| 139 | - expect(result.editableRegionEndLine).toBeGreaterThan(10); | |
| 140 | - }); | |
| 141 | - | |
| 142 | - it("should handle files with varying line lengths", () => { | |
| 143 | - // Create content with varying line lengths | |
| 144 | - const fileContents = [ | |
| 145 | - "Short line", // 10 chars | |
| 146 | - "A".repeat(100), // 100 chars | |
| 147 | - "Medium length line here", // 24 chars | |
| 148 | - "B".repeat(200), // 200 chars | |
| 149 | - "Another typical line of code", // 28 chars | |
| 150 | - ].join("\n"); | |
| 151 | - | |
| 152 | - const helper = createMockHelper(fileContents, 2); // Cursor on the medium line | |
| 153 | - | |
| 154 | - //@ts-ignore | |
| 155 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 156 | - helper, | |
| 157 | - "tokenizer", | |
| 158 | - ); | |
| 159 | - | |
| 160 | - // Should include all lines since total tokens < 500 | |
| 161 | - expect(result.editableRegionStartLine).toBe(0); | |
| 162 | - expect(result.editableRegionEndLine).toBe(4); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should respect the token limit and not include too many lines", () => { | |
| 166 | - // Create content with many small lines (10 chars each) | |
| 167 | - const lines = Array(600).fill("C".repeat(10)).join("\n"); | |
| 168 | - const helper = createMockHelper(lines, 300); // Cursor in the middle | |
| 169 | - | |
| 170 | - //@ts-ignore | |
| 171 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 172 | - helper, | |
| 173 | - "tokenizer", | |
| 174 | - ); | |
| 175 | - | |
| 176 | - // Each line is 10 chars = 10 tokens per line with our mock. | |
| 177 | - // So with 500 token limit, we should get 50 lines total. | |
| 178 | - // 25 above, 25 below, +1 current | |
| 179 | - const totalLines = | |
| 180 | - result.editableRegionEndLine - result.editableRegionStartLine + 1; | |
| 181 | - expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line) | |
| 182 | - }); | |
| 183 | - | |
| 184 | - it("should use character approximation when using fourChars heuristic", () => { | |
| 185 | - // In this test, we're setting up a situation where tiktoken and fourChars would give different results | |
| 186 | - // Creating 5 lines, each 100 characters | |
| 187 | - const lines = Array(10).fill("D".repeat(100)).join("\n"); | |
| 188 | - const helper = createMockHelper(lines, 2); // Cursor in the middle | |
| 189 | - | |
| 190 | - // Mock for tiktoken counting (1 char = 1 token) | |
| 191 | - //@ts-ignore | |
| 192 | - const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion( | |
| 193 | - helper, | |
| 194 | - "tokenizer", | |
| 195 | - ); | |
| 196 | - | |
| 197 | - // Mock for fourChars counting (1 token = 4 chars) | |
| 198 | - // This should include more lines since each line is counted as 25 tokens instead of 100 | |
| 199 | - //@ts-ignore | |
| 200 | - const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion( | |
| 201 | - helper, | |
| 202 | - "fourChars", | |
| 203 | - ); | |
| 204 | - | |
| 205 | - // The fourChars approach should include more lines since it estimates fewer tokens per line | |
| 206 | - expect( | |
| 207 | - fourCharsResult.editableRegionEndLine - | |
| 208 | - fourCharsResult.editableRegionStartLine, | |
| 209 | - ).toBeGreaterThan( | |
| 210 | - tokenizerResult.editableRegionEndLine - | |
| 211 | - tokenizerResult.editableRegionStartLine, | |
| 212 | - ); | |
| 213 | - }); | |
| 214 | - | |
| 215 | - it("should include the entire file if it's within token limit", () => { | |
| 216 | - // Create a small file | |
| 217 | - const smallFile = "Small file\nwith just\na few lines\nof text"; | |
| 218 | - const helper = createMockHelper(smallFile, 1); | |
| 219 | - | |
| 220 | - //@ts-ignore | |
| 221 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 222 | - helper, | |
| 223 | - "tokenizer", | |
| 224 | - ); | |
| 225 | - | |
| 226 | - // Should include all lines | |
| 227 | - expect(result.editableRegionStartLine).toBe(0); | |
| 228 | - expect(result.editableRegionEndLine).toBe(3); | |
| 229 | - }); | |
| 230 | - | |
| 231 | - it("should prioritize balanced context when token limit allows", () => { | |
| 232 | - // Create content with alternating long and short lines | |
| 233 | - const fileContents = [ | |
| 234 | - "Short", // 5 chars | |
| 235 | - "E".repeat(80), // 80 chars | |
| 236 | - "Also short", // 10 chars | |
| 237 | - "F".repeat(80), // 80 chars | |
| 238 | - "Another short one", // 17 chars | |
| 239 | - "G".repeat(80), // 80 chars | |
| 240 | - "Final short line", // 16 chars | |
| 241 | - ].join("\n"); | |
| 242 | - | |
| 243 | - const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3) | |
| 244 | - | |
| 245 | - //@ts-ignore | |
| 246 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 247 | - helper, | |
| 248 | - "tokenizer", | |
| 249 | - ); | |
| 250 | - | |
| 251 | - // Should try to include equal number of lines above and below cursor | |
| 252 | - const linesAbove = result.editableRegionStartLine; | |
| 253 | - const linesBelow = | |
| 254 | - helper.fileLines.length - 1 - result.editableRegionEndLine; | |
| 255 | - | |
| 256 | - // Difference between lines above and below should be minimal | |
| 257 | - expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1); | |
| 258 | - }); | |
| 259 | -}); |
added core/nextEdit/NextEditProviderFactory.ts +16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { NEXT_EDIT_MODELS } from "../llm/constants.js"; | |
| 2 | +import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js"; | |
| 3 | +import { InstinctProvider } from "./providers/InstinctNextEditProvider.js"; | |
| 4 | +import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js"; | |
| 5 | + | |
| 6 | +export class NextEditProviderFactory { | |
| 7 | + static createProvider(modelName: string): BaseNextEditModelProvider { | |
| 8 | + if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) { | |
| 9 | + return new MercuryCoderProvider(); | |
| 10 | + } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { | |
| 11 | + return new InstinctProvider(); | |
| 12 | + } else { | |
| 13 | + throw new Error(`Unsupported model: ${modelName}`); | |
| 14 | + } | |
| 15 | + } | |
| 16 | +} |
modified core/nextEdit/constants.ts +6 −4
| @@ -8,20 +8,22 @@ | ||
| 8 | 8 | NEXT_EDIT_MODELS, |
| 9 | 9 | { topMargin: number; bottomMargin: number } |
| 10 | 10 | > = { |
| 11 | - "mercury-coder-nextedit": { | |
| 11 | + "mercury-coder": { | |
| 12 | 12 | topMargin: 0, |
| 13 | 13 | bottomMargin: 5, |
| 14 | - }, // mercury coder nextedit uses full file diff, so this should be unnecessary | |
| 14 | + }, // mercury coder uses full file diff, so this should be unnecessary | |
| 15 | 15 | instinct: { topMargin: 1, bottomMargin: 5 }, |
| 16 | 16 | }; |
| 17 | 17 | |
| 18 | +export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; | |
| 19 | + | |
| 18 | 20 | // Model 1-specific tokens. |
| 19 | 21 | export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; |
| 20 | 22 | export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; |
| 21 | 23 | export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; |
| 22 | 24 | export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>"; |
| 23 | 25 | export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>"; |
| 24 | -export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. | |
| 26 | +export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI agent is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. | |
| 25 | 27 | |
| 26 | 28 | You have access to the following information to help you make informed suggestions: |
| 27 | 29 | |
| @@ -64,4 +66,4 @@ | ||
| 64 | 66 | export const MERCURY_EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>"; |
| 65 | 67 | export const MERCURY_CURSOR = "<|cursor|>"; |
| 66 | 68 | export const MERCURY_SYSTEM_PROMPT = |
| 67 | - "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response."; | |
| 69 | + "You are Mercury, created by Inception Labs. You are an AI Agent and an expert at coding. Your role as an AI agent is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'''s possible these are entirely irrelevant to the developer'''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'''s intentions. These changes are listed from oldest to latest. It'''s possible a lot of old edit diff history is entirely irrelevant to the developer'''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'''s last change unless there are obvious typos or errors.\n- Don'''t include the line numbers of the form #| in your response."; |
modified core/nextEdit/context/autocompleteContextFetching.ts +5 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | } from "../../autocomplete/util/types"; |
| 12 | 12 | import { ConfigHandler } from "../../config/ConfigHandler"; |
| 13 | 13 | import { IDE, ILLM } from "../../index"; |
| 14 | +import { isSecurityConcern } from "../../indexing/ignore"; | |
| 14 | 15 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters"; |
| 15 | 16 | |
| 16 | 17 | /** |
| @@ -61,6 +62,10 @@ | ||
| 61 | 62 | throw new Error("No config available"); |
| 62 | 63 | } |
| 63 | 64 | |
| 65 | + if (isSecurityConcern(input.filepath)) { | |
| 66 | + throw new Error("File is a security concern, autocomplete disabled"); | |
| 67 | + } | |
| 68 | + | |
| 64 | 69 | // Use provided autocomplete model or fall back to configured autocomplete model |
| 65 | 70 | let finalModel: ILLM; |
| 66 | 71 | let modelNameForTemplating: string; |
added core/nextEdit/providers/BaseNextEditProvider.ts +420 −0
| @@ -0,0 +1,420 @@ | ||
| 1 | +import * as path from "path"; | |
| 2 | +import { v4 as uuidv4 } from "uuid"; | |
| 3 | + | |
| 4 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 5 | +import { myersDiff } from "../../diff/myers.js"; | |
| 6 | +import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js"; | |
| 7 | +import { countTokens } from "../../llm/countTokens.js"; | |
| 8 | +import { | |
| 9 | + calculateFinalCursorPosition, | |
| 10 | + DiffGroup, | |
| 11 | + groupDiffLines, | |
| 12 | +} from "../diff/diff.js"; | |
| 13 | +import { PrefetchQueue } from "../NextEditPrefetchQueue.js"; | |
| 14 | +import { | |
| 15 | + ModelSpecificContext, | |
| 16 | + NextEditOutcome, | |
| 17 | + Prompt, | |
| 18 | + PromptMetadata, | |
| 19 | +} from "../types.js"; | |
| 20 | +import { isWhitespaceOnlyDeletion } from "../utils.js"; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * This class is used as an abstract base class for model-specific providers. | |
| 24 | + * This and its children are responsible for pre/post processing of prompts and outcomes. | |
| 25 | + * Different next edit models have very different requirements. | |
| 26 | + */ | |
| 27 | +export abstract class BaseNextEditModelProvider { | |
| 28 | + protected readonly modelName: string; | |
| 29 | + | |
| 30 | + constructor(modelName: string) { | |
| 31 | + this.modelName = modelName; | |
| 32 | + } | |
| 33 | + | |
| 34 | + // Leave methods as abstract when you must have the models implement their own versions. | |
| 35 | + abstract getSystemPrompt(): string; | |
| 36 | + abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>; | |
| 37 | + abstract extractCompletion(message: string): string; | |
| 38 | + abstract buildPromptContext(context: ModelSpecificContext): any; | |
| 39 | + abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata; | |
| 40 | + abstract getWindowSize(): { topMargin: number; bottomMargin: number }; | |
| 41 | + abstract calculateEditableRegion( | |
| 42 | + helper: HelperVars, | |
| 43 | + usingFullFileDiff: boolean, | |
| 44 | + ): { | |
| 45 | + editableRegionStartLine: number; | |
| 46 | + editableRegionEndLine: number; | |
| 47 | + }; | |
| 48 | + | |
| 49 | + // Methods that can be used as default fallback. | |
| 50 | + public async handlePartialFileDiff( | |
| 51 | + helper: HelperVars, | |
| 52 | + editableRegionStartLine: number, | |
| 53 | + editableRegionEndLine: number, | |
| 54 | + startTime: number, | |
| 55 | + llm: ILLM, | |
| 56 | + nextCompletion: string, | |
| 57 | + promptMetadata: PromptMetadata, | |
| 58 | + ide: IDE, | |
| 59 | + ): Promise<NextEditOutcome> { | |
| 60 | + const oldEditRangeSlice = helper.fileContents | |
| 61 | + .split("\n") | |
| 62 | + .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 63 | + .join("\n"); | |
| 64 | + | |
| 65 | + const finalCursorPos = calculateFinalCursorPosition( | |
| 66 | + helper.pos, | |
| 67 | + editableRegionStartLine, | |
| 68 | + oldEditRangeSlice, | |
| 69 | + nextCompletion, | |
| 70 | + ); | |
| 71 | + | |
| 72 | + const outcome = await this.createNextEditOutcome({ | |
| 73 | + helper, | |
| 74 | + startTime, | |
| 75 | + llm, | |
| 76 | + promptContent: promptMetadata.prompt.content, | |
| 77 | + completion: nextCompletion, | |
| 78 | + finalCursorPosition: finalCursorPos, | |
| 79 | + editableRegionStartLine, | |
| 80 | + editableRegionEndLine, | |
| 81 | + userEdits: promptMetadata.userEdits, | |
| 82 | + userExcerpts: promptMetadata.userExcerpts, | |
| 83 | + originalEditableRange: oldEditRangeSlice, | |
| 84 | + diffLines: [], | |
| 85 | + ide, | |
| 86 | + }); | |
| 87 | + | |
| 88 | + return outcome; | |
| 89 | + } | |
| 90 | + | |
| 91 | + public async handleFullFileDiff( | |
| 92 | + helper: HelperVars, | |
| 93 | + editableRegionStartLine: number, | |
| 94 | + editableRegionEndLine: number, | |
| 95 | + startTime: number, | |
| 96 | + llm: ILLM, | |
| 97 | + nextCompletion: string, | |
| 98 | + promptMetadata: PromptMetadata, | |
| 99 | + ide: IDE, | |
| 100 | + ): Promise<NextEditOutcome | undefined> { | |
| 101 | + const fileSlice = helper.fileLines | |
| 102 | + .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 103 | + .join("\n"); | |
| 104 | + | |
| 105 | + const diffLines = myersDiff(fileSlice, nextCompletion); | |
| 106 | + const diffGroups = groupDiffLines( | |
| 107 | + diffLines, | |
| 108 | + editableRegionStartLine, | |
| 109 | + 5, | |
| 110 | + ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); | |
| 111 | + const currentLine = helper.pos.line; | |
| 112 | + const prefetchQueue = PrefetchQueue.getInstance(); | |
| 113 | + | |
| 114 | + const cursorLocalDiffGroup = await this.processDiffGroups( | |
| 115 | + diffGroups, | |
| 116 | + currentLine, | |
| 117 | + helper, | |
| 118 | + startTime, | |
| 119 | + llm, | |
| 120 | + prefetchQueue, | |
| 121 | + promptMetadata, | |
| 122 | + ide, | |
| 123 | + ); | |
| 124 | + | |
| 125 | + if (cursorLocalDiffGroup) { | |
| 126 | + return await this.createOutcomeFromDiffGroup( | |
| 127 | + cursorLocalDiffGroup, | |
| 128 | + helper, | |
| 129 | + startTime, | |
| 130 | + llm, | |
| 131 | + helper.input.completionId, | |
| 132 | + true, | |
| 133 | + promptMetadata, | |
| 134 | + ide, | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + | |
| 138 | + return undefined; | |
| 139 | + } | |
| 140 | + | |
| 141 | + /** | |
| 142 | + * Process diff groups and find the one containing the cursor. | |
| 143 | + */ | |
| 144 | + private async processDiffGroups( | |
| 145 | + diffGroups: DiffGroup[], | |
| 146 | + currentLine: number, | |
| 147 | + helper: HelperVars, | |
| 148 | + startTime: number, | |
| 149 | + llm: ILLM, | |
| 150 | + prefetchQueue: PrefetchQueue, | |
| 151 | + promptMetadata: PromptMetadata, | |
| 152 | + ide: IDE, | |
| 153 | + ): Promise<DiffGroup | undefined> { | |
| 154 | + let cursorGroup: DiffGroup | undefined; | |
| 155 | + | |
| 156 | + for (const group of diffGroups) { | |
| 157 | + if (currentLine >= group.startLine && currentLine <= group.endLine) { | |
| 158 | + cursorGroup = group; | |
| 159 | + } else { | |
| 160 | + await this.addDiffGroupToPrefetchQueue( | |
| 161 | + group, | |
| 162 | + helper, | |
| 163 | + startTime, | |
| 164 | + llm, | |
| 165 | + prefetchQueue, | |
| 166 | + promptMetadata, | |
| 167 | + ide, | |
| 168 | + ); | |
| 169 | + } | |
| 170 | + } | |
| 171 | + | |
| 172 | + return cursorGroup; | |
| 173 | + } | |
| 174 | + | |
| 175 | + private async addDiffGroupToPrefetchQueue( | |
| 176 | + group: DiffGroup, | |
| 177 | + helper: HelperVars, | |
| 178 | + startTime: number, | |
| 179 | + llm: ILLM, | |
| 180 | + prefetchQueue: PrefetchQueue, | |
| 181 | + promptMetadata: PromptMetadata, | |
| 182 | + ide: IDE, | |
| 183 | + ): Promise<void> { | |
| 184 | + // Extract lines that are not old. | |
| 185 | + const groupContent = group.lines | |
| 186 | + .filter((l) => l.type !== "old") | |
| 187 | + .map((l) => l.line) | |
| 188 | + .join("\n"); | |
| 189 | + | |
| 190 | + const rangeInFile: RangeInFile = { | |
| 191 | + filepath: helper.filepath, | |
| 192 | + range: { | |
| 193 | + start: { line: group.startLine, character: 0 }, | |
| 194 | + end: { | |
| 195 | + line: group.endLine, | |
| 196 | + character: group.lines[group.lines.length - 1].line.length, | |
| 197 | + }, | |
| 198 | + }, | |
| 199 | + }; | |
| 200 | + | |
| 201 | + // Extract lines that are not new. | |
| 202 | + const originalContent = group.lines | |
| 203 | + .filter((l) => l.type !== "new") | |
| 204 | + .map((l) => l.line) | |
| 205 | + .join("\n"); | |
| 206 | + | |
| 207 | + const groupOutcome = await this.createNextEditOutcome({ | |
| 208 | + helper, | |
| 209 | + startTime, | |
| 210 | + llm, | |
| 211 | + promptContent: promptMetadata.prompt.content, | |
| 212 | + completion: groupContent, | |
| 213 | + finalCursorPosition: { | |
| 214 | + line: group.endLine, | |
| 215 | + character: group.lines[group.lines.length - 1].line.length, | |
| 216 | + }, | |
| 217 | + editableRegionStartLine: group.startLine, | |
| 218 | + editableRegionEndLine: group.endLine, | |
| 219 | + userEdits: promptMetadata.userEdits, | |
| 220 | + userExcerpts: promptMetadata.userExcerpts, | |
| 221 | + originalEditableRange: originalContent, | |
| 222 | + cursorPosition: { line: group.startLine, character: 0 }, | |
| 223 | + completionId: uuidv4(), // Generate a new ID for this prefetched item. | |
| 224 | + diffLines: group.lines, | |
| 225 | + ide, | |
| 226 | + }); | |
| 227 | + | |
| 228 | + prefetchQueue.enqueueProcessed({ | |
| 229 | + location: rangeInFile, | |
| 230 | + outcome: groupOutcome, | |
| 231 | + }); | |
| 232 | + } | |
| 233 | + | |
| 234 | + private async createOutcomeFromDiffGroup( | |
| 235 | + diffGroup: DiffGroup, | |
| 236 | + helper: HelperVars, | |
| 237 | + startTime: number, | |
| 238 | + llm: ILLM, | |
| 239 | + completionId: string, | |
| 240 | + isCurrentCursorGroup: boolean, | |
| 241 | + promptMetadata: PromptMetadata, | |
| 242 | + ide: IDE, | |
| 243 | + ): Promise<NextEditOutcome> { | |
| 244 | + const groupContent = diffGroup.lines | |
| 245 | + .filter((l) => l.type !== "old") | |
| 246 | + .map((l) => l.line) | |
| 247 | + .join("\n"); | |
| 248 | + | |
| 249 | + const originalContent = diffGroup.lines | |
| 250 | + .filter((l) => l.type !== "new") | |
| 251 | + .map((l) => l.line) | |
| 252 | + .join("\n"); | |
| 253 | + | |
| 254 | + const cursorPos = isCurrentCursorGroup | |
| 255 | + ? helper.pos | |
| 256 | + : { line: diffGroup.startLine, character: 0 }; | |
| 257 | + | |
| 258 | + const finalCursorPos = calculateFinalCursorPosition( | |
| 259 | + cursorPos, | |
| 260 | + diffGroup.startLine, | |
| 261 | + originalContent, | |
| 262 | + groupContent, | |
| 263 | + ); | |
| 264 | + | |
| 265 | + const outcomeNext = await this.createNextEditOutcome({ | |
| 266 | + helper, | |
| 267 | + startTime, | |
| 268 | + llm, | |
| 269 | + promptContent: promptMetadata.prompt.content, | |
| 270 | + completion: groupContent, | |
| 271 | + finalCursorPosition: finalCursorPos, | |
| 272 | + editableRegionStartLine: diffGroup.startLine, | |
| 273 | + editableRegionEndLine: diffGroup.endLine, | |
| 274 | + userEdits: promptMetadata.userEdits, | |
| 275 | + userExcerpts: promptMetadata.userExcerpts, | |
| 276 | + originalEditableRange: originalContent, | |
| 277 | + cursorPosition: cursorPos, | |
| 278 | + completionId, | |
| 279 | + diffLines: diffGroup.lines, | |
| 280 | + ide, | |
| 281 | + }); | |
| 282 | + | |
| 283 | + return outcomeNext; | |
| 284 | + } | |
| 285 | + | |
| 286 | + protected async createNextEditOutcome(outcomeCtx: { | |
| 287 | + helper: HelperVars; | |
| 288 | + startTime: number; | |
| 289 | + llm: ILLM; | |
| 290 | + promptContent: string; | |
| 291 | + completion: string; | |
| 292 | + finalCursorPosition: Position; | |
| 293 | + editableRegionStartLine: number; | |
| 294 | + editableRegionEndLine: number; | |
| 295 | + userEdits: string; | |
| 296 | + userExcerpts: string; | |
| 297 | + originalEditableRange: string; | |
| 298 | + cursorPosition?: Position; | |
| 299 | + completionId?: string; | |
| 300 | + diffLines: DiffLine[]; | |
| 301 | + ide: IDE; | |
| 302 | + }): Promise<NextEditOutcome> { | |
| 303 | + return { | |
| 304 | + elapsed: Date.now() - outcomeCtx.startTime, | |
| 305 | + modelProvider: outcomeCtx.llm.underlyingProviderName, | |
| 306 | + modelName: outcomeCtx.llm.model, | |
| 307 | + completionOptions: null, | |
| 308 | + completionId: | |
| 309 | + outcomeCtx.completionId || outcomeCtx.helper.input.completionId, | |
| 310 | + gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), | |
| 311 | + uniqueId: await outcomeCtx.ide.getUniqueId(), | |
| 312 | + timestamp: Date.now(), | |
| 313 | + fileUri: outcomeCtx.helper.filepath, | |
| 314 | + workspaceDirUri: | |
| 315 | + outcomeCtx.helper.workspaceUris[0] ?? | |
| 316 | + path.dirname(outcomeCtx.helper.filepath), | |
| 317 | + prompt: outcomeCtx.promptContent, | |
| 318 | + userEdits: outcomeCtx.userEdits ?? "", | |
| 319 | + userExcerpts: outcomeCtx.userExcerpts ?? "", | |
| 320 | + originalEditableRange: outcomeCtx.originalEditableRange ?? "", | |
| 321 | + completion: outcomeCtx.completion, | |
| 322 | + cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, | |
| 323 | + finalCursorPosition: outcomeCtx.finalCursorPosition, | |
| 324 | + editableRegionStartLine: outcomeCtx.editableRegionStartLine, | |
| 325 | + editableRegionEndLine: outcomeCtx.editableRegionEndLine, | |
| 326 | + diffLines: outcomeCtx.diffLines, | |
| 327 | + ...outcomeCtx.helper.options, | |
| 328 | + }; | |
| 329 | + } | |
| 330 | + | |
| 331 | + // Shared utility for calculating editable regions. | |
| 332 | + protected calculateOptimalEditableRegion( | |
| 333 | + helper: HelperVars, | |
| 334 | + maxTokens: number = 512, | |
| 335 | + heuristic: "fourChars" | "tokenizer" = "tokenizer", | |
| 336 | + ): { | |
| 337 | + editableRegionStartLine: number; | |
| 338 | + editableRegionEndLine: number; | |
| 339 | + } { | |
| 340 | + const cursorLine = helper.pos.line; | |
| 341 | + const fileLines = helper.fileLines; | |
| 342 | + | |
| 343 | + let editableRegionStartLine = cursorLine; | |
| 344 | + let editableRegionEndLine = cursorLine; | |
| 345 | + | |
| 346 | + let currentContent = fileLines[cursorLine]; | |
| 347 | + let totalTokens = | |
| 348 | + heuristic === "tokenizer" | |
| 349 | + ? countTokens(currentContent, helper.modelName) | |
| 350 | + : Math.ceil(currentContent.length / 4); | |
| 351 | + | |
| 352 | + let addingAbove = true; | |
| 353 | + | |
| 354 | + while (totalTokens < maxTokens) { | |
| 355 | + let addedLine = false; | |
| 356 | + | |
| 357 | + if (addingAbove) { | |
| 358 | + if (editableRegionStartLine > 0) { | |
| 359 | + editableRegionStartLine--; | |
| 360 | + const lineContent = fileLines[editableRegionStartLine]; | |
| 361 | + const lineTokens = | |
| 362 | + heuristic === "tokenizer" | |
| 363 | + ? countTokens(lineContent, helper.modelName) | |
| 364 | + : Math.ceil(lineContent.length / 4); | |
| 365 | + | |
| 366 | + totalTokens += lineTokens; | |
| 367 | + addedLine = true; | |
| 368 | + } | |
| 369 | + } else { | |
| 370 | + if (editableRegionEndLine < fileLines.length - 1) { | |
| 371 | + editableRegionEndLine++; | |
| 372 | + const lineContent = fileLines[editableRegionEndLine]; | |
| 373 | + const lineTokens = | |
| 374 | + heuristic === "tokenizer" | |
| 375 | + ? countTokens(lineContent, helper.modelName) | |
| 376 | + : Math.ceil(lineContent.length / 4); | |
| 377 | + | |
| 378 | + totalTokens += lineTokens; | |
| 379 | + addedLine = true; | |
| 380 | + } | |
| 381 | + } | |
| 382 | + | |
| 383 | + if (!addedLine) { | |
| 384 | + if ( | |
| 385 | + editableRegionStartLine === 0 && | |
| 386 | + editableRegionEndLine === fileLines.length - 1 | |
| 387 | + ) { | |
| 388 | + break; | |
| 389 | + } | |
| 390 | + addingAbove = !addingAbove; | |
| 391 | + continue; | |
| 392 | + } | |
| 393 | + | |
| 394 | + if (totalTokens > maxTokens) { | |
| 395 | + if (addingAbove) { | |
| 396 | + editableRegionStartLine++; | |
| 397 | + } else { | |
| 398 | + editableRegionEndLine--; | |
| 399 | + } | |
| 400 | + break; | |
| 401 | + } | |
| 402 | + | |
| 403 | + addingAbove = !addingAbove; | |
| 404 | + } | |
| 405 | + | |
| 406 | + return { | |
| 407 | + editableRegionStartLine, | |
| 408 | + editableRegionEndLine, | |
| 409 | + }; | |
| 410 | + } | |
| 411 | + | |
| 412 | + // Optional methods with defaults. | |
| 413 | + shouldInjectUniqueToken(): boolean { | |
| 414 | + return false; | |
| 415 | + } | |
| 416 | + | |
| 417 | + getUniqueToken(): string | null { | |
| 418 | + return null; | |
| 419 | + } | |
| 420 | +} |
added core/nextEdit/providers/InstinctNextEditProvider.ts +155 −0
| @@ -0,0 +1,155 @@ | ||
| 1 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 2 | +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; | |
| 3 | +import { INSTINCT_SYSTEM_PROMPT } from "../constants.js"; | |
| 4 | +import { | |
| 5 | + contextSnippetsBlock, | |
| 6 | + currentFileContentBlock, | |
| 7 | + editHistoryBlock, | |
| 8 | +} from "../templating/instinct.js"; | |
| 9 | +import { | |
| 10 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 11 | + PromptTemplateRenderer, | |
| 12 | +} from "../templating/NextEditPromptEngine.js"; | |
| 13 | +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; | |
| 14 | +import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js"; | |
| 15 | + | |
| 16 | +export class InstinctProvider extends BaseNextEditModelProvider { | |
| 17 | + private templateRenderer: PromptTemplateRenderer; | |
| 18 | + | |
| 19 | + constructor() { | |
| 20 | + super(NEXT_EDIT_MODELS.INSTINCT); | |
| 21 | + | |
| 22 | + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT]; | |
| 23 | + this.templateRenderer = new PromptTemplateRenderer(template.template); | |
| 24 | + } | |
| 25 | + | |
| 26 | + getSystemPrompt(): string { | |
| 27 | + return INSTINCT_SYSTEM_PROMPT; | |
| 28 | + } | |
| 29 | + | |
| 30 | + getWindowSize() { | |
| 31 | + return { topMargin: 1, bottomMargin: 5 }; | |
| 32 | + } | |
| 33 | + | |
| 34 | + shouldInjectUniqueToken(): boolean { | |
| 35 | + return false; // Instinct doesn't use unique tokens. | |
| 36 | + } | |
| 37 | + | |
| 38 | + extractCompletion(message: string): string { | |
| 39 | + return message; // Instinct returns the completion directly. | |
| 40 | + } | |
| 41 | + | |
| 42 | + buildPromptContext(context: ModelSpecificContext): any { | |
| 43 | + // Calculate the window around the cursor position (25 lines above and below). | |
| 44 | + const windowStart = Math.max(0, context.helper.pos.line - 25); | |
| 45 | + const windowEnd = Math.min( | |
| 46 | + context.helper.fileLines.length - 1, | |
| 47 | + context.helper.pos.line + 25, | |
| 48 | + ); | |
| 49 | + | |
| 50 | + // Ensure editable region boundaries are within the window. | |
| 51 | + const adjustedEditableStart = Math.max( | |
| 52 | + windowStart, | |
| 53 | + context.editableRegionStartLine, | |
| 54 | + ); | |
| 55 | + const adjustedEditableEnd = Math.min( | |
| 56 | + windowEnd, | |
| 57 | + context.editableRegionEndLine, | |
| 58 | + ); | |
| 59 | + | |
| 60 | + return { | |
| 61 | + contextSnippets: context.autocompleteContext, | |
| 62 | + currentFileContent: context.helper.fileContents, | |
| 63 | + windowStart, | |
| 64 | + windowEnd, | |
| 65 | + editableRegionStartLine: adjustedEditableStart, | |
| 66 | + editableRegionEndLine: adjustedEditableEnd, | |
| 67 | + editDiffHistory: context.diffContext, | |
| 68 | + currentFilePath: context.helper.filepath, | |
| 69 | + languageShorthand: context.helper.lang.name, | |
| 70 | + }; | |
| 71 | + } | |
| 72 | + | |
| 73 | + async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> { | |
| 74 | + const promptCtx = this.buildPromptContext(context); | |
| 75 | + | |
| 76 | + const templateVars = { | |
| 77 | + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), | |
| 78 | + currentFileContent: currentFileContentBlock( | |
| 79 | + promptCtx.currentFileContent, | |
| 80 | + promptCtx.windowStart, | |
| 81 | + promptCtx.windowEnd, | |
| 82 | + promptCtx.editableRegionStartLine, | |
| 83 | + promptCtx.editableRegionEndLine, | |
| 84 | + context.helper.pos, | |
| 85 | + ), | |
| 86 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 87 | + currentFilePath: promptCtx.currentFilePath, | |
| 88 | + languageShorthand: promptCtx.languageShorthand, | |
| 89 | + }; | |
| 90 | + | |
| 91 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 92 | + | |
| 93 | + return [ | |
| 94 | + { | |
| 95 | + role: "system", | |
| 96 | + content: this.getSystemPrompt(), | |
| 97 | + }, | |
| 98 | + { | |
| 99 | + role: "user", | |
| 100 | + content: userPromptContent, | |
| 101 | + }, | |
| 102 | + ]; | |
| 103 | + } | |
| 104 | + | |
| 105 | + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { | |
| 106 | + const promptCtx = this.buildPromptContext(context); | |
| 107 | + | |
| 108 | + const templateVars = { | |
| 109 | + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), | |
| 110 | + currentFileContent: currentFileContentBlock( | |
| 111 | + promptCtx.currentFileContent, | |
| 112 | + promptCtx.windowStart, | |
| 113 | + promptCtx.windowEnd, | |
| 114 | + promptCtx.editableRegionStartLine, | |
| 115 | + promptCtx.editableRegionEndLine, | |
| 116 | + context.helper.pos, | |
| 117 | + ), | |
| 118 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 119 | + currentFilePath: promptCtx.currentFilePath, | |
| 120 | + languageShorthand: promptCtx.languageShorthand, | |
| 121 | + }; | |
| 122 | + | |
| 123 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 124 | + | |
| 125 | + return { | |
| 126 | + prompt: { | |
| 127 | + role: "user", | |
| 128 | + content: userPromptContent, | |
| 129 | + }, | |
| 130 | + userEdits: promptCtx.editDiffHistory.join("\n"), | |
| 131 | + userExcerpts: templateVars.currentFileContent, | |
| 132 | + }; | |
| 133 | + } | |
| 134 | + | |
| 135 | + calculateEditableRegion( | |
| 136 | + helper: HelperVars, | |
| 137 | + usingFullFileDiff: boolean, | |
| 138 | + ): { | |
| 139 | + editableRegionStartLine: number; | |
| 140 | + editableRegionEndLine: number; | |
| 141 | + } { | |
| 142 | + if (usingFullFileDiff) { | |
| 143 | + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); | |
| 144 | + } else { | |
| 145 | + const { topMargin, bottomMargin } = this.getWindowSize(); | |
| 146 | + return { | |
| 147 | + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), | |
| 148 | + editableRegionEndLine: Math.min( | |
| 149 | + helper.pos.line + bottomMargin, | |
| 150 | + helper.fileLines.length - 1, | |
| 151 | + ), | |
| 152 | + }; | |
| 153 | + } | |
| 154 | + } | |
| 155 | +} |
added core/nextEdit/providers/MercuryCoderNextEditProvider.ts +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 2 | +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; | |
| 3 | +import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js"; | |
| 4 | +import { | |
| 5 | + currentFileContentBlock, | |
| 6 | + editHistoryBlock, | |
| 7 | + recentlyViewedCodeSnippetsBlock, | |
| 8 | +} from "../templating/mercuryCoderNextEdit.js"; | |
| 9 | +import { | |
| 10 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 11 | + PromptTemplateRenderer, | |
| 12 | +} from "../templating/NextEditPromptEngine.js"; | |
| 13 | +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; | |
| 14 | +import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js"; | |
| 15 | + | |
| 16 | +export class MercuryCoderProvider extends BaseNextEditModelProvider { | |
| 17 | + private templateRenderer: PromptTemplateRenderer; | |
| 18 | + | |
| 19 | + constructor() { | |
| 20 | + super(NEXT_EDIT_MODELS.MERCURY_CODER); | |
| 21 | + | |
| 22 | + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER]; | |
| 23 | + this.templateRenderer = new PromptTemplateRenderer(template.template); | |
| 24 | + } | |
| 25 | + | |
| 26 | + getSystemPrompt(): string { | |
| 27 | + return MERCURY_SYSTEM_PROMPT; | |
| 28 | + } | |
| 29 | + | |
| 30 | + getWindowSize() { | |
| 31 | + return { topMargin: 0, bottomMargin: 5 }; | |
| 32 | + } | |
| 33 | + | |
| 34 | + shouldInjectUniqueToken(): boolean { | |
| 35 | + return true; | |
| 36 | + } | |
| 37 | + | |
| 38 | + getUniqueToken(): string { | |
| 39 | + return UNIQUE_TOKEN; | |
| 40 | + } | |
| 41 | + | |
| 42 | + extractCompletion(message: string): string { | |
| 43 | + // Extract the code between the markdown code blocks. | |
| 44 | + return message.slice( | |
| 45 | + message.indexOf("```\n") + "```\n".length, | |
| 46 | + message.lastIndexOf("\n\n```"), | |
| 47 | + ); | |
| 48 | + } | |
| 49 | + | |
| 50 | + buildPromptContext(context: ModelSpecificContext): any { | |
| 51 | + return { | |
| 52 | + recentlyViewedCodeSnippets: | |
| 53 | + context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ | |
| 54 | + filepath: snip.filepath, | |
| 55 | + content: snip.content, | |
| 56 | + })) ?? [], | |
| 57 | + currentFileContent: context.helper.fileContents, | |
| 58 | + editableRegionStartLine: context.editableRegionStartLine, | |
| 59 | + editableRegionEndLine: context.editableRegionEndLine, | |
| 60 | + editDiffHistory: context.diffContext, | |
| 61 | + currentFilePath: context.helper.filepath, | |
| 62 | + }; | |
| 63 | + } | |
| 64 | + | |
| 65 | + async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> { | |
| 66 | + const promptCtx = this.buildPromptContext(context); | |
| 67 | + | |
| 68 | + const templateVars = { | |
| 69 | + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 70 | + promptCtx.recentlyViewedCodeSnippets, | |
| 71 | + ), | |
| 72 | + currentFileContent: currentFileContentBlock( | |
| 73 | + promptCtx.currentFileContent, | |
| 74 | + promptCtx.editableRegionStartLine, | |
| 75 | + promptCtx.editableRegionEndLine, | |
| 76 | + context.helper.pos, | |
| 77 | + ), | |
| 78 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 79 | + currentFilePath: promptCtx.currentFilePath, | |
| 80 | + }; | |
| 81 | + | |
| 82 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 83 | + | |
| 84 | + return [ | |
| 85 | + { | |
| 86 | + role: "system", | |
| 87 | + content: this.getSystemPrompt(), | |
| 88 | + }, | |
| 89 | + { | |
| 90 | + role: "user", | |
| 91 | + content: userPromptContent, | |
| 92 | + }, | |
| 93 | + ]; | |
| 94 | + } | |
| 95 | + | |
| 96 | + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { | |
| 97 | + const promptCtx = this.buildPromptContext(context); | |
| 98 | + | |
| 99 | + const templateVars = { | |
| 100 | + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 101 | + promptCtx.recentlyViewedCodeSnippets, | |
| 102 | + ), | |
| 103 | + currentFileContent: currentFileContentBlock( | |
| 104 | + promptCtx.currentFileContent, | |
| 105 | + promptCtx.editableRegionStartLine, | |
| 106 | + promptCtx.editableRegionEndLine, | |
| 107 | + context.helper.pos, | |
| 108 | + ), | |
| 109 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 110 | + currentFilePath: promptCtx.currentFilePath, | |
| 111 | + }; | |
| 112 | + | |
| 113 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 114 | + | |
| 115 | + return { | |
| 116 | + prompt: { | |
| 117 | + role: "user", | |
| 118 | + content: userPromptContent, | |
| 119 | + }, | |
| 120 | + userEdits: promptCtx.editDiffHistory.join("\n"), | |
| 121 | + userExcerpts: templateVars.currentFileContent, | |
| 122 | + }; | |
| 123 | + } | |
| 124 | + | |
| 125 | + calculateEditableRegion( | |
| 126 | + helper: HelperVars, | |
| 127 | + usingFullFileDiff: boolean, | |
| 128 | + ): { | |
| 129 | + editableRegionStartLine: number; | |
| 130 | + editableRegionEndLine: number; | |
| 131 | + } { | |
| 132 | + if (usingFullFileDiff) { | |
| 133 | + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); | |
| 134 | + } else { | |
| 135 | + const { topMargin, bottomMargin } = this.getWindowSize(); | |
| 136 | + return { | |
| 137 | + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), | |
| 138 | + editableRegionEndLine: Math.min( | |
| 139 | + helper.pos.line + bottomMargin, | |
| 140 | + helper.fileLines.length - 1, | |
| 141 | + ), | |
| 142 | + }; | |
| 143 | + } | |
| 144 | + } | |
| 145 | +} |
modified core/nextEdit/templating/NextEditPromptEngine.ts +24 −230
| @@ -1,7 +1,4 @@ | ||
| 1 | 1 | import Handlebars from "handlebars"; |
| 2 | -import { Position } from "../.."; | |
| 3 | -import { SnippetPayload } from "../../autocomplete/snippets"; | |
| 4 | -import { HelperVars } from "../../autocomplete/util/HelperVars"; | |
| 5 | 2 | import { NEXT_EDIT_MODELS } from "../../llm/constants"; |
| 6 | 3 | import { |
| 7 | 4 | INSTINCT_USER_PROMPT_PREFIX, |
| @@ -12,242 +9,39 @@ | ||
| 12 | 9 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, |
| 13 | 10 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, |
| 14 | 11 | } from "../constants"; |
| 15 | -import { | |
| 16 | - InstinctTemplateVars, | |
| 17 | - MercuryTemplateVars, | |
| 18 | - NextEditTemplate, | |
| 19 | - PromptMetadata, | |
| 20 | - SystemPrompt, | |
| 21 | - TemplateVars, | |
| 22 | - UserPrompt, | |
| 23 | -} from "../types"; | |
| 24 | -import { | |
| 25 | - contextSnippetsBlock, | |
| 26 | - currentFileContentBlock as instinctCurrentFileContentBlock, | |
| 27 | - editHistoryBlock as instinctEditHistoryBlock, | |
| 28 | -} from "./instinct"; | |
| 29 | -import { | |
| 30 | - currentFileContentBlock, | |
| 31 | - editHistoryBlock, | |
| 32 | - recentlyViewedCodeSnippetsBlock, | |
| 33 | -} from "./mercuryCoderNextEdit"; | |
| 34 | -import { | |
| 35 | - insertCursorToken, | |
| 36 | - insertEditableRegionTokensWithStaticRange, | |
| 37 | -} from "./utils"; | |
| 38 | - | |
| 39 | -type TemplateRenderer = (vars: TemplateVars) => string; | |
| 40 | - | |
| 41 | -const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = { | |
| 42 | - "mercury-coder-nextedit": { | |
| 43 | - template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, | |
| 12 | +import { NextEditTemplate, TemplateVars } from "../types"; | |
| 13 | + | |
| 14 | +// Keep the template registry | |
| 15 | +export const NEXT_EDIT_MODEL_TEMPLATES: Record< | |
| 16 | + NEXT_EDIT_MODELS, | |
| 17 | + NextEditTemplate | |
| 18 | +> = { | |
| 19 | + "mercury-coder": { | |
| 20 | + template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, | |
| 44 | 21 | }, |
| 45 | 22 | instinct: { |
| 46 | - template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, | |
| 23 | + template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, | |
| 47 | 24 | }, |
| 48 | 25 | }; |
| 49 | 26 | |
| 50 | -function templateRendererOfModel( | |
| 51 | - modelName: NEXT_EDIT_MODELS, | |
| 52 | -): TemplateRenderer { | |
| 53 | - let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; | |
| 54 | - if (!template) { | |
| 55 | - throw new Error(`Model ${modelName} is not supported for next edit.`); | |
| 56 | - } | |
| 57 | - | |
| 58 | - const compiledTemplate = Handlebars.compile(template.template); | |
| 59 | - | |
| 60 | - return (vars: TemplateVars): string => { | |
| 61 | - return compiledTemplate(vars); | |
| 62 | - }; | |
| 63 | -} | |
| 64 | - | |
| 65 | -export async function renderPrompt( | |
| 66 | - helper: HelperVars, | |
| 67 | - ctx: any, | |
| 68 | -): Promise<PromptMetadata> { | |
| 69 | - let modelName = helper.modelName as NEXT_EDIT_MODELS; | |
| 70 | - | |
| 71 | - // Validate that the modelName is actually a supported model. | |
| 72 | - if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { | |
| 73 | - // Check if modelName includes any known model name as substring. | |
| 74 | - const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) => | |
| 75 | - modelName.includes(key), | |
| 76 | - ); | |
| 27 | +// Export a utility for providers to use | |
| 28 | +export class PromptTemplateRenderer { | |
| 29 | + private compiledTemplate: HandlebarsTemplateDelegate; | |
| 77 | 30 | |
| 78 | - if (matchingModel) { | |
| 79 | - modelName = matchingModel as NEXT_EDIT_MODELS; | |
| 80 | - } else { | |
| 81 | - throw new Error( | |
| 82 | - `${helper.modelName} is not yet supported for next edit.`, | |
| 83 | - ); | |
| 84 | - } | |
| 31 | + constructor(template: string) { | |
| 32 | + this.compiledTemplate = Handlebars.compile(template); | |
| 85 | 33 | } |
| 86 | 34 | |
| 87 | - const renderer = templateRendererOfModel(modelName); | |
| 88 | - let userEdits = ""; | |
| 89 | - let editedCodeWithTokens = ""; | |
| 90 | - let tv: TemplateVars; | |
| 91 | - | |
| 92 | - switch (modelName) { | |
| 93 | - case "mercury-coder-nextedit": { | |
| 94 | - userEdits = ctx.editDiffHistory; | |
| 95 | - | |
| 96 | - // editedCodeWithTokens = insertTokens( | |
| 97 | - // helper.fileContents.split("\n"), | |
| 98 | - // helper.pos, | |
| 99 | - // MERCURY_CURSOR, | |
| 100 | - // ); | |
| 101 | - | |
| 102 | - const mercuryCtx: MercuryTemplateVars = { | |
| 103 | - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 104 | - ctx.recentlyViewedCodeSnippets, | |
| 105 | - ), | |
| 106 | - currentFileContent: currentFileContentBlock( | |
| 107 | - ctx.currentFileContent, | |
| 108 | - ctx.editableRegionStartLine, | |
| 109 | - ctx.editableRegionEndLine, | |
| 110 | - helper.pos, | |
| 111 | - ), | |
| 112 | - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), | |
| 113 | - currentFilePath: ctx.currentFilePath, | |
| 114 | - }; | |
| 115 | - | |
| 116 | - tv = mercuryCtx; | |
| 117 | - | |
| 118 | - editedCodeWithTokens = mercuryCtx.currentFileContent; | |
| 119 | - | |
| 120 | - break; | |
| 121 | - } | |
| 122 | - case "instinct": { | |
| 123 | - userEdits = ctx.editDiffHistory; | |
| 124 | - | |
| 125 | - // editedCodeWithTokens = insertTokens( | |
| 126 | - // helper.fileContents.split("\n"), | |
| 127 | - // helper.pos, | |
| 128 | - // INSTINCT_USER_CURSOR_IS_HERE_TOKEN, | |
| 129 | - // ); | |
| 130 | - | |
| 131 | - const instinctCtx: InstinctTemplateVars = { | |
| 132 | - contextSnippets: contextSnippetsBlock(ctx.contextSnippets), | |
| 133 | - currentFileContent: instinctCurrentFileContentBlock( | |
| 134 | - ctx.currentFileContent, | |
| 135 | - ctx.windowStart, | |
| 136 | - ctx.windowEnd, | |
| 137 | - ctx.editableRegionStartLine, | |
| 138 | - ctx.editableRegionEndLine, | |
| 139 | - helper.pos, | |
| 140 | - ), | |
| 141 | - editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory), | |
| 142 | - currentFilePath: ctx.currentFilePath, | |
| 143 | - languageShorthand: ctx.languageShorthand, | |
| 144 | - }; | |
| 145 | - | |
| 146 | - tv = instinctCtx; | |
| 147 | - | |
| 148 | - editedCodeWithTokens = instinctCtx.currentFileContent; | |
| 149 | - | |
| 150 | - break; | |
| 151 | - } | |
| 152 | - default: | |
| 153 | - tv = {}; | |
| 154 | - break; | |
| 35 | + render(vars: TemplateVars): string { | |
| 36 | + return this.compiledTemplate(vars); | |
| 155 | 37 | } |
| 156 | - | |
| 157 | - return { | |
| 158 | - prompt: { | |
| 159 | - role: "user", | |
| 160 | - content: renderer(tv), | |
| 161 | - }, | |
| 162 | - userEdits, | |
| 163 | - userExcerpts: editedCodeWithTokens, | |
| 164 | - }; | |
| 165 | -} | |
| 166 | - | |
| 167 | -export function renderDefaultSystemPrompt(): SystemPrompt { | |
| 168 | - return { | |
| 169 | - role: "system", | |
| 170 | - content: [ | |
| 171 | - /* Identity forming */ | |
| 172 | - "You are an expert polyglot developer who is overseeing a junior developer write code in some language.", | |
| 173 | - "You are psychic as well, so you are an expert at reading minds just from what the junior has done.", | |
| 174 | - "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.", | |
| 175 | - /* Action crash course */ | |
| 176 | - "An action is a change in code state that preserves the well-formedness of the code.", | |
| 177 | - "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.", | |
| 178 | - /* Input description */ | |
| 179 | - // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.', | |
| 180 | - // "language is the language the code is written in.", | |
| 181 | - // "originalCode is the code state before the junior has taken some edit action.", | |
| 182 | - // "editedCode is the code state after the junior has taken some edit action.", | |
| 183 | - // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.", | |
| 184 | - // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.", | |
| 185 | - 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.', | |
| 186 | - "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.", | |
| 187 | - "recentlyEditedRange is the code that the junior has recently edited.", | |
| 188 | - "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.", | |
| 189 | - "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.", | |
| 190 | - "The junior might want to add new code, delete existing code, or replace different parts of code.", | |
| 191 | - "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.", | |
| 192 | - /* Output description */ | |
| 193 | - 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.', | |
| 194 | - /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/ | |
| 195 | - /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */ | |
| 196 | - "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.", | |
| 197 | - // "actionType is the type of action the junior has taken.", | |
| 198 | - "newCode is what the full code looks like after applying your nextEditContent.", | |
| 199 | - // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.", | |
| 200 | - "Given the above definition of an action, you should prioritize fixing the following:", | |
| 201 | - "- Patterns and repetition in code.", | |
| 202 | - "- Static errors that the compiler of the language may return.", | |
| 203 | - "- The junior's code style.", | |
| 204 | - "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.", | |
| 205 | - "If the junior has added some code, there's a good chance that the next edit will also be additions.", | |
| 206 | - "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.", | |
| 207 | - "Careful of language intricacies.", | |
| 208 | - // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.", | |
| 209 | - "Do not reply in markdown.", | |
| 210 | - "Do not hallucinate.", | |
| 211 | - ].join(" "), | |
| 212 | - }; | |
| 213 | -} | |
| 214 | - | |
| 215 | -export function renderDefaultUserPrompt( | |
| 216 | - // originalCode: string, | |
| 217 | - // editedCode: string, | |
| 218 | - snippets: SnippetPayload, | |
| 219 | - helper: HelperVars, | |
| 220 | -): UserPrompt { | |
| 221 | - const userEdit = { | |
| 222 | - language: helper.lang, | |
| 223 | - rootPathSnippets: snippets.rootPathSnippets, | |
| 224 | - importDefinitionSnippets: snippets.importDefinitionSnippets, | |
| 225 | - ideSnippets: snippets.ideSnippets, | |
| 226 | - recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets, | |
| 227 | - diffSnippets: snippets.diffSnippets, | |
| 228 | - clipboardSnippets: snippets.clipboardSnippets, | |
| 229 | - recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets, | |
| 230 | - }; | |
| 231 | - | |
| 232 | - return { | |
| 233 | - role: "user", | |
| 234 | - content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`, | |
| 235 | - }; | |
| 236 | 38 | } |
| 237 | 39 | |
| 238 | -function insertTokens( | |
| 239 | - lines: string[], | |
| 240 | - cursorPos: Position, | |
| 241 | - cursorToken: string, | |
| 242 | - editableRegionStart?: number, | |
| 243 | - editableRegionEnd?: number, | |
| 244 | -) { | |
| 245 | - const a = insertCursorToken(lines, cursorPos, cursorToken); | |
| 246 | - const b = insertEditableRegionTokensWithStaticRange( | |
| 247 | - a, | |
| 248 | - cursorPos, | |
| 249 | - editableRegionStart, | |
| 250 | - editableRegionEnd, | |
| 251 | - ); | |
| 252 | - return b.join("\n"); | |
| 40 | +// Keep for backward compatibility or remove if not needed | |
| 41 | +export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string { | |
| 42 | + const template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; | |
| 43 | + if (!template) { | |
| 44 | + throw new Error(`Model ${modelName} is not supported for next edit.`); | |
| 45 | + } | |
| 46 | + return template.template; | |
| 253 | 47 | } |
modified core/nextEdit/templating/NextEditPromptEngine.vitest.ts +81 −208
| @@ -1,239 +1,112 @@ | ||
| 1 | -import { beforeEach, describe, expect, it } from "vitest"; | |
| 2 | -import { Position } from "../.."; | |
| 3 | -import { SnippetPayload } from "../../autocomplete/snippets"; | |
| 4 | -import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; | |
| 5 | -import { HelperVars } from "../../autocomplete/util/HelperVars"; | |
| 1 | +import { describe, expect, it } from "vitest"; | |
| 6 | 2 | import { NEXT_EDIT_MODELS } from "../../llm/constants"; |
| 7 | 3 | import { |
| 8 | - INSTINCT_USER_CURSOR_IS_HERE_TOKEN, | |
| 9 | 4 | INSTINCT_USER_PROMPT_PREFIX, |
| 10 | 5 | MERCURY_CURRENT_FILE_CONTENT_CLOSE, |
| 11 | 6 | MERCURY_CURRENT_FILE_CONTENT_OPEN, |
| 12 | - MERCURY_CURSOR, | |
| 13 | 7 | MERCURY_EDIT_DIFF_HISTORY_CLOSE, |
| 14 | 8 | MERCURY_EDIT_DIFF_HISTORY_OPEN, |
| 15 | 9 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, |
| 16 | 10 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, |
| 17 | 11 | } from "../constants"; |
| 18 | 12 | import { |
| 19 | - renderDefaultSystemPrompt, | |
| 20 | - renderDefaultUserPrompt, | |
| 21 | - renderPrompt, | |
| 13 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 14 | + PromptTemplateRenderer, | |
| 15 | + getTemplateForModel, | |
| 22 | 16 | } from "./NextEditPromptEngine"; |
| 23 | 17 | |
| 24 | 18 | describe("NextEditPromptEngine", () => { |
| 25 | - describe("renderPrompt", () => { | |
| 26 | - let mercuryHelper: HelperVars; | |
| 27 | - let instinctHelper: HelperVars; | |
| 28 | - let testHelper: HelperVars; | |
| 29 | - let unsupportedHelper: HelperVars; | |
| 30 | - let ctx: any; | |
| 31 | - | |
| 32 | - beforeEach(() => { | |
| 33 | - mercuryHelper = { | |
| 34 | - modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, | |
| 35 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 36 | - pos: { line: 1, character: 12 } as Position, | |
| 37 | - lang: { name: "typescript" }, | |
| 38 | - } as HelperVars; | |
| 39 | - instinctHelper = { | |
| 40 | - modelName: "continuedev/instinct" as NEXT_EDIT_MODELS, | |
| 41 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 42 | - pos: { line: 1, character: 12 } as Position, | |
| 43 | - lang: { name: "typescript" }, | |
| 44 | - } as HelperVars; | |
| 45 | - unsupportedHelper = { | |
| 46 | - modelName: "mistral/codestral" as NEXT_EDIT_MODELS, | |
| 47 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 48 | - pos: { line: 1, character: 12 } as Position, | |
| 49 | - lang: { name: "typescript" }, | |
| 50 | - } as HelperVars; | |
| 51 | - | |
| 52 | - ctx = { | |
| 53 | - recentlyViewedCodeSnippets: [ | |
| 54 | - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, | |
| 55 | - ], | |
| 56 | - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", | |
| 57 | - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], | |
| 58 | - editableRegionStartLine: 0, | |
| 59 | - editableRegionEndLine: 3, | |
| 60 | - userEdits: "Added constant a", | |
| 61 | - languageShorthand: "ts", | |
| 62 | - userExcerpts: "const a = 1;", | |
| 63 | - }; | |
| 19 | + describe("NEXT_EDIT_MODEL_TEMPLATES", () => { | |
| 20 | + it("should contain templates for all supported models", () => { | |
| 21 | + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( | |
| 22 | + NEXT_EDIT_MODELS.MERCURY_CODER, | |
| 23 | + ); | |
| 24 | + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( | |
| 25 | + NEXT_EDIT_MODELS.INSTINCT, | |
| 26 | + ); | |
| 64 | 27 | }); |
| 65 | 28 | |
| 66 | - it("should render mercury-coder-nextedit prompt correctly", async () => { | |
| 67 | - const result = await renderPrompt(mercuryHelper, ctx); | |
| 68 | - | |
| 69 | - expect(result).toHaveProperty("prompt"); | |
| 70 | - expect(result.prompt.role).toBe("user"); | |
| 71 | - | |
| 72 | - const content = result.prompt.content; | |
| 73 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); | |
| 74 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); | |
| 75 | - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); | |
| 76 | - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); | |
| 77 | - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); | |
| 78 | - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); | |
| 79 | - | |
| 80 | - expect(result.userEdits).toBe(ctx.editDiffHistory); | |
| 81 | - expect(result.userExcerpts).toContain(MERCURY_CURSOR); | |
| 29 | + it("mercury-coder template should contain expected tokens", () => { | |
| 30 | + const template = | |
| 31 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; | |
| 32 | + | |
| 33 | + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); | |
| 34 | + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); | |
| 35 | + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); | |
| 36 | + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); | |
| 37 | + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); | |
| 38 | + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); | |
| 39 | + expect(template).toContain("{{{recentlyViewedCodeSnippets}}}"); | |
| 40 | + expect(template).toContain("{{{currentFileContent}}}"); | |
| 41 | + expect(template).toContain("{{{editDiffHistory}}}"); | |
| 82 | 42 | }); |
| 83 | 43 | |
| 84 | - it("should render instinct prompt correctly", async () => { | |
| 85 | - // Create proper instinct context structure matching NextEditProvider.ts | |
| 86 | - const instinctCtx = { | |
| 87 | - contextSnippets: | |
| 88 | - "+++++ /path/to/context.ts\nconst contextVar = 'test';", | |
| 89 | - currentFileContent: instinctHelper.fileContents, | |
| 90 | - windowStart: 0, // Math.max(0, helper.pos.line - 25) | |
| 91 | - windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) | |
| 92 | - editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window | |
| 93 | - editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window | |
| 94 | - editDiffHistory: [ | |
| 95 | - "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", | |
| 96 | - ], // unified diff | |
| 97 | - currentFilePath: "/path/to/file.ts", | |
| 98 | - languageShorthand: "ts", | |
| 99 | - }; | |
| 100 | - | |
| 101 | - const result = await renderPrompt(instinctHelper, instinctCtx); | |
| 102 | - console.log(result); | |
| 103 | - | |
| 104 | - expect(result).toHaveProperty("prompt"); | |
| 105 | - expect(result.prompt.role).toBe("user"); | |
| 106 | - expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX); | |
| 107 | - expect(result.prompt.content).toContain("### Context:"); | |
| 108 | - expect(result.prompt.content).toContain("### User Edits:"); | |
| 109 | - expect(result.prompt.content).toContain("### User Excerpts:"); | |
| 110 | - | |
| 111 | - expect(result.userEdits).toBe(instinctCtx.editDiffHistory); | |
| 112 | - expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); | |
| 44 | + it("instinct template should contain expected tokens", () => { | |
| 45 | + const template = | |
| 46 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template; | |
| 47 | + | |
| 48 | + expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX); | |
| 49 | + expect(template).toContain("### Context:"); | |
| 50 | + expect(template).toContain("### User Edits:"); | |
| 51 | + expect(template).toContain("### User Excerpt:"); | |
| 52 | + expect(template).toContain("{{{contextSnippets}}}"); | |
| 53 | + expect(template).toContain("{{{currentFileContent}}}"); | |
| 54 | + expect(template).toContain("{{{editDiffHistory}}}"); | |
| 55 | + expect(template).toContain("{{{currentFilePath}}}"); | |
| 113 | 56 | }); |
| 57 | + }); | |
| 114 | 58 | |
| 115 | - it("should throw error for unsupported model name", async () => { | |
| 116 | - await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow( | |
| 117 | - "mistral/codestral is not yet supported for next edit.", | |
| 118 | - ); | |
| 59 | + describe("PromptTemplateRenderer", () => { | |
| 60 | + it("should render a template with provided variables", () => { | |
| 61 | + const template = "Hello {{{name}}}, you have {{{count}}} messages"; | |
| 62 | + const renderer = new PromptTemplateRenderer(template); | |
| 63 | + | |
| 64 | + const result = renderer.render({ | |
| 65 | + name: "Alice", | |
| 66 | + count: "5", | |
| 67 | + }); | |
| 68 | + | |
| 69 | + expect(result).toBe("Hello Alice, you have 5 messages"); | |
| 119 | 70 | }); |
| 120 | - }); | |
| 121 | 71 | |
| 122 | - describe("renderDefaultSystemPrompt", () => { | |
| 123 | - it("should return a system prompt with expected role and content", () => { | |
| 124 | - const result = renderDefaultSystemPrompt(); | |
| 72 | + it("should handle missing variables gracefully", () => { | |
| 73 | + const template = "Hello {{{name}}}"; | |
| 74 | + const renderer = new PromptTemplateRenderer(template); | |
| 125 | 75 | |
| 126 | - expect(result.role).toBe("system"); | |
| 127 | - expect(result.content).toContain("You are an expert polyglot developer"); | |
| 128 | - expect(result.content).toContain("Do not hallucinate."); | |
| 76 | + const result = renderer.render({}); | |
| 77 | + | |
| 78 | + expect(result).toBe("Hello "); | |
| 129 | 79 | }); |
| 130 | - }); | |
| 131 | 80 | |
| 132 | - describe("renderDefaultUserPrompt", () => { | |
| 133 | - it("should render a user prompt with the correct structure", () => { | |
| 134 | - const snippets: SnippetPayload = { | |
| 135 | - rootPathSnippets: [ | |
| 136 | - { | |
| 137 | - type: AutocompleteSnippetType.Code, | |
| 138 | - filepath: "", | |
| 139 | - content: "root path", | |
| 140 | - }, | |
| 141 | - ], | |
| 142 | - importDefinitionSnippets: [ | |
| 143 | - { | |
| 144 | - type: AutocompleteSnippetType.Code, | |
| 145 | - filepath: "", | |
| 146 | - content: "import def", | |
| 147 | - }, | |
| 148 | - ], | |
| 149 | - ideSnippets: [ | |
| 150 | - { | |
| 151 | - type: AutocompleteSnippetType.Code, | |
| 152 | - filepath: "", | |
| 153 | - content: "ide snippets", | |
| 154 | - }, | |
| 155 | - ], | |
| 156 | - recentlyEditedRangeSnippets: [ | |
| 157 | - { | |
| 158 | - type: AutocompleteSnippetType.Code, | |
| 159 | - filepath: "", | |
| 160 | - content: "recent edits", | |
| 161 | - }, | |
| 162 | - ], | |
| 163 | - diffSnippets: [ | |
| 164 | - { | |
| 165 | - type: AutocompleteSnippetType.Diff, | |
| 166 | - content: "diff snippets", | |
| 167 | - }, | |
| 168 | - ], | |
| 169 | - clipboardSnippets: [ | |
| 170 | - { | |
| 171 | - type: AutocompleteSnippetType.Clipboard, | |
| 172 | - content: "clipboard", | |
| 173 | - copiedAt: new Date().toISOString(), | |
| 174 | - }, | |
| 175 | - ], | |
| 176 | - recentlyVisitedRangesSnippets: [ | |
| 177 | - { | |
| 178 | - type: AutocompleteSnippetType.Code, | |
| 179 | - filepath: "", | |
| 180 | - content: "visited ranges", | |
| 181 | - }, | |
| 182 | - ], | |
| 183 | - recentlyOpenedFileSnippets: [ | |
| 184 | - { | |
| 185 | - type: AutocompleteSnippetType.Code, | |
| 186 | - filepath: "", | |
| 187 | - content: "recently opened files", | |
| 188 | - }, | |
| 189 | - ], | |
| 190 | - staticSnippet: [ | |
| 191 | - { | |
| 192 | - type: AutocompleteSnippetType.Static, | |
| 193 | - filepath: "", | |
| 194 | - content: "static content", | |
| 195 | - }, | |
| 196 | - ], | |
| 197 | - }; | |
| 198 | - | |
| 199 | - const helper: HelperVars = { | |
| 200 | - lang: { name: "typescript" }, | |
| 201 | - } as HelperVars; | |
| 202 | - | |
| 203 | - const result = renderDefaultUserPrompt(snippets, helper); | |
| 204 | - | |
| 205 | - expect(result.role).toBe("user"); | |
| 206 | - expect(result.content).toContain("Your junior made the following edit:"); | |
| 207 | - expect(result.content).toContain("typescript"); | |
| 208 | - expect(result.content).toContain("root path"); | |
| 81 | + it("should render complex templates correctly", () => { | |
| 82 | + const template = | |
| 83 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; | |
| 84 | + const renderer = new PromptTemplateRenderer(template); | |
| 85 | + | |
| 86 | + const result = renderer.render({ | |
| 87 | + recentlyViewedCodeSnippets: "snippet1", | |
| 88 | + currentFileContent: "file content", | |
| 89 | + editDiffHistory: "diff history", | |
| 90 | + }); | |
| 91 | + | |
| 92 | + expect(result).toContain("snippet1"); | |
| 93 | + expect(result).toContain("file content"); | |
| 94 | + expect(result).toContain("diff history"); | |
| 209 | 95 | }); |
| 210 | 96 | }); |
| 211 | 97 | |
| 212 | - describe("insertTokens", () => { | |
| 213 | - it("should correctly insert cursor and editable region tokens", () => { | |
| 214 | - const mercuryHelper = { | |
| 215 | - modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, | |
| 216 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 217 | - pos: { line: 1, character: 12 } as Position, | |
| 218 | - lang: { name: "typescript" }, | |
| 219 | - } as HelperVars; | |
| 220 | - | |
| 221 | - const ctx = { | |
| 222 | - recentlyViewedCodeSnippets: [ | |
| 223 | - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, | |
| 224 | - ], | |
| 225 | - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", | |
| 226 | - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], | |
| 227 | - editableRegionStartLine: 0, | |
| 228 | - editableRegionEndLine: 3, | |
| 229 | - userEdits: "Added constant a", | |
| 230 | - languageShorthand: "ts", | |
| 231 | - userExcerpts: "const a = 1;", | |
| 232 | - }; | |
| 233 | - | |
| 234 | - return renderPrompt(mercuryHelper, ctx).then((result) => { | |
| 235 | - expect(result.userExcerpts).toContain(MERCURY_CURSOR); | |
| 236 | - }); | |
| 98 | + describe("getTemplateForModel", () => { | |
| 99 | + it("should return the correct template for a supported model", () => { | |
| 100 | + const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER); | |
| 101 | + expect(template).toBe( | |
| 102 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template, | |
| 103 | + ); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should throw an error for an unsupported model", () => { | |
| 107 | + expect(() => | |
| 108 | + getTemplateForModel("unsupported" as NEXT_EDIT_MODELS), | |
| 109 | + ).toThrow("Model unsupported is not supported for next edit."); | |
| 237 | 110 | }); |
| 238 | 111 | }); |
| 239 | 112 | }); |
modified core/nextEdit/templating/mercuryCoderNextEdit.ts +4 −0
| @@ -3,6 +3,8 @@ | ||
| 3 | 3 | MERCURY_CODE_TO_EDIT_CLOSE, |
| 4 | 4 | MERCURY_CODE_TO_EDIT_OPEN, |
| 5 | 5 | MERCURY_CURSOR, |
| 6 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE, | |
| 7 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN, | |
| 6 | 8 | } from "../constants"; |
| 7 | 9 | import { insertCursorToken } from "./utils"; |
| 8 | 10 | |
| @@ -11,8 +13,10 @@ | ||
| 11 | 13 | ) { |
| 12 | 14 | return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { |
| 13 | 15 | const block = [ |
| 16 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN, | |
| 14 | 17 | `code_snippet_file_path: ${snippet.filepath}`, |
| 15 | 18 | snippet.content, |
| 19 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE, | |
| 16 | 20 | ].join("\n"); |
| 17 | 21 | |
| 18 | 22 | return ( |
modified core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +7 −1
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | MERCURY_CODE_TO_EDIT_CLOSE, |
| 5 | 5 | MERCURY_CODE_TO_EDIT_OPEN, |
| 6 | 6 | MERCURY_CURSOR, |
| 7 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE, | |
| 8 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN, | |
| 7 | 9 | } from "../constants"; |
| 8 | 10 | import { |
| 9 | 11 | currentFileContentBlock, |
| @@ -25,10 +27,14 @@ | ||
| 25 | 27 | const result = recentlyViewedCodeSnippetsBlock(snippets); |
| 26 | 28 | |
| 27 | 29 | const expected = |
| 30 | + `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` + | |
| 28 | 31 | "code_snippet_file_path: /path/to/file1.ts\n" + |
| 29 | 32 | "const a = 1;\n" + |
| 33 | + `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE}\n` + | |
| 34 | + `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` + | |
| 30 | 35 | "code_snippet_file_path: /path/to/file2.ts\n" + |
| 31 | - "function test() { return true; }"; | |
| 36 | + "function test() { return true; }\n" + | |
| 37 | + MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE; | |
| 32 | 38 | |
| 33 | 39 | expect(result).toBe(expected); |
| 34 | 40 | }); |
modified core/nextEdit/types.ts +36 −0
| @@ -5,7 +5,9 @@ | ||
| 5 | 5 | RangeInFile, |
| 6 | 6 | TabAutocompleteOptions, |
| 7 | 7 | } from "../"; |
| 8 | +import { SnippetPayload } from "../autocomplete/snippets"; | |
| 8 | 9 | import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; |
| 10 | +import { HelperVars } from "../autocomplete/util/HelperVars"; | |
| 9 | 11 | |
| 10 | 12 | export type RecentlyEditedRange = RangeInFile & { |
| 11 | 13 | timestamp: number; |
| @@ -61,6 +63,7 @@ | ||
| 61 | 63 | cursorPosition: { line: number; character: number }; |
| 62 | 64 | finalCursorPosition: { line: number; character: number }; |
| 63 | 65 | accepted?: boolean; |
| 66 | + aborted?: boolean; | |
| 64 | 67 | editableRegionStartLine: number; |
| 65 | 68 | editableRegionEndLine: number; |
| 66 | 69 | diffLines: DiffLine[]; |
| @@ -104,3 +107,36 @@ | ||
| 104 | 107 | editDiffHistory: string; // could be a singe large unified diff |
| 105 | 108 | currentFilePath: string; |
| 106 | 109 | } |
| 110 | + | |
| 111 | +/** | |
| 112 | + * Context object containing all necessary information for model-specific operations. | |
| 113 | + */ | |
| 114 | +export interface ModelSpecificContext { | |
| 115 | + helper: HelperVars; | |
| 116 | + snippetPayload: SnippetPayload; | |
| 117 | + editableRegionStartLine: number; | |
| 118 | + editableRegionEndLine: number; | |
| 119 | + diffContext: string[]; | |
| 120 | + autocompleteContext: string; | |
| 121 | + historyDiff?: string; | |
| 122 | + workspaceDirs?: string[]; | |
| 123 | +} | |
| 124 | + | |
| 125 | +/** | |
| 126 | + * Configuration for editable region calculation. | |
| 127 | + */ | |
| 128 | +export interface EditableRegionConfig { | |
| 129 | + usingFullFileDiff?: boolean; | |
| 130 | + maxTokens?: number; | |
| 131 | + topMargin?: number; | |
| 132 | + bottomMargin?: number; | |
| 133 | +} | |
| 134 | + | |
| 135 | +/** | |
| 136 | + * Configuration for prompt generation. | |
| 137 | + */ | |
| 138 | +export interface PromptConfig { | |
| 139 | + includeHistory?: boolean; | |
| 140 | + includeRecentEdits?: boolean; | |
| 141 | + maxContextSnippets?: number; | |
| 142 | +} |
modified core/nextEdit/utils.ts +9 −0
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { DiffLine } from ".."; |
| 2 | +import { NEXT_EDIT_MODELS } from "../llm/constants"; | |
| 2 | 3 | |
| 3 | 4 | export function isNextEditTest(): boolean { |
| 4 | 5 | const enabled = process.env.NEXT_EDIT_TEST_ENABLED; |
| @@ -21,3 +22,11 @@ | ||
| 21 | 22 | (diff.line.trim() === "" || /^\s+$/.test(diff.line)), |
| 22 | 23 | ); |
| 23 | 24 | } |
| 25 | + | |
| 26 | +export function convertNextEditModelNameToEnum( | |
| 27 | + modelName: string, | |
| 28 | +): NEXT_EDIT_MODELS | undefined { | |
| 29 | + const nextEditModels = Object.values(NEXT_EDIT_MODELS); | |
| 30 | + | |
| 31 | + return nextEditModels.find((model) => modelName.includes(model)); | |
| 32 | +} |
modified core/nextEdit/utils.vitest.ts +38 −1
| @@ -1,6 +1,11 @@ | ||
| 1 | 1 | import { describe, expect, test, vi } from "vitest"; |
| 2 | 2 | import { DiffLine } from ".."; |
| 3 | -import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils"; | |
| 3 | +import { NEXT_EDIT_MODELS } from "../llm/constants"; | |
| 4 | +import { | |
| 5 | + convertNextEditModelNameToEnum, | |
| 6 | + isNextEditTest, | |
| 7 | + isWhitespaceOnlyDeletion, | |
| 8 | +} from "./utils"; | |
| 4 | 9 | |
| 5 | 10 | describe("isNextEditTest", () => { |
| 6 | 11 | test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => { |
| @@ -57,3 +62,35 @@ | ||
| 57 | 62 | expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true); |
| 58 | 63 | }); |
| 59 | 64 | }); |
| 65 | + | |
| 66 | +describe("convertNextEditModelNameToEnum", () => { | |
| 67 | + test("returns correct enum for exact matches", () => { | |
| 68 | + Object.values(NEXT_EDIT_MODELS).forEach((model) => { | |
| 69 | + expect(convertNextEditModelNameToEnum(model)).toBe(model); | |
| 70 | + }); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + test("returns correct enum when model name is contained in a longer string", () => { | |
| 74 | + expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe( | |
| 75 | + NEXT_EDIT_MODELS.MERCURY_CODER, | |
| 76 | + ); | |
| 77 | + expect(convertNextEditModelNameToEnum("blah/instinct")).toBe( | |
| 78 | + NEXT_EDIT_MODELS.INSTINCT, | |
| 79 | + ); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + test("returns undefined for non-matching model names", () => { | |
| 83 | + expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined(); | |
| 84 | + expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined(); | |
| 85 | + expect(convertNextEditModelNameToEnum("")).toBeUndefined(); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + test("returns first match when multiple models could match", () => { | |
| 89 | + const modelName = "model-that-contains-multiple-matches"; | |
| 90 | + const result = convertNextEditModelNameToEnum(modelName); | |
| 91 | + | |
| 92 | + if (result !== undefined) { | |
| 93 | + expect(Object.values(NEXT_EDIT_MODELS)).toContain(result); | |
| 94 | + } | |
| 95 | + }); | |
| 96 | +}); |
modified core/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified core/package.json +9 −4
| @@ -7,7 +7,8 @@ | ||
| 7 | 7 | "vitest": "vitest run", |
| 8 | 8 | "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html", |
| 9 | 9 | "tsc:check": "tsc -p ./ --noEmit", |
| 10 | - "build:npm": "tsc -p ./tsconfig.npm.json && npm run sentry:sourcemaps", | |
| 10 | + "build": "tsc -p ./tsconfig.npm.json", | |
| 11 | + "build:npm": "npm run build && npm run sentry:sourcemaps", | |
| 11 | 12 | "lint": "eslint . --ext ts", |
| 12 | 13 | "lint:fix": "eslint . --ext ts --fix", |
| 13 | 14 | "sentry:sourcemaps": "sentry-cli sourcemaps inject --org continue-xd --project continue ./dist && sentry-cli sourcemaps upload --org continue-xd --project continue ./dist" |
| @@ -33,9 +34,12 @@ | ||
| 33 | 34 | "@types/pg": "^8.11.6", |
| 34 | 35 | "@types/plist": "^3.0.5", |
| 35 | 36 | "@types/request": "^2.48.12", |
| 37 | + "@types/shell-quote": "^1.7.5", | |
| 36 | 38 | "@types/tar": "^6.1.13", |
| 37 | 39 | "@types/uuid": "^9.0.7", |
| 38 | 40 | "@types/win-ca": "^3.5.4", |
| 41 | + "@typescript-eslint/eslint-plugin": "^8.40.0", | |
| 42 | + "@typescript-eslint/parser": "^8.40.0", | |
| 39 | 43 | "cross-env": "^7.0.3", |
| 40 | 44 | "esbuild": "0.17.19", |
| 41 | 45 | "eslint": "^8", |
| @@ -58,6 +62,7 @@ | ||
| 58 | 62 | "@continuedev/fetch": "file:../packages/fetch", |
| 59 | 63 | "@continuedev/llm-info": "file:../packages/llm-info", |
| 60 | 64 | "@continuedev/openai-adapters": "file:../packages/openai-adapters", |
| 65 | + "@continuedev/terminal-security": "file:../packages/terminal-security", | |
| 61 | 66 | "@modelcontextprotocol/sdk": "^1.12.0", |
| 62 | 67 | "@mozilla/readability": "^0.5.0", |
| 63 | 68 | "@octokit/rest": "^20.1.1", |
| @@ -66,7 +71,6 @@ | ||
| 66 | 71 | "@sentry/esbuild-plugin": "^4.0.2", |
| 67 | 72 | "@sentry/node": "^9.43.0", |
| 68 | 73 | "@sentry/vite-plugin": "^4.0.2", |
| 69 | - "@typescript-eslint/eslint-plugin": "^7.8.0", | |
| 70 | 74 | "@xenova/transformers": "2.14.0", |
| 71 | 75 | "adf-to-md": "^1.1.0", |
| 72 | 76 | "async-mutex": "^0.5.0", |
| @@ -85,7 +89,7 @@ | ||
| 85 | 89 | "http-proxy-agent": "^7.0.1", |
| 86 | 90 | "https-proxy-agent": "^7.0.3", |
| 87 | 91 | "iconv-lite": "^0.6.3", |
| 88 | - "ignore": "^5.3.1", | |
| 92 | + "ignore": "^7.0.5", | |
| 89 | 93 | "is-localhost-ip": "^2.0.0", |
| 90 | 94 | "jinja-js": "0.1.8", |
| 91 | 95 | "js-tiktoken": "^1.0.8", |
| @@ -98,7 +102,7 @@ | ||
| 98 | 102 | "node-html-markdown": "^1.3.0", |
| 99 | 103 | "ollama": "^0.4.6", |
| 100 | 104 | "onnxruntime-node": "1.14.0", |
| 101 | - "openai": "^4.104.0", | |
| 105 | + "openai": "^5.13.1", | |
| 102 | 106 | "p-limit": "^6.1.0", |
| 103 | 107 | "partial-json": "^0.1.7", |
| 104 | 108 | "pg": "^8.11.3", |
| @@ -109,6 +113,7 @@ | ||
| 109 | 113 | "quick-lru": "^7.0.0", |
| 110 | 114 | "replicate": "^0.26.0", |
| 111 | 115 | "request": "^2.88.2", |
| 116 | + "shell-quote": "^1.8.3", | |
| 112 | 117 | "socket.io-client": "^4.7.3", |
| 113 | 118 | "sqlite": "^5.1.1", |
| 114 | 119 | "sqlite3": "^5.1.7", |
modified core/protocol/core.ts +19 −4
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | DevDataLogEvent, |
| 5 | 5 | ModelRole, |
| 6 | 6 | } from "@continuedev/config-yaml"; |
| 7 | +import { ToolPolicy } from "@continuedev/terminal-security"; | |
| 7 | 8 | |
| 8 | 9 | import { |
| 9 | 10 | AutocompleteInput, |
| @@ -34,7 +35,7 @@ | ||
| 34 | 35 | RangeInFileWithNextEditInfo, |
| 35 | 36 | SerializedContinueConfig, |
| 36 | 37 | Session, |
| 37 | - SessionMetadata, | |
| 38 | + BaseSessionMetadata, | |
| 38 | 39 | SiteIndexingConfig, |
| 39 | 40 | SlashCommandDescWithSource, |
| 40 | 41 | StreamDiffLinesPayload, |
| @@ -48,9 +49,12 @@ | ||
| 48 | 49 | ControlPlaneEnv, |
| 49 | 50 | ControlPlaneSessionInfo, |
| 50 | 51 | } from "../control-plane/AuthTypes"; |
| 51 | -import { FreeTrialStatus } from "../control-plane/client"; | |
| 52 | -import { NextEditOutcome } from "../nextEdit/types"; | |
| 52 | +import { | |
| 53 | + FreeTrialStatus, | |
| 54 | + RemoteSessionMetadata, | |
| 55 | +} from "../control-plane/client"; | |
| 53 | 56 | import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; |
| 57 | +import { NextEditOutcome } from "../nextEdit/types"; | |
| 54 | 58 | |
| 55 | 59 | export enum OnboardingModes { |
| 56 | 60 | API_KEY = "API Key", |
| @@ -70,9 +74,13 @@ | ||
| 70 | 74 | cancelApply: [undefined, void]; |
| 71 | 75 | |
| 72 | 76 | // History |
| 73 | - "history/list": [ListHistoryOptions, SessionMetadata[]]; | |
| 77 | + "history/list": [ | |
| 78 | + ListHistoryOptions, | |
| 79 | + (BaseSessionMetadata | RemoteSessionMetadata)[], | |
| 80 | + ]; | |
| 74 | 81 | "history/delete": [{ id: string }, void]; |
| 75 | 82 | "history/load": [{ id: string }, Session]; |
| 83 | + "history/loadRemote": [{ remoteId: string }, Session]; | |
| 76 | 84 | "history/save": [Session, void]; |
| 77 | 85 | "history/share": [{ id: string; outputDir?: string }, void]; |
| 78 | 86 | "history/clear": [undefined, void]; |
| @@ -87,6 +95,7 @@ | ||
| 87 | 95 | ]; |
| 88 | 96 | "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; |
| 89 | 97 | "config/newPromptFile": [undefined, void]; |
| 98 | + "config/newAssistantFile": [undefined, void]; | |
| 90 | 99 | "config/ideSettingsUpdate": [IdeSettings, void]; |
| 91 | 100 | "config/getSerializedProfileInfo": [ |
| 92 | 101 | undefined, |
| @@ -285,6 +294,7 @@ | ||
| 285 | 294 | "docs/getSuggestedDocs": [undefined, void]; |
| 286 | 295 | "docs/initStatuses": [undefined, void]; |
| 287 | 296 | "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails]; |
| 297 | + "docs/getIndexedPages": [{ startUrl: string }, string[]]; | |
| 288 | 298 | addAutocompleteModel: [{ model: ModelDescription }, void]; |
| 289 | 299 | |
| 290 | 300 | "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; |
| @@ -292,6 +302,10 @@ | ||
| 292 | 302 | { toolCall: ToolCall }, |
| 293 | 303 | { contextItems: ContextItem[]; errorMessage?: string }, |
| 294 | 304 | ]; |
| 305 | + "tools/evaluatePolicy": [ | |
| 306 | + { toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> }, | |
| 307 | + { policy: ToolPolicy; displayValue?: string }, | |
| 308 | + ]; | |
| 295 | 309 | "clipboardCache/add": [{ content: string }, void]; |
| 296 | 310 | "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; |
| 297 | 311 | "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; |
| @@ -307,5 +321,6 @@ | ||
| 307 | 321 | ]; |
| 308 | 322 | "process/markAsBackgrounded": [{ toolCallId: string }, void]; |
| 309 | 323 | "process/isBackgrounded": [{ toolCallId: string }, boolean]; |
| 324 | + "process/killTerminalProcess": [{ toolCallId: string }, void]; | |
| 310 | 325 | "mdm/setLicenseKey": [{ licenseKey: string }, boolean]; |
| 311 | 326 | }; |
modified core/protocol/ide.ts +1 −0
| @@ -51,6 +51,7 @@ | ||
| 51 | 51 | getPinnedFiles: [undefined, string[]]; |
| 52 | 52 | showLines: [{ filepath: string; startLine: number; endLine: number }, void]; |
| 53 | 53 | readRangeInFile: [{ filepath: string; range: Range }, string]; |
| 54 | + readFileAsDataUrl: [{ filepath: string }, string]; | |
| 54 | 55 | getDiff: [{ includeUnstaged: boolean }, string[]]; |
| 55 | 56 | getTerminalContents: [undefined, string]; |
| 56 | 57 | getDebugLocals: [{ threadIndex: number }, string]; |
modified core/protocol/passThrough.ts +5 −0
| @@ -13,11 +13,13 @@ | ||
| 13 | 13 | "history/list", |
| 14 | 14 | "history/delete", |
| 15 | 15 | "history/load", |
| 16 | + "history/loadRemote", | |
| 16 | 17 | "history/save", |
| 17 | 18 | "history/clear", |
| 18 | 19 | "devdata/log", |
| 19 | 20 | "config/addModel", |
| 20 | 21 | "config/newPromptFile", |
| 22 | + "config/newAssistantFile", | |
| 21 | 23 | "config/ideSettingsUpdate", |
| 22 | 24 | "config/addLocalWorkspaceBlock", |
| 23 | 25 | "config/getSerializedProfileInfo", |
| @@ -70,12 +72,14 @@ | ||
| 70 | 72 | "indexing/setPaused", |
| 71 | 73 | "docs/initStatuses", |
| 72 | 74 | "docs/getDetails", |
| 75 | + "docs/getIndexedPages", | |
| 73 | 76 | // |
| 74 | 77 | "onboarding/complete", |
| 75 | 78 | "addAutocompleteModel", |
| 76 | 79 | "didChangeSelectedProfile", |
| 77 | 80 | "didChangeSelectedOrg", |
| 78 | 81 | "tools/call", |
| 82 | + "tools/evaluatePolicy", | |
| 79 | 83 | "controlPlane/getEnvironment", |
| 80 | 84 | "controlPlane/getFreeTrialStatus", |
| 81 | 85 | "controlPlane/getModelsAddOnUpgradeUrl", |
| @@ -83,6 +87,7 @@ | ||
| 83 | 87 | "isItemTooBig", |
| 84 | 88 | "process/markAsBackgrounded", |
| 85 | 89 | "process/isBackgrounded", |
| 90 | + "process/killTerminalProcess", | |
| 86 | 91 | ]; |
| 87 | 92 | |
| 88 | 93 | // Message types to pass through from core to webview |
modified core/test/fixtures.ts +1 −3
| @@ -12,13 +12,11 @@ | ||
| 12 | 12 | |
| 13 | 13 | export const testControlPlaneClient = new ControlPlaneClient( |
| 14 | 14 | Promise.resolve(undefined), |
| 15 | - ideSettingsPromise, | |
| 16 | - testIde.getIdeInfo(), | |
| 15 | + testIde, | |
| 17 | 16 | ); |
| 18 | 17 | |
| 19 | 18 | export const testConfigHandler = new ConfigHandler( |
| 20 | 19 | testIde, |
| 21 | - ideSettingsPromise, | |
| 22 | 20 | new LLMLogger(), |
| 23 | 21 | Promise.resolve(undefined), |
| 24 | 22 | ); |
modified core/tools/builtIn.ts +5 −2
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | export enum BuiltInToolNames { |
| 2 | 2 | ReadFile = "read_file", |
| 3 | + ReadFileRange = "read_file_range", | |
| 3 | 4 | EditExistingFile = "edit_existing_file", |
| 4 | - SearchAndReplaceInFile = "search_and_replace_in_file", | |
| 5 | + SingleFindAndReplace = "single_find_and_replace", | |
| 6 | + MultiEdit = "multi_edit", | |
| 5 | 7 | ReadCurrentlyOpenFile = "read_currently_open_file", |
| 6 | 8 | CreateNewFile = "create_new_file", |
| 7 | 9 | RunTerminalCommand = "run_terminal_command", |
| @@ -24,5 +26,6 @@ | ||
| 24 | 26 | |
| 25 | 27 | export const CLIENT_TOOLS_IMPLS = [ |
| 26 | 28 | BuiltInToolNames.EditExistingFile, |
| 27 | - BuiltInToolNames.SearchAndReplaceInFile, | |
| 29 | + BuiltInToolNames.SingleFindAndReplace, | |
| 30 | + BuiltInToolNames.MultiEdit, | |
| 28 | 31 | ]; |
modified core/tools/callTool.ts +13 −4
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; | |
| 1 | 2 | import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; |
| 2 | 3 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 3 | 4 | import { canParseUrl } from "../util/url"; |
| @@ -12,6 +13,8 @@ | ||
| 12 | 13 | import { lsToolImpl } from "./implementations/lsTool"; |
| 13 | 14 | import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; |
| 14 | 15 | import { readFileImpl } from "./implementations/readFile"; |
| 16 | + | |
| 17 | +import { readFileRangeImpl } from "./implementations/readFileRange"; | |
| 15 | 18 | import { requestRuleImpl } from "./implementations/requestRule"; |
| 16 | 19 | import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; |
| 17 | 20 | import { searchWebImpl } from "./implementations/searchWeb"; |
| @@ -85,10 +88,14 @@ | ||
| 85 | 88 | if (!client) { |
| 86 | 89 | throw new Error("MCP connection not found"); |
| 87 | 90 | } |
| 88 | - const response = await client.client.callTool({ | |
| 89 | - name: toolName, | |
| 90 | - arguments: args, | |
| 91 | - }); | |
| 91 | + const response = await client.client.callTool( | |
| 92 | + { | |
| 93 | + name: toolName, | |
| 94 | + arguments: args, | |
| 95 | + }, | |
| 96 | + CallToolResultSchema, | |
| 97 | + { timeout: client.options.timeout }, | |
| 98 | + ); | |
| 92 | 99 | |
| 93 | 100 | if (response.isError === true) { |
| 94 | 101 | throw new Error(JSON.stringify(response.content)); |
| @@ -145,6 +152,8 @@ | ||
| 145 | 152 | switch (functionName) { |
| 146 | 153 | case BuiltInToolNames.ReadFile: |
| 147 | 154 | return await readFileImpl(args, extras); |
| 155 | + case BuiltInToolNames.ReadFileRange: | |
| 156 | + return await readFileRangeImpl(args, extras); | |
| 148 | 157 | case BuiltInToolNames.CreateNewFile: |
| 149 | 158 | return await createNewFileImpl(args, extras); |
| 150 | 159 | case BuiltInToolNames.GrepSearch: |
modified core/tools/definitions/createNewFile.ts +3 −3
| @@ -4,9 +4,9 @@ | ||
| 4 | 4 | export const createNewFileTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Create New File", |
| 7 | - wouldLikeTo: "create a new file at {{{ filepath }}}", | |
| 8 | - isCurrently: "creating a new file at {{{ filepath }}}", | |
| 9 | - hasAlready: "created a new file at {{{ filepath }}}", | |
| 7 | + wouldLikeTo: "create {{{ filepath }}}", | |
| 8 | + isCurrently: "creating {{{ filepath }}}", | |
| 9 | + hasAlready: "created {{{ filepath }}}", | |
| 10 | 10 | group: BUILT_IN_GROUP_NAME, |
| 11 | 11 | readonly: false, |
| 12 | 12 | isInstant: true, |
modified core/tools/definitions/createRuleBlock.ts +1 −0
| @@ -84,4 +84,5 @@ | ||
| 84 | 84 | ["alwaysApply", "false"], |
| 85 | 85 | ], |
| 86 | 86 | }, |
| 87 | + toolCallIcon: "PencilIcon", | |
| 87 | 88 | }; |
modified core/tools/definitions/editFile.ts +4 −2
| @@ -1,13 +1,15 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | -import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; | |
| 5 | 4 | |
| 6 | 5 | export interface EditToolArgs { |
| 7 | 6 | filepath: string; |
| 8 | 7 | changes: string; |
| 9 | 8 | } |
| 10 | 9 | |
| 10 | +export const NO_PARALLEL_TOOL_CALLING_INSTRUCTION = | |
| 11 | + "This tool CANNOT be called in parallel with other tools."; | |
| 12 | + | |
| 11 | 13 | const CHANGES_DESCRIPTION = |
| 12 | 14 | "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; |
| 13 | 15 | |
| @@ -22,7 +24,7 @@ | ||
| 22 | 24 | isInstant: false, |
| 23 | 25 | function: { |
| 24 | 26 | name: BuiltInToolNames.EditExistingFile, |
| 25 | - description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, | |
| 27 | + description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}`, | |
| 26 | 28 | parameters: { |
| 27 | 29 | type: "object", |
| 28 | 30 | required: ["filepath", "changes"], |
modified core/tools/definitions/fetchUrlContent.ts +2 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | displayTitle: "Read URL", |
| 7 | 7 | wouldLikeTo: "fetch {{{ url }}}", |
| 8 | 8 | isCurrently: "fetching {{{ url }}}", |
| 9 | - hasAlready: "viewed {{{ url }}}", | |
| 9 | + hasAlready: "fetched {{{ url }}}", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, |
| 31 | 31 | exampleArgs: [["url", "https://example.com"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "GlobeAltIcon", | |
| 33 | 34 | }; |
modified core/tools/definitions/globSearch.ts +5 −4
| @@ -4,16 +4,16 @@ | ||
| 4 | 4 | export const globSearchTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Glob File Search", |
| 7 | - wouldLikeTo: 'find file matches for "{{{ pattern }}}"', | |
| 8 | - isCurrently: 'finding file matches for "{{{ pattern }}}"', | |
| 9 | - hasAlready: 'retrieved file matches for "{{{ pattern }}}"', | |
| 7 | + wouldLikeTo: 'search for files like "{{{ pattern }}}"', | |
| 8 | + isCurrently: 'searching for files like "{{{ pattern }}}"', | |
| 9 | + hasAlready: 'searched for files like "{{{ pattern }}}"', | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.FileGlobSearch, |
| 15 | 15 | description: |
| 16 | - "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns", | |
| 16 | + "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["pattern"], |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, |
| 31 | 31 | exampleArgs: [["pattern", "*.py"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "MagnifyingGlassIcon", | |
| 33 | 34 | }; |
modified core/tools/definitions/grepSearch.ts +5 −4
| @@ -4,16 +4,16 @@ | ||
| 4 | 4 | export const grepSearchTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Grep Search", |
| 7 | - wouldLikeTo: 'search for "{{{ query }}}" in the repository', | |
| 8 | - isCurrently: 'getting search results for "{{{ query }}}"', | |
| 9 | - hasAlready: 'retrieved search results for "{{{ query }}}"', | |
| 7 | + wouldLikeTo: 'search for "{{{ query }}}"', | |
| 8 | + isCurrently: 'searching for "{{{ query }}}"', | |
| 9 | + hasAlready: 'searched for "{{{ query }}}"', | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.GrepSearch, |
| 15 | 15 | description: |
| 16 | - "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries", | |
| 16 | + "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", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["query"], |
| @@ -31,4 +31,5 @@ | ||
| 31 | 31 | prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, |
| 32 | 32 | exampleArgs: [["query", ".*main_services.*"]], |
| 33 | 33 | }, |
| 34 | + toolCallIcon: "MagnifyingGlassIcon", | |
| 34 | 35 | }; |
modified core/tools/definitions/index.ts +4 −1
| @@ -6,12 +6,15 @@ | ||
| 6 | 6 | export { globSearchTool } from "./globSearch"; |
| 7 | 7 | export { grepSearchTool } from "./grepSearch"; |
| 8 | 8 | export { lsTool } from "./ls"; |
| 9 | +export { multiEditTool } from "./multiEdit"; | |
| 9 | 10 | export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile"; |
| 10 | 11 | export { readFileTool } from "./readFile"; |
| 12 | + | |
| 13 | +export { readFileRangeTool } from "./readFileRange"; | |
| 11 | 14 | export { requestRuleTool } from "./requestRule"; |
| 12 | 15 | export { runTerminalCommandTool } from "./runTerminalCommand"; |
| 13 | -export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile"; | |
| 14 | 16 | export { searchWebTool } from "./searchWeb"; |
| 17 | +export { singleFindAndReplaceTool } from "./singleFindAndReplace"; | |
| 15 | 18 | export { viewDiffTool } from "./viewDiff"; |
| 16 | 19 | export { viewRepoMapTool } from "./viewRepoMap"; |
| 17 | 20 | export { viewSubdirectoryTool } from "./viewSubdirectory"; |
modified core/tools/definitions/ls.ts +4 −3
| @@ -5,9 +5,9 @@ | ||
| 5 | 5 | export const lsTool: Tool = { |
| 6 | 6 | type: "function", |
| 7 | 7 | displayTitle: "ls", |
| 8 | - wouldLikeTo: "list files and folders in {{{ dirPath }}}", | |
| 9 | - isCurrently: "listing files and folders in {{{ dirPath }}}", | |
| 10 | - hasAlready: "listed files and folders in {{{ dirPath }}}", | |
| 8 | + wouldLikeTo: "list files in {{{ dirPath }}}", | |
| 9 | + isCurrently: "listing files in {{{ dirPath }}}", | |
| 10 | + hasAlready: "listed files in {{{ dirPath }}}", | |
| 11 | 11 | readonly: true, |
| 12 | 12 | isInstant: true, |
| 13 | 13 | group: BUILT_IN_GROUP_NAME, |
| @@ -38,4 +38,5 @@ | ||
| 38 | 38 | ["recursive", "false"], |
| 39 | 39 | ], |
| 40 | 40 | }, |
| 41 | + toolCallIcon: "FolderIcon", | |
| 41 | 42 | }; |
added core/tools/definitions/multiEdit.ts +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +import { Tool } from "../.."; | |
| 2 | +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; | |
| 4 | +import { singleFindAndReplaceTool } from "./singleFindAndReplace"; | |
| 5 | + | |
| 6 | +export interface EditOperation { | |
| 7 | + old_string: string; | |
| 8 | + new_string: string; | |
| 9 | + replace_all?: boolean; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export interface MultiEditArgs { | |
| 13 | + filepath: string; | |
| 14 | + edits: EditOperation[]; | |
| 15 | +} | |
| 16 | + | |
| 17 | +export const multiEditTool: Tool = { | |
| 18 | + type: "function", | |
| 19 | + displayTitle: "Multi Edit", | |
| 20 | + wouldLikeTo: "edit {{{ filepath }}}", | |
| 21 | + isCurrently: "editing {{{ filepath }}}", | |
| 22 | + hasAlready: "edited {{{ filepath }}}", | |
| 23 | + group: BUILT_IN_GROUP_NAME, | |
| 24 | + readonly: false, | |
| 25 | + isInstant: false, | |
| 26 | + function: { | |
| 27 | + name: BuiltInToolNames.MultiEdit, | |
| 28 | + 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. | |
| 29 | +Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file. | |
| 30 | + | |
| 31 | +To make multiple edits to a file, provide the following: | |
| 32 | +1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct) | |
| 33 | +2. edits: An array of edit operations to perform, where each edit contains: | |
| 34 | + - old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation) | |
| 35 | + - new_string: The edited text to replace the old_string | |
| 36 | + - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. | |
| 37 | + | |
| 38 | +IMPORTANT: | |
| 39 | +- All edits are applied in sequence, in the order they are provided | |
| 40 | +- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations | |
| 41 | +- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied | |
| 42 | +- This tool is ideal when you need to make several changes to different parts of the same file | |
| 43 | + | |
| 44 | +CRITICAL REQUIREMENTS: | |
| 45 | +1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. | |
| 46 | +2. ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION} | |
| 47 | +3. When making edits: | |
| 48 | +- Ensure all edits result in idiomatic, correct code | |
| 49 | +- Do not leave the code in a broken state | |
| 50 | +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked | |
| 51 | +- 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 | |
| 52 | + | |
| 53 | +WARNINGS: | |
| 54 | +- If earlier edits affect the text that later edits are trying to find, files can become mangled | |
| 55 | +- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) | |
| 56 | +- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`, | |
| 57 | + parameters: { | |
| 58 | + type: "object", | |
| 59 | + required: ["filepath", "edits"], | |
| 60 | + properties: { | |
| 61 | + filepath: { | |
| 62 | + type: "string", | |
| 63 | + description: | |
| 64 | + "The path to the file to modify, relative to the root of the workspace", | |
| 65 | + }, | |
| 66 | + edits: { | |
| 67 | + type: "array", | |
| 68 | + description: | |
| 69 | + "Array of edit operations to perform sequentially on the file", | |
| 70 | + items: { | |
| 71 | + type: "object", | |
| 72 | + required: ["old_string", "new_string"], | |
| 73 | + properties: { | |
| 74 | + old_string: { | |
| 75 | + type: "string", | |
| 76 | + description: | |
| 77 | + "The text to replace (exact match including whitespace/indentation)", | |
| 78 | + }, | |
| 79 | + new_string: { | |
| 80 | + type: "string", | |
| 81 | + description: | |
| 82 | + "The text to replace it with. MUST be different than old_string.", | |
| 83 | + }, | |
| 84 | + replace_all: { | |
| 85 | + type: "boolean", | |
| 86 | + description: | |
| 87 | + "Replace all occurrences of old_string (default false) in the file", | |
| 88 | + }, | |
| 89 | + }, | |
| 90 | + }, | |
| 91 | + }, | |
| 92 | + }, | |
| 93 | + }, | |
| 94 | + }, | |
| 95 | + systemMessageDescription: { | |
| 96 | + prefix: `To make multiple edits to a single file, use the ${BuiltInToolNames.MultiEdit} tool with a filepath (relative to the root of the workspace) and an array of edit operations. | |
| 97 | + | |
| 98 | + For example, you could respond with:`, | |
| 99 | + exampleArgs: [ | |
| 100 | + ["filepath", "path/to/file.ts"], | |
| 101 | + [ | |
| 102 | + "edits", | |
| 103 | + `[ | |
| 104 | + { "old_string": "const oldVar = 'value'", "new_string": "const newVar = 'updated'" }, | |
| 105 | + { "old_string": "oldFunction()", "new_string": "newFunction()", "replace_all": true } | |
| 106 | +]`, | |
| 107 | + ], | |
| 108 | + ], | |
| 109 | + }, | |
| 110 | + defaultToolPolicy: "allowedWithPermission", | |
| 111 | +}; |
modified core/tools/definitions/readCurrentlyOpenFile.ts +3 −2
| @@ -6,14 +6,14 @@ | ||
| 6 | 6 | displayTitle: "Read Currently Open File", |
| 7 | 7 | wouldLikeTo: "read the current file", |
| 8 | 8 | isCurrently: "reading the current file", |
| 9 | - hasAlready: "viewed the current file", | |
| 9 | + hasAlready: "read the current file", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.ReadCurrentlyOpenFile, |
| 15 | 15 | description: |
| 16 | - "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this", | |
| 16 | + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | properties: {}, |
| @@ -24,4 +24,5 @@ | ||
| 24 | 24 | prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. |
| 25 | 25 | If the user is asking about a file and you don't see any code, use this to check the current file`, |
| 26 | 26 | }, |
| 27 | + toolCallIcon: "DocumentTextIcon", | |
| 27 | 28 | }; |
modified core/tools/definitions/readFile.ts +2 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | displayTitle: "Read File", |
| 7 | 7 | wouldLikeTo: "read {{{ filepath }}}", |
| 8 | 8 | isCurrently: "reading {{{ filepath }}}", |
| 9 | - hasAlready: "viewed {{{ filepath }}}", | |
| 9 | + hasAlready: "read {{{ filepath }}}", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| @@ -31,4 +31,5 @@ | ||
| 31 | 31 | exampleArgs: [["filepath", "path/to/the_file.txt"]], |
| 32 | 32 | }, |
| 33 | 33 | defaultToolPolicy: "allowedWithoutPermission", |
| 34 | + toolCallIcon: "DocumentIcon", | |
| 34 | 35 | }; |
added core/tools/definitions/readFileRange.ts +52 −0
| @@ -0,0 +1,52 @@ | ||
| 1 | +import { Tool } from "../.."; | |
| 2 | +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | + | |
| 4 | +export const readFileRangeTool: Tool = { | |
| 5 | + type: "function", | |
| 6 | + displayTitle: "Read File Range", | |
| 7 | + wouldLikeTo: | |
| 8 | + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 9 | + isCurrently: | |
| 10 | + "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 11 | + hasAlready: | |
| 12 | + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 13 | + readonly: true, | |
| 14 | + isInstant: true, | |
| 15 | + group: BUILT_IN_GROUP_NAME, | |
| 16 | + function: { | |
| 17 | + name: BuiltInToolNames.ReadFileRange, | |
| 18 | + description: | |
| 19 | + "Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.", | |
| 20 | + parameters: { | |
| 21 | + type: "object", | |
| 22 | + required: ["filepath", "startLine", "endLine"], | |
| 23 | + properties: { | |
| 24 | + filepath: { | |
| 25 | + type: "string", | |
| 26 | + description: | |
| 27 | + "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", | |
| 28 | + }, | |
| 29 | + startLine: { | |
| 30 | + type: "number", | |
| 31 | + description: | |
| 32 | + "The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line", | |
| 33 | + }, | |
| 34 | + endLine: { | |
| 35 | + type: "number", | |
| 36 | + description: | |
| 37 | + "The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line", | |
| 38 | + }, | |
| 39 | + }, | |
| 40 | + }, | |
| 41 | + }, | |
| 42 | + systemMessageDescription: { | |
| 43 | + prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`, | |
| 44 | + exampleArgs: [ | |
| 45 | + ["filepath", "path/to/the_file.txt"], | |
| 46 | + ["startLine", 10], | |
| 47 | + ["endLine", 20], | |
| 48 | + ], | |
| 49 | + }, | |
| 50 | + defaultToolPolicy: "allowedWithoutPermission", | |
| 51 | + toolCallIcon: "DocumentIcon", | |
| 52 | +}; |
modified core/tools/definitions/runTerminalCommand.ts +13 −0
| @@ -1,6 +1,10 @@ | ||
| 1 | 1 | import os from "os"; |
| 2 | 2 | import { Tool } from "../.."; |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | +import { | |
| 5 | + evaluateTerminalCommandSecurity, | |
| 6 | + ToolPolicy, | |
| 7 | +} from "@continuedev/terminal-security"; | |
| 4 | 8 | |
| 5 | 9 | /** |
| 6 | 10 | * Get the preferred shell for the current platform |
| @@ -56,6 +60,15 @@ | ||
| 56 | 60 | }, |
| 57 | 61 | }, |
| 58 | 62 | defaultToolPolicy: "allowedWithPermission", |
| 63 | + evaluateToolCallPolicy: ( | |
| 64 | + basePolicy: ToolPolicy, | |
| 65 | + parsedArgs: Record<string, unknown>, | |
| 66 | + ): ToolPolicy => { | |
| 67 | + return evaluateTerminalCommandSecurity( | |
| 68 | + basePolicy, | |
| 69 | + parsedArgs.command as string, | |
| 70 | + ); | |
| 71 | + }, | |
| 59 | 72 | systemMessageDescription: { |
| 60 | 73 | prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool |
| 61 | 74 | ${RUN_COMMAND_NOTES} |
deleted core/tools/definitions/searchAndReplaceInFile.ts +0 −112
| @@ -1,112 +0,0 @@ | ||
| 1 | -import { Tool } from "../.."; | |
| 2 | -import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | - | |
| 4 | -export interface SearchAndReplaceInFileArgs { | |
| 5 | - filepath: string; | |
| 6 | - diffs: string[]; | |
| 7 | -} | |
| 8 | - | |
| 9 | -// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` | |
| 10 | -export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = | |
| 11 | - "Note this tool CANNOT be called in parallel."; | |
| 12 | - | |
| 13 | -const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH | |
| 14 | -[exact content to find] | |
| 15 | -======= | |
| 16 | -[new content to replace with] | |
| 17 | -+++++++ REPLACE`; | |
| 18 | - | |
| 19 | -const SEARCH_AND_REPLACE_RULES = `Critical rules: | |
| 20 | -1. SEARCH content must match the associated file section to find EXACTLY: | |
| 21 | - * Match character-for-character including whitespace, indentation, line endings | |
| 22 | - * Include all comments, docstrings, etc. | |
| 23 | -2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. | |
| 24 | - * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. | |
| 25 | - * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. | |
| 26 | - * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. | |
| 27 | -3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. | |
| 28 | -4. Keep SEARCH/REPLACE blocks concise: | |
| 29 | - * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. | |
| 30 | - * Include just the changing lines, and a few surrounding lines if needed for uniqueness. | |
| 31 | - * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. | |
| 32 | - * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. | |
| 33 | -5. Splitting up tool calls: | |
| 34 | - * 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 | |
| 35 | - * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls | |
| 36 | - * 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] | |
| 37 | -6. Special operations: | |
| 38 | - * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) | |
| 39 | - * To delete code: Use empty REPLACE section | |
| 40 | -7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`; | |
| 41 | - | |
| 42 | -const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: | |
| 43 | -\`\`\` | |
| 44 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 45 | -\`\`\` | |
| 46 | - | |
| 47 | -${SEARCH_AND_REPLACE_RULES} | |
| 48 | - | |
| 49 | -Usage: | |
| 50 | -\`\`\` | |
| 51 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 52 | - | |
| 53 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 54 | -\`\`\` | |
| 55 | - | |
| 56 | -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`; | |
| 57 | - | |
| 58 | -/** | |
| 59 | - * This tool is in an experimental state. | |
| 60 | - * 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 | |
| 61 | - */ | |
| 62 | -export const searchAndReplaceInFileTool: Tool = { | |
| 63 | - type: "function", | |
| 64 | - displayTitle: "Edit File", | |
| 65 | - wouldLikeTo: "edit {{{ filepath }}}", | |
| 66 | - isCurrently: "editing {{{ filepath }}}", | |
| 67 | - hasAlready: "edited {{{ filepath }}}", | |
| 68 | - group: BUILT_IN_GROUP_NAME, | |
| 69 | - readonly: false, | |
| 70 | - isInstant: false, | |
| 71 | - function: { | |
| 72 | - name: BuiltInToolNames.SearchAndReplaceInFile, | |
| 73 | - 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}`, | |
| 74 | - parameters: { | |
| 75 | - type: "object", | |
| 76 | - required: ["filepath", "diffs"], | |
| 77 | - properties: { | |
| 78 | - filepath: { | |
| 79 | - type: "string", | |
| 80 | - description: `The path of the file to modify, relative to the root of the workspace.`, | |
| 81 | - }, | |
| 82 | - diffs: { | |
| 83 | - type: "array", | |
| 84 | - items: { | |
| 85 | - type: "string", | |
| 86 | - }, | |
| 87 | - description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION, | |
| 88 | - }, | |
| 89 | - }, | |
| 90 | - }, | |
| 91 | - }, | |
| 92 | - systemMessageDescription: { | |
| 93 | - prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. | |
| 94 | -Each block should follow this format: | |
| 95 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 96 | - | |
| 97 | -${SEARCH_AND_REPLACE_RULES} | |
| 98 | - | |
| 99 | - For example, you could respond with:`, | |
| 100 | - exampleArgs: [ | |
| 101 | - ["filepath", "path/to/file.ts"], | |
| 102 | - [ | |
| 103 | - "diffs", | |
| 104 | - `[ | |
| 105 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}", | |
| 106 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}" | |
| 107 | -]`, | |
| 108 | - ], | |
| 109 | - ], | |
| 110 | - }, | |
| 111 | - defaultToolPolicy: "allowedWithPermission", | |
| 112 | -}; |
modified core/tools/definitions/searchWeb.ts +1 −0
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, |
| 31 | 31 | exampleArgs: [["query", "What is the current weather in San Francisco?"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "GlobeAltIcon", | |
| 33 | 34 | }; |
added core/tools/definitions/singleFindAndReplace.ts +73 −0
| @@ -0,0 +1,73 @@ | ||
| 1 | +import { Tool } from "../.."; | |
| 2 | +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; | |
| 4 | + | |
| 5 | +export interface SingleFindAndReplaceArgs { | |
| 6 | + filepath: string; | |
| 7 | + old_string: string; | |
| 8 | + new_string: string; | |
| 9 | + replace_all?: boolean; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export const singleFindAndReplaceTool: Tool = { | |
| 13 | + type: "function", | |
| 14 | + displayTitle: "Find and Replace", | |
| 15 | + wouldLikeTo: "edit {{{ filepath }}}", | |
| 16 | + isCurrently: "editing {{{ filepath }}}", | |
| 17 | + hasAlready: "edited {{{ filepath }}}", | |
| 18 | + group: BUILT_IN_GROUP_NAME, | |
| 19 | + readonly: false, | |
| 20 | + isInstant: false, | |
| 21 | + function: { | |
| 22 | + name: BuiltInToolNames.SingleFindAndReplace, | |
| 23 | + description: `Performs exact string replacements in a file. | |
| 24 | + | |
| 25 | +IMPORTANT: | |
| 26 | +- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. | |
| 27 | +- ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION} | |
| 28 | +- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation. | |
| 29 | +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. | |
| 30 | +- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance. | |
| 31 | + | |
| 32 | +WARNINGS: | |
| 33 | +- 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\`. | |
| 34 | +- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`, | |
| 35 | + parameters: { | |
| 36 | + type: "object", | |
| 37 | + required: ["filepath", "old_string", "new_string"], | |
| 38 | + properties: { | |
| 39 | + filepath: { | |
| 40 | + type: "string", | |
| 41 | + description: | |
| 42 | + "The path to the file to modify, relative to the root of the workspace", | |
| 43 | + }, | |
| 44 | + old_string: { | |
| 45 | + type: "string", | |
| 46 | + description: | |
| 47 | + "The text to replace - must be exact including whitespace/indentation", | |
| 48 | + }, | |
| 49 | + new_string: { | |
| 50 | + type: "string", | |
| 51 | + description: | |
| 52 | + "The text to replace it with (MUST be different from old_string)", | |
| 53 | + }, | |
| 54 | + replace_all: { | |
| 55 | + type: "boolean", | |
| 56 | + description: "Replace all occurrences of old_string (default false)", | |
| 57 | + }, | |
| 58 | + }, | |
| 59 | + }, | |
| 60 | + }, | |
| 61 | + systemMessageDescription: { | |
| 62 | + prefix: `To perform exact string replacements in files, use the ${BuiltInToolNames.SingleFindAndReplace} tool with a filepath (relative to the root of the workspace) and the strings to find and replace. | |
| 63 | + | |
| 64 | + For example, you could respond with:`, | |
| 65 | + exampleArgs: [ | |
| 66 | + ["filepath", "path/to/file.ts"], | |
| 67 | + ["old_string", "const oldVariable = 'value'"], | |
| 68 | + ["new_string", "const newVariable = 'updated'"], | |
| 69 | + ["replace_all", "false"], | |
| 70 | + ], | |
| 71 | + }, | |
| 72 | + defaultToolPolicy: "allowedWithPermission", | |
| 73 | +}; |
modified core/tools/definitions/toolDefinitions.test.ts +3 −0
| @@ -7,6 +7,9 @@ | ||
| 7 | 7 | const mockParams: ConfigDependentToolParams = { |
| 8 | 8 | rules: [], |
| 9 | 9 | enableExperimentalTools: false, |
| 10 | + isSignedIn: false, | |
| 11 | + isRemote: false, | |
| 12 | + modelName: "a model", | |
| 10 | 13 | }; |
| 11 | 14 | |
| 12 | 15 | // Helper function to get the actual tool object |
modified core/tools/definitions/viewDiff.ts +1 −0
| @@ -23,4 +23,5 @@ | ||
| 23 | 23 | prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, |
| 24 | 24 | }, |
| 25 | 25 | defaultToolPolicy: "allowedWithoutPermission", |
| 26 | + toolCallIcon: "CodeBracketIcon", | |
| 26 | 27 | }; |
modified core/tools/definitions/viewRepoMap.ts +1 −0
| @@ -23,4 +23,5 @@ | ||
| 23 | 23 | prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, |
| 24 | 24 | }, |
| 25 | 25 | defaultToolPolicy: "allowedWithPermission", |
| 26 | + toolCallIcon: "MapIcon", | |
| 26 | 27 | }; |
modified core/tools/definitions/viewSubdirectory.ts +1 −0
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | exampleArgs: [["directory_path", "path/to/subdirectory"]], |
| 31 | 31 | }, |
| 32 | 32 | defaultToolPolicy: "allowedWithPermission", |
| 33 | + toolCallIcon: "FolderOpenIcon", | |
| 33 | 34 | }; |
modified core/tools/implementations/fetchUrlContent.ts +2 −2
| @@ -27,8 +27,8 @@ | ||
| 27 | 27 | // Add truncation warning if needed |
| 28 | 28 | if (truncatedUrls.length > 0) { |
| 29 | 29 | processedItems.push({ |
| 30 | - name: "URL content truncation warning", | |
| 31 | - description: "Informs that URL content was truncated", | |
| 30 | + name: "Truncation warning", | |
| 31 | + description: "", | |
| 32 | 32 | content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`, |
| 33 | 33 | }); |
| 34 | 34 | } |
modified core/tools/implementations/fetchUrlContent.vitest.ts +2 −2
| @@ -54,7 +54,7 @@ | ||
| 54 | 54 | |
| 55 | 55 | expect(result).toHaveLength(2); // Original item + warning |
| 56 | 56 | expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); |
| 57 | - expect(result[1].name).toBe("URL content truncation warning"); | |
| 57 | + expect(result[1].name).toBe("Truncation warning"); | |
| 58 | 58 | expect(result[1].content).toContain("was truncated"); |
| 59 | 59 | expect(result[1].content).toContain("20000 character limit"); |
| 60 | 60 | }); |
| @@ -87,5 +87,5 @@ | ||
| 87 | 87 | expect(result).toHaveLength(3); // Two original items + warning |
| 88 | 88 | expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); |
| 89 | 89 | expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); |
| 90 | - expect(result[2].name).toBe("URL content truncation warning"); | |
| 90 | + expect(result[2].name).toBe("Truncation warning"); | |
| 91 | 91 | }); |
modified core/tools/implementations/globSearch.ts +12 −2
| @@ -10,10 +10,20 @@ | ||
| 10 | 10 | pattern, |
| 11 | 11 | MAX_AGENT_GLOB_RESULTS, |
| 12 | 12 | ); |
| 13 | + | |
| 14 | + if (results.length === 0) { | |
| 15 | + return [ | |
| 16 | + { | |
| 17 | + name: "File results", | |
| 18 | + description: "glob search", | |
| 19 | + content: "The glob search returned no results.", | |
| 20 | + }, | |
| 21 | + ]; | |
| 22 | + } | |
| 13 | 23 | const contextItems: ContextItem[] = [ |
| 14 | 24 | { |
| 15 | 25 | name: "File results", |
| 16 | - description: "Results from file glob search", | |
| 26 | + description: "glob search", | |
| 17 | 27 | content: results.join("\n"), |
| 18 | 28 | }, |
| 19 | 29 | ]; |
| @@ -22,7 +32,7 @@ | ||
| 22 | 32 | if (results.length === MAX_AGENT_GLOB_RESULTS) { |
| 23 | 33 | contextItems.push({ |
| 24 | 34 | name: "Truncation warning", |
| 25 | - description: "Inform the model that results were truncated", | |
| 35 | + description: "", | |
| 26 | 36 | content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`, |
| 27 | 37 | }); |
| 28 | 38 | } |
modified core/tools/implementations/grepSearch.ts +54 −14
| @@ -1,18 +1,15 @@ | ||
| 1 | 1 | import { ToolImpl } from "."; |
| 2 | 2 | import { ContextItem } from "../.."; |
| 3 | 3 | import { formatGrepSearchResults } from "../../util/grepSearch"; |
| 4 | +import { prepareQueryForRipgrep } from "../../util/regexValidator"; | |
| 4 | 5 | import { getStringArg } from "../parseArgs"; |
| 5 | 6 | |
| 6 | 7 | const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; |
| 7 | -const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now | |
| 8 | +const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 7500; // ~1500 tokens, will keep truncation simply for now | |
| 8 | 9 | |
| 9 | 10 | function splitGrepResultsByFile(content: string): ContextItem[] { |
| 10 | 11 | const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; |
| 11 | 12 | |
| 12 | - if (matches.length === 0) { | |
| 13 | - return []; | |
| 14 | - } | |
| 15 | - | |
| 16 | 13 | const contextItems: ContextItem[] = []; |
| 17 | 14 | |
| 18 | 15 | for (let i = 0; i < matches.length; i++) { |
| @@ -42,16 +39,48 @@ | ||
| 42 | 39 | } |
| 43 | 40 | |
| 44 | 41 | export const grepSearchImpl: ToolImpl = async (args, extras) => { |
| 45 | - const query = getStringArg(args, "query"); | |
| 46 | - | |
| 47 | - const results = await extras.ide.getSearchResults( | |
| 48 | - query, | |
| 49 | - DEFAULT_GREP_SEARCH_RESULTS_LIMIT, | |
| 50 | - ); | |
| 42 | + const rawQuery = getStringArg(args, "query"); | |
| 43 | + | |
| 44 | + const { query, warning } = prepareQueryForRipgrep(rawQuery); | |
| 45 | + | |
| 46 | + let results: string; | |
| 47 | + try { | |
| 48 | + results = await extras.ide.getSearchResults( | |
| 49 | + query, | |
| 50 | + DEFAULT_GREP_SEARCH_RESULTS_LIMIT, | |
| 51 | + ); | |
| 52 | + } catch (error) { | |
| 53 | + const errorMessage = error instanceof Error ? error.message : String(error); | |
| 54 | + | |
| 55 | + // Helpful error for common ripgrep exit code | |
| 56 | + if (errorMessage.includes("Process exited with code 2")) { | |
| 57 | + return [ | |
| 58 | + { | |
| 59 | + name: "Search error", | |
| 60 | + description: "The search query could not be processed", | |
| 61 | + content: `The search failed due to an invalid regex pattern.\n\nOriginal query: ${rawQuery}\nProcessed query: ${query}\n\nError: ${errorMessage}\n\nTip: If you're searching for literal text with special characters, the query was automatically escaped. If you need regex patterns, ensure they use proper regex syntax.`, | |
| 62 | + }, | |
| 63 | + ]; | |
| 64 | + } | |
| 65 | + | |
| 66 | + throw error; | |
| 67 | + } | |
| 68 | + | |
| 51 | 69 | const { formatted, numResults, truncated } = formatGrepSearchResults( |
| 52 | 70 | results, |
| 53 | 71 | DEFAULT_GREP_SEARCH_CHAR_LIMIT, |
| 54 | 72 | ); |
| 73 | + | |
| 74 | + if (numResults === 0) { | |
| 75 | + return [ | |
| 76 | + { | |
| 77 | + name: "Search results", | |
| 78 | + description: "Results from grep search", | |
| 79 | + content: "The search returned no results.", | |
| 80 | + }, | |
| 81 | + ]; | |
| 82 | + } | |
| 83 | + | |
| 55 | 84 | const truncationReasons: string[] = []; |
| 56 | 85 | if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) { |
| 57 | 86 | truncationReasons.push( |
| @@ -64,7 +93,7 @@ | ||
| 64 | 93 | ); |
| 65 | 94 | } |
| 66 | 95 | |
| 67 | - let contextItems: ContextItem[] = []; | |
| 96 | + let contextItems: ContextItem[]; | |
| 68 | 97 | |
| 69 | 98 | const splitByFile: boolean = args?.splitByFile || false; |
| 70 | 99 | if (splitByFile) { |
| @@ -79,10 +108,21 @@ | ||
| 79 | 108 | ]; |
| 80 | 109 | } |
| 81 | 110 | |
| 111 | + // Add warnings about query modifications or truncation | |
| 112 | + const warnings: string[] = []; | |
| 113 | + if (warning) { | |
| 114 | + warnings.push(warning); | |
| 115 | + } | |
| 116 | + if (truncationReasons.length > 0) { | |
| 117 | + warnings.push( | |
| 118 | + `Results were truncated because ${truncationReasons.join(" and ")}`, | |
| 119 | + ); | |
| 120 | + } | |
| 121 | + | |
| 82 | 122 | if (truncationReasons.length > 0) { |
| 83 | 123 | contextItems.push({ |
| 84 | - name: "Search truncation warning", | |
| 85 | - description: "Informs the model that search results were truncated", | |
| 124 | + name: "Truncation warning", | |
| 125 | + description: "", | |
| 86 | 126 | content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`, |
| 87 | 127 | }); |
| 88 | 128 | } |
modified core/tools/implementations/lsTool.ts +5 −2
| @@ -1,3 +1,5 @@ | ||
| 1 | +import ignore from "ignore"; | |
| 2 | + | |
| 1 | 3 | import { ToolImpl } from "."; |
| 2 | 4 | import { walkDir } from "../../indexing/walkDir"; |
| 3 | 5 | import { resolveRelativePathInDir } from "../../util/ideUtils"; |
| @@ -27,6 +29,7 @@ | ||
| 27 | 29 | returnRelativeUrisPaths: true, |
| 28 | 30 | include: "both", |
| 29 | 31 | recursive: args?.recursive ?? false, |
| 32 | + overrideDefaultIgnores: ignore(), // Show all directories including dist/, build/, etc. | |
| 30 | 33 | }); |
| 31 | 34 | |
| 32 | 35 | const lines = entries.slice(0, MAX_LS_TOOL_LINES); |
| @@ -50,8 +53,8 @@ | ||
| 50 | 53 | warningContent += ". Try using a non-recursive search"; |
| 51 | 54 | } |
| 52 | 55 | contextItems.push({ |
| 53 | - name: "ls truncation warning", | |
| 54 | - description: "Informs the model that ls results were truncated", | |
| 56 | + name: "Truncation warning", | |
| 57 | + description: "", | |
| 55 | 58 | content: warningContent, |
| 56 | 59 | }); |
| 57 | 60 | } |
modified core/tools/implementations/readCurrentlyOpenFile.ts +3 −1
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | import { getUriDescription } from "../../util/uri"; |
| 2 | 2 | |
| 3 | 3 | import { ToolImpl } from "."; |
| 4 | +import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; | |
| 4 | 5 | import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; |
| 5 | 6 | |
| 6 | -export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { | |
| 7 | +export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => { | |
| 7 | 8 | const result = await extras.ide.getCurrentFile(); |
| 8 | 9 | |
| 9 | 10 | if (result) { |
| 11 | + throwIfFileIsSecurityConcern(result.path); | |
| 10 | 12 | await throwIfFileExceedsHalfOfContext( |
| 11 | 13 | result.path, |
| 12 | 14 | result.contents, |
modified core/tools/implementations/readFile.ts +2 −0
| @@ -2,11 +2,13 @@ | ||
| 2 | 2 | import { getUriPathBasename } from "../../util/uri"; |
| 3 | 3 | |
| 4 | 4 | import { ToolImpl } from "."; |
| 5 | +import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; | |
| 5 | 6 | import { getStringArg } from "../parseArgs"; |
| 6 | 7 | import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; |
| 7 | 8 | |
| 8 | 9 | export const readFileImpl: ToolImpl = async (args, extras) => { |
| 9 | 10 | const filepath = getStringArg(args, "filepath"); |
| 11 | + throwIfFileIsSecurityConcern(filepath); | |
| 10 | 12 | |
| 11 | 13 | const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); |
| 12 | 14 | if (!firstUriMatch) { |
added core/tools/implementations/readFileRange.integration.vitest.ts +204 −0
| @@ -0,0 +1,204 @@ | ||
| 1 | +import { expect, test, vi } from "vitest"; | |
| 2 | +import { ToolExtras } from "../.."; | |
| 3 | +import { readFileRangeImpl } from "./readFileRange"; | |
| 4 | + | |
| 5 | +// Mock the dependencies | |
| 6 | +vi.mock("../../util/ideUtils", () => ({ | |
| 7 | + resolveRelativePathInDir: vi.fn(), | |
| 8 | +})); | |
| 9 | + | |
| 10 | +vi.mock("../../util/uri", () => ({ | |
| 11 | + getUriPathBasename: vi.fn(), | |
| 12 | +})); | |
| 13 | + | |
| 14 | +vi.mock("./readFileLimit", () => ({ | |
| 15 | + throwIfFileExceedsHalfOfContext: vi.fn(), | |
| 16 | +})); | |
| 17 | + | |
| 18 | +test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => { | |
| 19 | + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); | |
| 20 | + const { getUriPathBasename } = await import("../../util/uri"); | |
| 21 | + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); | |
| 22 | + | |
| 23 | + // Mock the utility functions | |
| 24 | + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); | |
| 25 | + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); | |
| 26 | + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); | |
| 27 | + | |
| 28 | + // Test case 1: Start line beyond end of file | |
| 29 | + const mockIdeOutOfBounds = { | |
| 30 | + readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string | |
| 31 | + }; | |
| 32 | + | |
| 33 | + const mockExtras1 = { | |
| 34 | + ide: mockIdeOutOfBounds, | |
| 35 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 36 | + } as unknown as ToolExtras; | |
| 37 | + | |
| 38 | + const result1 = await readFileRangeImpl( | |
| 39 | + { | |
| 40 | + filepath: "test.txt", | |
| 41 | + startLine: 100, // Beyond end of file | |
| 42 | + endLine: 105, | |
| 43 | + }, | |
| 44 | + mockExtras1, | |
| 45 | + ); | |
| 46 | + | |
| 47 | + expect(result1).toHaveLength(1); | |
| 48 | + expect(result1[0].content).toBe(""); | |
| 49 | + expect(result1[0].description).toBe("test.txt (lines 100-105)"); | |
| 50 | + | |
| 51 | + // Test case 2: End line beyond end of file | |
| 52 | + const mockIdePartialRange = { | |
| 53 | + readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content | |
| 54 | + }; | |
| 55 | + | |
| 56 | + const mockExtras2 = { | |
| 57 | + ide: mockIdePartialRange, | |
| 58 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 59 | + } as unknown as ToolExtras; | |
| 60 | + | |
| 61 | + const result2 = await readFileRangeImpl( | |
| 62 | + { | |
| 63 | + filepath: "test.txt", | |
| 64 | + startLine: 5, | |
| 65 | + endLine: 100, // Beyond end of file | |
| 66 | + }, | |
| 67 | + mockExtras2, | |
| 68 | + ); | |
| 69 | + | |
| 70 | + expect(result2).toHaveLength(1); | |
| 71 | + expect(result2[0].content).toBe("line5\nline6"); | |
| 72 | + expect(result2[0].description).toBe("test.txt (lines 5-100)"); | |
| 73 | + | |
| 74 | + // Verify that IDE methods were called with correct 0-based ranges | |
| 75 | + expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith( | |
| 76 | + "file:///test.txt", | |
| 77 | + { | |
| 78 | + start: { line: 99, character: 0 }, // 100 - 1 | |
| 79 | + end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1 | |
| 80 | + }, | |
| 81 | + ); | |
| 82 | + | |
| 83 | + expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith( | |
| 84 | + "file:///test.txt", | |
| 85 | + { | |
| 86 | + start: { line: 4, character: 0 }, // 5 - 1 | |
| 87 | + end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1 | |
| 88 | + }, | |
| 89 | + ); | |
| 90 | +}); | |
| 91 | + | |
| 92 | +test("readFileRangeImpl validates line number constraints", async () => { | |
| 93 | + const mockExtras = { | |
| 94 | + ide: { readRangeInFile: vi.fn(), readFile: vi.fn() }, | |
| 95 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 96 | + } as unknown as ToolExtras; | |
| 97 | + | |
| 98 | + // Test startLine < 1 (invalid) | |
| 99 | + await expect( | |
| 100 | + readFileRangeImpl( | |
| 101 | + { | |
| 102 | + filepath: "test.txt", | |
| 103 | + startLine: 0, | |
| 104 | + endLine: 5, | |
| 105 | + }, | |
| 106 | + mockExtras, | |
| 107 | + ), | |
| 108 | + ).rejects.toThrow("startLine must be 1 or greater"); | |
| 109 | + | |
| 110 | + // Test negative startLine (no longer supported) | |
| 111 | + await expect( | |
| 112 | + readFileRangeImpl( | |
| 113 | + { | |
| 114 | + filepath: "test.txt", | |
| 115 | + startLine: -1, | |
| 116 | + endLine: 5, | |
| 117 | + }, | |
| 118 | + mockExtras, | |
| 119 | + ), | |
| 120 | + ).rejects.toThrow("Negative line numbers are not supported"); | |
| 121 | + | |
| 122 | + // Test endLine < 1 (invalid) | |
| 123 | + await expect( | |
| 124 | + readFileRangeImpl( | |
| 125 | + { | |
| 126 | + filepath: "test.txt", | |
| 127 | + startLine: 1, | |
| 128 | + endLine: 0, | |
| 129 | + }, | |
| 130 | + mockExtras, | |
| 131 | + ), | |
| 132 | + ).rejects.toThrow("endLine must be 1 or greater"); | |
| 133 | + | |
| 134 | + // Test negative endLine (no longer supported) | |
| 135 | + await expect( | |
| 136 | + readFileRangeImpl( | |
| 137 | + { | |
| 138 | + filepath: "test.txt", | |
| 139 | + startLine: 1, | |
| 140 | + endLine: -1, | |
| 141 | + }, | |
| 142 | + mockExtras, | |
| 143 | + ), | |
| 144 | + ).rejects.toThrow("Negative line numbers are not supported"); | |
| 145 | + | |
| 146 | + // Test endLine < startLine | |
| 147 | + await expect( | |
| 148 | + readFileRangeImpl( | |
| 149 | + { | |
| 150 | + filepath: "test.txt", | |
| 151 | + startLine: 10, | |
| 152 | + endLine: 5, | |
| 153 | + }, | |
| 154 | + mockExtras, | |
| 155 | + ), | |
| 156 | + ).rejects.toThrow( | |
| 157 | + "endLine (5) must be greater than or equal to startLine (10)", | |
| 158 | + ); | |
| 159 | +}); | |
| 160 | + | |
| 161 | +test("readFileRangeImpl handles normal ranges correctly", async () => { | |
| 162 | + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); | |
| 163 | + const { getUriPathBasename } = await import("../../util/uri"); | |
| 164 | + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); | |
| 165 | + | |
| 166 | + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); | |
| 167 | + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); | |
| 168 | + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); | |
| 169 | + | |
| 170 | + const mockIde = { | |
| 171 | + readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"), | |
| 172 | + }; | |
| 173 | + | |
| 174 | + const mockExtras = { | |
| 175 | + ide: mockIde, | |
| 176 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 177 | + } as unknown as ToolExtras; | |
| 178 | + | |
| 179 | + const result = await readFileRangeImpl( | |
| 180 | + { | |
| 181 | + filepath: "src/test.py", | |
| 182 | + startLine: 2, | |
| 183 | + endLine: 4, | |
| 184 | + }, | |
| 185 | + mockExtras, | |
| 186 | + ); | |
| 187 | + | |
| 188 | + expect(result).toHaveLength(1); | |
| 189 | + expect(result[0]).toEqual({ | |
| 190 | + name: "test.txt", | |
| 191 | + description: "src/test.py (lines 2-4)", | |
| 192 | + content: "line2\nline3\nline4", | |
| 193 | + uri: { | |
| 194 | + type: "file", | |
| 195 | + value: "file:///test.txt", | |
| 196 | + }, | |
| 197 | + }); | |
| 198 | + | |
| 199 | + // Verify correct 0-based conversion | |
| 200 | + expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", { | |
| 201 | + start: { line: 1, character: 0 }, // 2 - 1 | |
| 202 | + end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1 | |
| 203 | + }); | |
| 204 | +}); |
added core/tools/implementations/readFileRange.ts +68 −0
| @@ -0,0 +1,68 @@ | ||
| 1 | +import { resolveRelativePathInDir } from "../../util/ideUtils"; | |
| 2 | +import { getUriPathBasename } from "../../util/uri"; | |
| 3 | + | |
| 4 | +import { ToolImpl } from "."; | |
| 5 | +import { getNumberArg, getStringArg } from "../parseArgs"; | |
| 6 | +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; | |
| 7 | + | |
| 8 | +export const readFileRangeImpl: ToolImpl = async (args, extras) => { | |
| 9 | + const filepath = getStringArg(args, "filepath"); | |
| 10 | + const startLine = getNumberArg(args, "startLine"); | |
| 11 | + const endLine = getNumberArg(args, "endLine"); | |
| 12 | + | |
| 13 | + // Validate that line numbers are positive integers | |
| 14 | + if (startLine < 1) { | |
| 15 | + throw new Error( | |
| 16 | + "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", | |
| 17 | + ); | |
| 18 | + } | |
| 19 | + if (endLine < 1) { | |
| 20 | + throw new Error( | |
| 21 | + "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", | |
| 22 | + ); | |
| 23 | + } | |
| 24 | + if (endLine < startLine) { | |
| 25 | + throw new Error( | |
| 26 | + `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, | |
| 27 | + ); | |
| 28 | + } | |
| 29 | + | |
| 30 | + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); | |
| 31 | + if (!firstUriMatch) { | |
| 32 | + throw new Error( | |
| 33 | + `File "${filepath}" does not exist. You might want to check the path and try again.`, | |
| 34 | + ); | |
| 35 | + } | |
| 36 | + | |
| 37 | + // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) | |
| 38 | + const content = await extras.ide.readRangeInFile(firstUriMatch, { | |
| 39 | + start: { | |
| 40 | + line: startLine - 1, // Convert from 1-based to 0-based | |
| 41 | + character: 0, | |
| 42 | + }, | |
| 43 | + end: { | |
| 44 | + line: endLine - 1, // Convert from 1-based to 0-based | |
| 45 | + character: Number.MAX_SAFE_INTEGER, // Read to end of line | |
| 46 | + }, | |
| 47 | + }); | |
| 48 | + | |
| 49 | + await throwIfFileExceedsHalfOfContext( | |
| 50 | + filepath, | |
| 51 | + content, | |
| 52 | + extras.config.selectedModelByRole.chat, | |
| 53 | + ); | |
| 54 | + | |
| 55 | + const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; | |
| 56 | + | |
| 57 | + return [ | |
| 58 | + { | |
| 59 | + name: getUriPathBasename(firstUriMatch), | |
| 60 | + description: rangeDescription, | |
| 61 | + content, | |
| 62 | + uri: { | |
| 63 | + type: "file", | |
| 64 | + value: firstUriMatch, | |
| 65 | + }, | |
| 66 | + }, | |
| 67 | + ]; | |
| 68 | +}; |
added core/tools/implementations/readFileRange.vitest.ts +60 −0
| @@ -0,0 +1,60 @@ | ||
| 1 | +import { expect, test } from "vitest"; | |
| 2 | +import { getNumberArg } from "../parseArgs"; | |
| 3 | + | |
| 4 | +test("readFileRange should validate positive line number arguments", () => { | |
| 5 | + // Test positive startLine validation | |
| 6 | + expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow(); | |
| 7 | + expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow(); | |
| 8 | + expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow(); | |
| 9 | + | |
| 10 | + // Test positive endLine validation | |
| 11 | + expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow(); | |
| 12 | + expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow(); | |
| 13 | + expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow(); | |
| 14 | + | |
| 15 | + // Test missing arguments | |
| 16 | + expect(() => getNumberArg({}, "startLine")).toThrow( | |
| 17 | + "Argument `startLine` is required (type number)", | |
| 18 | + ); | |
| 19 | + expect(() => getNumberArg({}, "endLine")).toThrow( | |
| 20 | + "Argument `endLine` is required (type number)", | |
| 21 | + ); | |
| 22 | + | |
| 23 | + // Test invalid arguments | |
| 24 | + expect(() => | |
| 25 | + getNumberArg({ startLine: "not-a-number" }, "startLine"), | |
| 26 | + ).toThrow("Argument `startLine` must be a valid number"); | |
| 27 | + expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow( | |
| 28 | + "Argument `endLine` must be a valid number", | |
| 29 | + ); | |
| 30 | +}); | |
| 31 | + | |
| 32 | +test("readFileRange should handle line number conversion", () => { | |
| 33 | + // Test that our parsing function converts correctly | |
| 34 | + expect(getNumberArg({ line: 1 }, "line")).toBe(1); | |
| 35 | + expect(getNumberArg({ line: "5" }, "line")).toBe(5); | |
| 36 | + expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor | |
| 37 | + expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor | |
| 38 | +}); | |
| 39 | + | |
| 40 | +test("readFileRange parses negative numbers (validation happens in implementation)", () => { | |
| 41 | + // The parseArgs function should parse negative numbers correctly | |
| 42 | + // but the implementation will reject them with helpful error messages | |
| 43 | + expect(getNumberArg({ line: -1 }, "line")).toBe(-1); | |
| 44 | + expect(getNumberArg({ line: -10 }, "line")).toBe(-10); | |
| 45 | + expect(getNumberArg({ line: "-5" }, "line")).toBe(-5); | |
| 46 | +}); | |
| 47 | + | |
| 48 | +test("readFileRange handles out-of-bounds ranges gracefully", () => { | |
| 49 | + // IDE implementations handle out-of-bounds gracefully: | |
| 50 | + // - VS Code: Uses array.slice() which handles out-of-bounds gracefully | |
| 51 | + // - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds | |
| 52 | + // Both return empty content or available content without throwing errors | |
| 53 | + | |
| 54 | + expect(() => { | |
| 55 | + const startLine = getNumberArg({ startLine: 1000 }, "startLine"); | |
| 56 | + const endLine = getNumberArg({ endLine: 2000 }, "endLine"); | |
| 57 | + expect(startLine).toBe(1000); | |
| 58 | + expect(endLine).toBe(2000); | |
| 59 | + }).not.toThrow(); | |
| 60 | +}); |
deleted core/tools/implementations/runTerminalCommand.test.ts +0 −474
| @@ -1,474 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import * as childProcess from "node:child_process"; | |
| 3 | -import * as fs from "node:fs"; | |
| 4 | -import * as os from "node:os"; | |
| 5 | -import * as path from "node:path"; | |
| 6 | -import { IDE, ToolExtras } from "../.."; | |
| 7 | -import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; | |
| 8 | -import { runTerminalCommandImpl } from "./runTerminalCommand"; | |
| 9 | - | |
| 10 | -// We're using real child processes, so ensure these aren't mocked | |
| 11 | -jest.unmock("node:child_process"); | |
| 12 | -jest.unmock("node:util"); | |
| 13 | - | |
| 14 | -describe("runTerminalCommandImpl", () => { | |
| 15 | - // Setup mocks and spies | |
| 16 | - const mockGetIdeInfo = jest.fn(); | |
| 17 | - const mockGetWorkspaceDirs = jest.fn(); | |
| 18 | - const mockOnPartialOutput = jest.fn(); | |
| 19 | - const mockRunCommand = jest.fn(); | |
| 20 | - | |
| 21 | - // Use a simple approach to ensure background processes are terminated | |
| 22 | - let testPid: number | null = null; | |
| 23 | - | |
| 24 | - // Create a temp directory for our tests | |
| 25 | - const tempDir = fs.mkdtempSync( | |
| 26 | - path.join(os.tmpdir(), "terminal-command-test-"), | |
| 27 | - ); | |
| 28 | - | |
| 29 | - beforeEach(() => { | |
| 30 | - jest.resetAllMocks(); | |
| 31 | - | |
| 32 | - // Setup backgrounded processes handling - don't mock, just make sure it's empty | |
| 33 | - // Get any processes that might be already tracked and clear them | |
| 34 | - const processMap = (processBackgroundStates as any) | |
| 35 | - .processTerminalBackgroundStates; | |
| 36 | - if (processMap && typeof processMap.clear === "function") { | |
| 37 | - processMap.clear(); | |
| 38 | - } | |
| 39 | - | |
| 40 | - // Setup IDE mocks | |
| 41 | - mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); | |
| 42 | - mockGetWorkspaceDirs.mockReturnValue( | |
| 43 | - Promise.resolve([`file://${tempDir}`]), | |
| 44 | - ); | |
| 45 | - }); | |
| 46 | - | |
| 47 | - afterEach(async () => { | |
| 48 | - // Clean up any lingering test processes | |
| 49 | - if (testPid !== null) { | |
| 50 | - try { | |
| 51 | - // Platform-independent way to kill a process | |
| 52 | - if (process.platform === "win32") { | |
| 53 | - await new Promise((resolve) => { | |
| 54 | - childProcess.exec(`taskkill /F /PID ${testPid}`, () => | |
| 55 | - resolve(null), | |
| 56 | - ); | |
| 57 | - }); | |
| 58 | - } else { | |
| 59 | - process.kill(testPid); | |
| 60 | - } | |
| 61 | - } catch (e) { | |
| 62 | - // Process might already be gone, ignore | |
| 63 | - } | |
| 64 | - testPid = null; | |
| 65 | - } | |
| 66 | - }); | |
| 67 | - | |
| 68 | - afterAll(() => { | |
| 69 | - // Clean up the temp directory after tests | |
| 70 | - fs.rmSync(tempDir, { recursive: true, force: true }); | |
| 71 | - }); | |
| 72 | - | |
| 73 | - // Helper function to create a ToolExtras object | |
| 74 | - const createMockExtras = ( | |
| 75 | - overrides: Partial<{ | |
| 76 | - onPartialOutput?: jest.Mock; | |
| 77 | - remoteName?: string; | |
| 78 | - }> = {}, | |
| 79 | - ): ToolExtras => { | |
| 80 | - // Update IDE info if remoteName is provided | |
| 81 | - if (overrides.remoteName) { | |
| 82 | - mockGetIdeInfo.mockReturnValue( | |
| 83 | - Promise.resolve({ remoteName: overrides.remoteName }), | |
| 84 | - ); | |
| 85 | - } | |
| 86 | - | |
| 87 | - // Create a minimally compliant IDE mock | |
| 88 | - const mockIde = { | |
| 89 | - getIdeInfo: mockGetIdeInfo, | |
| 90 | - getWorkspaceDirs: mockGetWorkspaceDirs, | |
| 91 | - runCommand: mockRunCommand, | |
| 92 | - // Add stubs for other required IDE methods | |
| 93 | - getIdeSettings: jest.fn(), | |
| 94 | - getDiff: jest.fn(), | |
| 95 | - getClipboardContent: jest.fn(), | |
| 96 | - isTelemetryEnabled: jest.fn(), | |
| 97 | - readFile: jest.fn(), | |
| 98 | - writeFile: jest.fn(), | |
| 99 | - renameFile: jest.fn(), | |
| 100 | - deleteFile: jest.fn(), | |
| 101 | - globFiles: jest.fn(), | |
| 102 | - ls: jest.fn(), | |
| 103 | - }; | |
| 104 | - | |
| 105 | - // Create a base ToolExtras object with required properties | |
| 106 | - const baseExtras = { | |
| 107 | - ide: mockIde as unknown as IDE, | |
| 108 | - llm: {} as any, | |
| 109 | - fetch: {} as any, | |
| 110 | - tool: {} as any, | |
| 111 | - toolCallId: "test-tool-call", | |
| 112 | - } as ToolExtras; | |
| 113 | - | |
| 114 | - // Apply overrides | |
| 115 | - if (overrides.onPartialOutput) { | |
| 116 | - baseExtras.onPartialOutput = overrides.onPartialOutput; | |
| 117 | - } | |
| 118 | - | |
| 119 | - return baseExtras; | |
| 120 | - }; | |
| 121 | - | |
| 122 | - it("should execute a command synchronously and capture output", async () => { | |
| 123 | - // Use Node.js for cross-platform output generation | |
| 124 | - const command = `node -e "console.log('real test output')"`; | |
| 125 | - const args = { command, waitForCompletion: true }; | |
| 126 | - const extras = createMockExtras(); | |
| 127 | - | |
| 128 | - const result = await runTerminalCommandImpl(args, extras); | |
| 129 | - | |
| 130 | - // Verify real command output | |
| 131 | - expect(result).toHaveLength(1); | |
| 132 | - expect(result[0].name).toBe("Terminal"); | |
| 133 | - expect(result[0].description).toBe("Terminal command output"); | |
| 134 | - expect(result[0].content).toContain("real test output"); | |
| 135 | - // Verify status field indicates successful completion | |
| 136 | - expect(result[0].status).toBe("Command completed"); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should stream output when onPartialOutput is provided", async () => { | |
| 140 | - // This test uses Node to create a command that outputs data incrementally | |
| 141 | - const command = `node -e " | |
| 142 | - console.log('first output'); | |
| 143 | - setTimeout(() => { | |
| 144 | - console.log('second output'); | |
| 145 | - console.error('error output'); | |
| 146 | - }, 50); | |
| 147 | - "`; | |
| 148 | - | |
| 149 | - const args = { command, waitForCompletion: true }; | |
| 150 | - const mockOutputFn = jest.fn(); | |
| 151 | - const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 152 | - | |
| 153 | - // Execute the command with streaming | |
| 154 | - const result = await runTerminalCommandImpl(args, extras); | |
| 155 | - | |
| 156 | - // Verify onPartialOutput was called with increasing content | |
| 157 | - expect(mockOutputFn).toHaveBeenCalled(); | |
| 158 | - | |
| 159 | - // Verify final result has all output | |
| 160 | - expect(result[0].content).toContain("first output"); | |
| 161 | - expect(result[0].content).toContain("second output"); | |
| 162 | - expect(result[0].content).toContain("error output"); | |
| 163 | - // Verify status field indicates successful completion | |
| 164 | - expect(result[0].status).toBe("Command completed"); | |
| 165 | - | |
| 166 | - // Verify that initial streaming updates have empty status for regular commands | |
| 167 | - const firstCall = mockOutputFn.mock.calls[0][0]; | |
| 168 | - if (firstCall && typeof firstCall === "object") { | |
| 169 | - const contextItems = (firstCall as any).contextItems; | |
| 170 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 171 | - // For commands with waitForCompletion=true, status should be empty while streaming | |
| 172 | - expect(contextItems[0].status).toBe(""); | |
| 173 | - } | |
| 174 | - } | |
| 175 | - }); | |
| 176 | - | |
| 177 | - it("should run commands in background when waitForCompletion is false", async () => { | |
| 178 | - // Create a self-identifying background process that writes its PID | |
| 179 | - // to a file we can access to kill it later | |
| 180 | - const pidFile = path.join(tempDir, "test-pid.txt"); | |
| 181 | - | |
| 182 | - // This script creates a long-running process and writes its PID to our file | |
| 183 | - // Using a fixed duration timeout so we can be sure to clean it up | |
| 184 | - const command = `node -e " | |
| 185 | - const fs = require('fs'); | |
| 186 | - console.log('starting background process with PID: ' + process.pid); | |
| 187 | - fs.writeFileSync('${pidFile}', process.pid.toString()); | |
| 188 | - setTimeout(() => { | |
| 189 | - console.log('background process completed'); | |
| 190 | - }, 500); | |
| 191 | - "`; | |
| 192 | - | |
| 193 | - const args = { command, waitForCompletion: false }; | |
| 194 | - const mockOutputFn = jest.fn(); | |
| 195 | - const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 196 | - | |
| 197 | - const result = await runTerminalCommandImpl(args, extras); | |
| 198 | - | |
| 199 | - // Result should indicate background running in either content or status | |
| 200 | - expect(result[0].content || result[0].status).toContain( | |
| 201 | - "running in the background", | |
| 202 | - ); | |
| 203 | - // Verify status field indicates background running | |
| 204 | - expect(result[0].status).toBe("Command is running in the background..."); | |
| 205 | - | |
| 206 | - // Initial notification should indicate background running | |
| 207 | - expect(mockOutputFn).toHaveBeenCalled(); | |
| 208 | - // Check the first call contains background running message | |
| 209 | - const firstCallData = mockOutputFn.mock.calls[0][0]; | |
| 210 | - if (firstCallData && typeof firstCallData === "object") { | |
| 211 | - const contextItems = (firstCallData as any).contextItems; | |
| 212 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 213 | - expect(contextItems[0].content).toContain(""); | |
| 214 | - expect(contextItems[0].status).toMatch( | |
| 215 | - /Command is running in the background.../, | |
| 216 | - ); | |
| 217 | - } | |
| 218 | - } | |
| 219 | - | |
| 220 | - // Wait a bit to make sure the PID file is written | |
| 221 | - await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 222 | - | |
| 223 | - // Read the PID file to get the process ID so we can kill it later | |
| 224 | - if (fs.existsSync(pidFile)) { | |
| 225 | - testPid = Number(fs.readFileSync(pidFile, "utf-8")); | |
| 226 | - } | |
| 227 | - | |
| 228 | - // Wait a bit longer for the process to complete and onPartialOutput to be called again | |
| 229 | - await new Promise((resolve) => setTimeout(resolve, 400)); | |
| 230 | - | |
| 231 | - // Check for background process completion message in mockOutputFn calls | |
| 232 | - // Note: This is optional and depends on timing, so we don't want to strictly enforce it | |
| 233 | - let foundCompletionMessage = false; | |
| 234 | - | |
| 235 | - for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { | |
| 236 | - const call = mockOutputFn.mock.calls[i][0]; | |
| 237 | - if (call && typeof call === "object") { | |
| 238 | - const contextItems = (call as any).contextItems; | |
| 239 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 240 | - if ( | |
| 241 | - contextItems[0].status === "\nBackground command completed" || | |
| 242 | - (contextItems[0].status && | |
| 243 | - contextItems[0].status.includes("Background command")) | |
| 244 | - ) { | |
| 245 | - foundCompletionMessage = true; | |
| 246 | - break; | |
| 247 | - } | |
| 248 | - } | |
| 249 | - } | |
| 250 | - } | |
| 251 | - | |
| 252 | - // If we found any completion message in the output, great! | |
| 253 | - // But we won't fail the test if we didn't, since it may be timing-dependent | |
| 254 | - if (mockOutputFn.mock.calls.length > 1) { | |
| 255 | - expect(foundCompletionMessage || true).toBeTruthy(); | |
| 256 | - } | |
| 257 | - }); | |
| 258 | - | |
| 259 | - it("should handle remote environments", async () => { | |
| 260 | - // We'll keep mocking for remote environments as we can't test those directly | |
| 261 | - const args = { command: "echo 'test'", waitForCompletion: true }; | |
| 262 | - const extras = createMockExtras({ remoteName: "ssh" }); | |
| 263 | - | |
| 264 | - const result = await runTerminalCommandImpl(args, extras); | |
| 265 | - | |
| 266 | - // In remote environments, it should use the IDE's runCommand | |
| 267 | - expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); | |
| 268 | - // Match the actual output message | |
| 269 | - expect(result[0].content).toContain("Terminal output not available"); | |
| 270 | - expect(result[0].content).toContain("SSH environments"); | |
| 271 | - // Verify status field indicates command failed in remote environments | |
| 272 | - expect(result[0].status).toBe("Command failed"); | |
| 273 | - }); | |
| 274 | - | |
| 275 | - it("should handle errors when executing invalid commands", async () => { | |
| 276 | - // Use a command that should fail on any platform | |
| 277 | - const args = { | |
| 278 | - command: "non-existent-command-xyz", | |
| 279 | - waitForCompletion: true, | |
| 280 | - }; | |
| 281 | - const extras = createMockExtras(); | |
| 282 | - | |
| 283 | - const result = await runTerminalCommandImpl(args, extras); | |
| 284 | - | |
| 285 | - expect(result[0].name).toBe("Terminal"); | |
| 286 | - expect(result[0].description).toBe("Terminal command output"); | |
| 287 | - | |
| 288 | - // The exact error message varies by platform, but should contain error information | |
| 289 | - const errorContent = result[0].content; | |
| 290 | - expect( | |
| 291 | - errorContent.includes("Command failed") || | |
| 292 | - errorContent.includes("not found") || | |
| 293 | - errorContent.includes("recognized") || | |
| 294 | - /error/i.test(errorContent), | |
| 295 | - ).toBe(true); | |
| 296 | - | |
| 297 | - // Verify status field indicates command failure | |
| 298 | - expect(result[0].status).toContain("Command failed with:"); | |
| 299 | - }); | |
| 300 | - | |
| 301 | - it("should handle error situations gracefully", async () => { | |
| 302 | - // Use Node.js script that writes to stderr for cross-platform testing | |
| 303 | - const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; | |
| 304 | - const args = { command, waitForCompletion: true }; | |
| 305 | - const extras = createMockExtras(); | |
| 306 | - | |
| 307 | - const result = await runTerminalCommandImpl(args, extras); | |
| 308 | - | |
| 309 | - // Verify we still get a result with a name and description | |
| 310 | - expect(result).toHaveLength(1); | |
| 311 | - expect(result[0].name).toBe("Terminal"); | |
| 312 | - expect(result[0].description).toBe("Terminal command output"); | |
| 313 | - | |
| 314 | - // The command should have executed and returned content | |
| 315 | - expect(result[0].content).toBeDefined(); | |
| 316 | - | |
| 317 | - // We should see the error message we wrote to stderr | |
| 318 | - expect(result[0].content).toContain("This is an error message"); | |
| 319 | - | |
| 320 | - // Verify status field indicates command failure - the exact message format can vary | |
| 321 | - // between different node versions and platforms | |
| 322 | - expect(result[0].status).toContain("Command failed"); | |
| 323 | - }); | |
| 324 | - | |
| 325 | - it("should set appropriate status when a command completes successfully", async () => { | |
| 326 | - // Use a simple command that will succeed | |
| 327 | - const command = `node -e "console.log('success test')"`; | |
| 328 | - const args = { command, waitForCompletion: true }; | |
| 329 | - const extras = createMockExtras(); | |
| 330 | - | |
| 331 | - const result = await runTerminalCommandImpl(args, extras); | |
| 332 | - | |
| 333 | - expect(result).toHaveLength(1); | |
| 334 | - expect(result[0].name).toBe("Terminal"); | |
| 335 | - expect(result[0].content).toContain("success test"); | |
| 336 | - // Verify status field for successful command | |
| 337 | - expect(result[0].status).toBe("Command completed"); | |
| 338 | - }); | |
| 339 | - | |
| 340 | - it("should include status info for background commands in non-streaming mode", async () => { | |
| 341 | - // Use a simple background command | |
| 342 | - const command = `node -e "setTimeout(() => console.log('done'), 300)"`; | |
| 343 | - const args = { command, waitForCompletion: false }; | |
| 344 | - // No streaming in this test (no onPartialOutput) | |
| 345 | - const extras = createMockExtras(); | |
| 346 | - | |
| 347 | - const result = await runTerminalCommandImpl(args, extras); | |
| 348 | - | |
| 349 | - expect(result).toHaveLength(1); | |
| 350 | - expect(result[0].name).toBe("Terminal"); | |
| 351 | - // Verify both content and status fields for background commands | |
| 352 | - expect(result[0].content).toBe("Command is running in the background..."); | |
| 353 | - expect(result[0].status).toBe("Command is running in the background..."); | |
| 354 | - }); | |
| 355 | - | |
| 356 | - it("should handle missing workspace directory gracefully", async () => { | |
| 357 | - // Mock IDE to return empty workspace directories | |
| 358 | - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); | |
| 359 | - | |
| 360 | - // Create IDE mock with empty workspace | |
| 361 | - const mockIde = { | |
| 362 | - getIdeInfo: jest | |
| 363 | - .fn() | |
| 364 | - .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 365 | - getWorkspaceDirs: mockEmptyWorkspace, | |
| 366 | - runCommand: jest.fn(), | |
| 367 | - getIdeSettings: jest.fn(), | |
| 368 | - getDiff: jest.fn(), | |
| 369 | - getClipboardContent: jest.fn(), | |
| 370 | - isTelemetryEnabled: jest.fn(), | |
| 371 | - readFile: jest.fn(), | |
| 372 | - writeFile: jest.fn(), | |
| 373 | - renameFile: jest.fn(), | |
| 374 | - deleteFile: jest.fn(), | |
| 375 | - globFiles: jest.fn(), | |
| 376 | - ls: jest.fn(), | |
| 377 | - }; | |
| 378 | - | |
| 379 | - const extras = { | |
| 380 | - ide: mockIde as unknown as IDE, | |
| 381 | - llm: {} as any, | |
| 382 | - fetch: {} as any, | |
| 383 | - tool: {} as any, | |
| 384 | - toolCallId: "test-tool-call", | |
| 385 | - } as ToolExtras; | |
| 386 | - | |
| 387 | - const command = `node -e "console.log('no workspace test')"`; | |
| 388 | - const args = { command, waitForCompletion: true }; | |
| 389 | - | |
| 390 | - const result = await runTerminalCommandImpl(args, extras); | |
| 391 | - | |
| 392 | - // Should still work - falling back to HOME or cwd | |
| 393 | - expect(result).toHaveLength(1); | |
| 394 | - expect(result[0].name).toBe("Terminal"); | |
| 395 | - expect(result[0].description).toBe("Terminal command output"); | |
| 396 | - expect(result[0].content).toContain("no workspace test"); | |
| 397 | - expect(result[0].status).toBe("Command completed"); | |
| 398 | - | |
| 399 | - // Verify workspace dirs was called but returned empty | |
| 400 | - expect(mockEmptyWorkspace).toHaveBeenCalled(); | |
| 401 | - }); | |
| 402 | - | |
| 403 | - it("should handle case where cwd fallbacks all fail", async () => { | |
| 404 | - // Mock IDE to return empty workspace directories | |
| 405 | - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); | |
| 406 | - | |
| 407 | - // Save original environment variables and process.cwd | |
| 408 | - const originalHome = process.env.HOME; | |
| 409 | - const originalUserProfile = process.env.USERPROFILE; | |
| 410 | - const originalCwd = process.cwd; | |
| 411 | - | |
| 412 | - try { | |
| 413 | - // Mock all fallbacks to fail | |
| 414 | - delete process.env.HOME; | |
| 415 | - delete process.env.USERPROFILE; | |
| 416 | - process.cwd = jest.fn().mockImplementation(() => { | |
| 417 | - throw new Error("Current directory unavailable"); | |
| 418 | - }) as jest.MockedFunction<() => string>; | |
| 419 | - | |
| 420 | - // Create IDE mock with empty workspace | |
| 421 | - const mockIde = { | |
| 422 | - getIdeInfo: jest | |
| 423 | - .fn() | |
| 424 | - .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 425 | - getWorkspaceDirs: mockEmptyWorkspace, | |
| 426 | - runCommand: jest.fn(), | |
| 427 | - getIdeSettings: jest.fn(), | |
| 428 | - getDiff: jest.fn(), | |
| 429 | - getClipboardContent: jest.fn(), | |
| 430 | - isTelemetryEnabled: jest.fn(), | |
| 431 | - readFile: jest.fn(), | |
| 432 | - writeFile: jest.fn(), | |
| 433 | - renameFile: jest.fn(), | |
| 434 | - deleteFile: jest.fn(), | |
| 435 | - globFiles: jest.fn(), | |
| 436 | - ls: jest.fn(), | |
| 437 | - }; | |
| 438 | - | |
| 439 | - const extras = { | |
| 440 | - ide: mockIde as unknown as IDE, | |
| 441 | - llm: {} as any, | |
| 442 | - fetch: {} as any, | |
| 443 | - tool: {} as any, | |
| 444 | - toolCallId: "test-tool-call", | |
| 445 | - } as ToolExtras; | |
| 446 | - | |
| 447 | - const command = `node -e "console.log('fallback test')"`; | |
| 448 | - const args = { command, waitForCompletion: true }; | |
| 449 | - | |
| 450 | - // This should now handle the case gracefully by falling back to temp directory | |
| 451 | - const result = await runTerminalCommandImpl(args, extras); | |
| 452 | - | |
| 453 | - // Should work using the temp directory as fallback | |
| 454 | - expect(result).toHaveLength(1); | |
| 455 | - expect(result[0].name).toBe("Terminal"); | |
| 456 | - expect(result[0].content).toContain("fallback test"); | |
| 457 | - expect(result[0].status).toBe("Command completed"); | |
| 458 | - | |
| 459 | - console.log( | |
| 460 | - "Successfully handled cwd fallback to temp directory:", | |
| 461 | - result[0].status, | |
| 462 | - ); | |
| 463 | - } finally { | |
| 464 | - // Always restore original values | |
| 465 | - if (originalHome !== undefined) { | |
| 466 | - process.env.HOME = originalHome; | |
| 467 | - } | |
| 468 | - if (originalUserProfile !== undefined) { | |
| 469 | - process.env.USERPROFILE = originalUserProfile; | |
| 470 | - } | |
| 471 | - process.cwd = originalCwd; | |
| 472 | - } | |
| 473 | - }); | |
| 474 | -}); |
modified core/tools/implementations/runTerminalCommand.ts +55 −10
| @@ -36,8 +36,11 @@ | ||
| 36 | 36 | import { ToolImpl } from "."; |
| 37 | 37 | import { |
| 38 | 38 | isProcessBackgrounded, |
| 39 | + markProcessAsRunning, | |
| 39 | 40 | removeBackgroundedProcess, |
| 40 | -} from "../../util/processTerminalBackgroundStates"; | |
| 41 | + removeRunningProcess, | |
| 42 | + updateProcessOutput, | |
| 43 | +} from "../../util/processTerminalStates"; | |
| 41 | 44 | import { getBooleanArg, getStringArg } from "../parseArgs"; |
| 42 | 45 | |
| 43 | 46 | const asyncExec = util.promisify(childProcess.exec); |
| @@ -120,6 +123,16 @@ | ||
| 120 | 123 | env: getColorEnv(), // Add enhanced environment for colors |
| 121 | 124 | }); |
| 122 | 125 | |
| 126 | + // Track this process for foreground cancellation | |
| 127 | + if (toolCallId && waitForCompletion) { | |
| 128 | + markProcessAsRunning( | |
| 129 | + toolCallId, | |
| 130 | + childProc, | |
| 131 | + extras.onPartialOutput, | |
| 132 | + terminalOutput, | |
| 133 | + ); | |
| 134 | + } | |
| 135 | + | |
| 123 | 136 | childProc.stdout?.on("data", (data) => { |
| 124 | 137 | // Skip if this process has been backgrounded |
| 125 | 138 | if (isProcessBackgrounded(toolCallId)) return; |
| @@ -127,6 +140,11 @@ | ||
| 127 | 140 | const newOutput = getDecodedOutput(data); |
| 128 | 141 | terminalOutput += newOutput; |
| 129 | 142 | |
| 143 | + // Update the tracked output for potential cancellation notifications | |
| 144 | + if (toolCallId && waitForCompletion) { | |
| 145 | + updateProcessOutput(toolCallId, terminalOutput); | |
| 146 | + } | |
| 147 | + | |
| 130 | 148 | // Send partial output to UI |
| 131 | 149 | if (extras.onPartialOutput) { |
| 132 | 150 | const status = waitForCompletion |
| @@ -153,6 +171,11 @@ | ||
| 153 | 171 | const newOutput = getDecodedOutput(data); |
| 154 | 172 | terminalOutput += newOutput; |
| 155 | 173 | |
| 174 | + // Update the tracked output for potential cancellation notifications | |
| 175 | + if (toolCallId && waitForCompletion) { | |
| 176 | + updateProcessOutput(toolCallId, terminalOutput); | |
| 177 | + } | |
| 178 | + | |
| 156 | 179 | // Send partial output to UI, status is not required |
| 157 | 180 | if (extras.onPartialOutput) { |
| 158 | 181 | extras.onPartialOutput({ |
| @@ -182,15 +205,19 @@ | ||
| 182 | 205 | } |
| 183 | 206 | |
| 184 | 207 | childProc.on("close", (code) => { |
| 185 | - // If this process has been backgrounded, clean it up from the map and return | |
| 186 | - if (isProcessBackgrounded(toolCallId)) { | |
| 187 | - removeBackgroundedProcess(toolCallId); | |
| 188 | - return; | |
| 208 | + // Clean up process tracking | |
| 209 | + if (toolCallId) { | |
| 210 | + if (isProcessBackgrounded(toolCallId)) { | |
| 211 | + removeBackgroundedProcess(toolCallId); | |
| 212 | + return; | |
| 213 | + } | |
| 214 | + // Remove from foreground tracking if it was tracked | |
| 215 | + removeRunningProcess(toolCallId); | |
| 189 | 216 | } |
| 190 | 217 | |
| 191 | 218 | if (waitForCompletion) { |
| 192 | 219 | // Normal completion, resolve now |
| 193 | - if (code === 0) { | |
| 220 | + if (!code || code === 0) { | |
| 194 | 221 | const status = "Command completed"; |
| 195 | 222 | resolve([ |
| 196 | 223 | { |
| @@ -234,10 +261,14 @@ | ||
| 234 | 261 | }); |
| 235 | 262 | |
| 236 | 263 | childProc.on("error", (error) => { |
| 237 | - // If this process has been backgrounded, clean it up from the map and return | |
| 238 | - if (isProcessBackgrounded(toolCallId)) { | |
| 239 | - removeBackgroundedProcess(toolCallId); | |
| 240 | - return; | |
| 264 | + // Clean up process tracking | |
| 265 | + if (toolCallId) { | |
| 266 | + if (isProcessBackgrounded(toolCallId)) { | |
| 267 | + removeBackgroundedProcess(toolCallId); | |
| 268 | + return; | |
| 269 | + } | |
| 270 | + // Remove from foreground tracking if it was tracked | |
| 271 | + removeRunningProcess(toolCallId); | |
| 241 | 272 | } |
| 242 | 273 | |
| 243 | 274 | reject(error); |
| @@ -281,6 +312,11 @@ | ||
| 281 | 312 | }, |
| 282 | 313 | ); |
| 283 | 314 | |
| 315 | + // Track this process for foreground cancellation | |
| 316 | + if (toolCallId) { | |
| 317 | + markProcessAsRunning(toolCallId, childProc, undefined, ""); | |
| 318 | + } | |
| 319 | + | |
| 284 | 320 | let stdout = ""; |
| 285 | 321 | let stderr = ""; |
| 286 | 322 | |
| @@ -293,6 +329,11 @@ | ||
| 293 | 329 | }); |
| 294 | 330 | |
| 295 | 331 | childProc.on("close", (code) => { |
| 332 | + // Clean up process tracking | |
| 333 | + if (toolCallId) { | |
| 334 | + removeRunningProcess(toolCallId); | |
| 335 | + } | |
| 336 | + | |
| 296 | 337 | if (code === 0) { |
| 297 | 338 | resolve({ stdout, stderr }); |
| 298 | 339 | } else { |
| @@ -305,6 +346,10 @@ | ||
| 305 | 346 | }); |
| 306 | 347 | |
| 307 | 348 | childProc.on("error", (error) => { |
| 349 | + // Clean up process tracking | |
| 350 | + if (toolCallId) { | |
| 351 | + removeRunningProcess(toolCallId); | |
| 352 | + } | |
| 308 | 353 | reject(error); |
| 309 | 354 | }); |
| 310 | 355 | }, |
added core/tools/implementations/runTerminalCommand.vitest.ts +601 −0
| @@ -0,0 +1,601 @@ | ||
| 1 | +import { | |
| 2 | + describe, | |
| 3 | + it, | |
| 4 | + expect, | |
| 5 | + beforeEach, | |
| 6 | + afterEach, | |
| 7 | + afterAll, | |
| 8 | + vi, | |
| 9 | +} from "vitest"; | |
| 10 | +import * as childProcess from "node:child_process"; | |
| 11 | +import * as fs from "node:fs"; | |
| 12 | +import * as os from "node:os"; | |
| 13 | +import * as path from "node:path"; | |
| 14 | +import { IDE, ToolExtras } from "../.."; | |
| 15 | +import * as processTerminalStates from "../../util/processTerminalStates"; | |
| 16 | +import { runTerminalCommandImpl } from "./runTerminalCommand"; | |
| 17 | +import { runTerminalCommandTool } from "../definitions/runTerminalCommand"; | |
| 18 | + | |
| 19 | +// We're using real child processes, so ensure these aren't mocked | |
| 20 | +vi.unmock("node:child_process"); | |
| 21 | +vi.unmock("node:util"); | |
| 22 | + | |
| 23 | +describe("runTerminalCommandImpl", () => { | |
| 24 | + // Setup mocks and spies | |
| 25 | + const mockGetIdeInfo = vi.fn(); | |
| 26 | + const mockGetWorkspaceDirs = vi.fn(); | |
| 27 | + const mockOnPartialOutput = vi.fn(); | |
| 28 | + const mockRunCommand = vi.fn(); | |
| 29 | + | |
| 30 | + // Use a simple approach to ensure background processes are terminated | |
| 31 | + let testPid: number | null = null; | |
| 32 | + | |
| 33 | + // Create a temp directory for our tests | |
| 34 | + const tempDir = fs.mkdtempSync( | |
| 35 | + path.join(os.tmpdir(), "terminal-command-test-"), | |
| 36 | + ); | |
| 37 | + | |
| 38 | + beforeEach(() => { | |
| 39 | + vi.resetAllMocks(); | |
| 40 | + | |
| 41 | + // Setup backgrounded processes handling - don't mock, just make sure it's empty | |
| 42 | + // Clear any processes that might be already tracked | |
| 43 | + processTerminalStates.clearAllBackgroundProcesses(); | |
| 44 | + | |
| 45 | + // Setup IDE mocks | |
| 46 | + mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); | |
| 47 | + mockGetWorkspaceDirs.mockReturnValue( | |
| 48 | + Promise.resolve([`file://${tempDir}`]), | |
| 49 | + ); | |
| 50 | + }); | |
| 51 | + | |
| 52 | + afterEach(async () => { | |
| 53 | + // Clean up any lingering test processes | |
| 54 | + if (testPid !== null) { | |
| 55 | + try { | |
| 56 | + // Platform-independent way to kill a process | |
| 57 | + if (process.platform === "win32") { | |
| 58 | + await new Promise((resolve) => { | |
| 59 | + childProcess.exec(`taskkill /F /PID ${testPid}`, () => | |
| 60 | + resolve(null), | |
| 61 | + ); | |
| 62 | + }); | |
| 63 | + } else { | |
| 64 | + process.kill(testPid); | |
| 65 | + } | |
| 66 | + } catch (e) { | |
| 67 | + // Process might already be gone, ignore | |
| 68 | + } | |
| 69 | + testPid = null; | |
| 70 | + } | |
| 71 | + }); | |
| 72 | + | |
| 73 | + afterAll(() => { | |
| 74 | + // Clean up the temp directory after tests | |
| 75 | + fs.rmSync(tempDir, { recursive: true, force: true }); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + // Helper function to create a ToolExtras object | |
| 79 | + const createMockExtras = ( | |
| 80 | + overrides: Partial<{ | |
| 81 | + onPartialOutput?: any; | |
| 82 | + remoteName?: string; | |
| 83 | + }> = {}, | |
| 84 | + ): ToolExtras => { | |
| 85 | + // Update IDE info if remoteName is provided | |
| 86 | + if (overrides.remoteName) { | |
| 87 | + mockGetIdeInfo.mockReturnValue( | |
| 88 | + Promise.resolve({ remoteName: overrides.remoteName }), | |
| 89 | + ); | |
| 90 | + } | |
| 91 | + | |
| 92 | + // Create a minimally compliant IDE mock | |
| 93 | + const mockIde = { | |
| 94 | + getIdeInfo: mockGetIdeInfo, | |
| 95 | + getWorkspaceDirs: mockGetWorkspaceDirs, | |
| 96 | + runCommand: mockRunCommand, | |
| 97 | + // Add stubs for other required IDE methods | |
| 98 | + getIdeSettings: vi.fn(), | |
| 99 | + getDiff: vi.fn(), | |
| 100 | + getClipboardContent: vi.fn(), | |
| 101 | + isTelemetryEnabled: vi.fn(), | |
| 102 | + readFile: vi.fn(), | |
| 103 | + writeFile: vi.fn(), | |
| 104 | + renameFile: vi.fn(), | |
| 105 | + deleteFile: vi.fn(), | |
| 106 | + globFiles: vi.fn(), | |
| 107 | + ls: vi.fn(), | |
| 108 | + }; | |
| 109 | + | |
| 110 | + // Create a base ToolExtras object with required properties | |
| 111 | + const baseExtras = { | |
| 112 | + ide: mockIde as unknown as IDE, | |
| 113 | + llm: {} as any, | |
| 114 | + fetch: {} as any, | |
| 115 | + tool: {} as any, | |
| 116 | + toolCallId: "test-tool-call", | |
| 117 | + } as ToolExtras; | |
| 118 | + | |
| 119 | + // Apply overrides | |
| 120 | + if (overrides.onPartialOutput) { | |
| 121 | + baseExtras.onPartialOutput = overrides.onPartialOutput; | |
| 122 | + } | |
| 123 | + | |
| 124 | + return baseExtras; | |
| 125 | + }; | |
| 126 | + | |
| 127 | + it("should execute a command synchronously and capture output", async () => { | |
| 128 | + // Use Node.js for cross-platform output generation | |
| 129 | + const command = `node -e "console.log('real test output')"`; | |
| 130 | + const args = { command, waitForCompletion: true }; | |
| 131 | + const extras = createMockExtras(); | |
| 132 | + | |
| 133 | + const result = await runTerminalCommandImpl(args, extras); | |
| 134 | + | |
| 135 | + // Verify real command output | |
| 136 | + expect(result).toHaveLength(1); | |
| 137 | + expect(result[0].name).toBe("Terminal"); | |
| 138 | + expect(result[0].description).toBe("Terminal command output"); | |
| 139 | + expect(result[0].content).toContain("real test output"); | |
| 140 | + // Verify status field indicates successful completion | |
| 141 | + expect(result[0].status).toBe("Command completed"); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should stream output when onPartialOutput is provided", async () => { | |
| 145 | + // This test uses Node to create a command that outputs data incrementally | |
| 146 | + const command = `node -e " | |
| 147 | + console.log('first output'); | |
| 148 | + setTimeout(() => { | |
| 149 | + console.log('second output'); | |
| 150 | + console.error('error output'); | |
| 151 | + }, 50); | |
| 152 | + "`; | |
| 153 | + | |
| 154 | + const args = { command, waitForCompletion: true }; | |
| 155 | + const mockOutputFn = vi.fn(); | |
| 156 | + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 157 | + | |
| 158 | + // Execute the command with streaming | |
| 159 | + const result = await runTerminalCommandImpl(args, extras); | |
| 160 | + | |
| 161 | + // Verify onPartialOutput was called with increasing content | |
| 162 | + expect(mockOutputFn).toHaveBeenCalled(); | |
| 163 | + | |
| 164 | + // Verify final result has all output | |
| 165 | + expect(result[0].content).toContain("first output"); | |
| 166 | + expect(result[0].content).toContain("second output"); | |
| 167 | + expect(result[0].content).toContain("error output"); | |
| 168 | + // Verify status field indicates successful completion | |
| 169 | + expect(result[0].status).toBe("Command completed"); | |
| 170 | + | |
| 171 | + // Verify that initial streaming updates have empty status for regular commands | |
| 172 | + const firstCall = mockOutputFn.mock.calls[0][0]; | |
| 173 | + if (firstCall && typeof firstCall === "object") { | |
| 174 | + const contextItems = (firstCall as any).contextItems; | |
| 175 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 176 | + // For commands with waitForCompletion=true, status should be empty while streaming | |
| 177 | + expect(contextItems[0].status).toBe(""); | |
| 178 | + } | |
| 179 | + } | |
| 180 | + }); | |
| 181 | + | |
| 182 | + it("should run commands in background when waitForCompletion is false", async () => { | |
| 183 | + // Create a self-identifying background process that writes its PID | |
| 184 | + // to a file we can access to kill it later | |
| 185 | + const pidFile = path.join(tempDir, "test-pid.txt"); | |
| 186 | + | |
| 187 | + // This script creates a long-running process and writes its PID to our file | |
| 188 | + // Using a fixed duration timeout so we can be sure to clean it up | |
| 189 | + const command = `node -e " | |
| 190 | + const fs = require('fs'); | |
| 191 | + console.log('starting background process with PID: ' + process.pid); | |
| 192 | + fs.writeFileSync('${pidFile}', process.pid.toString()); | |
| 193 | + setTimeout(() => { | |
| 194 | + console.log('background process completed'); | |
| 195 | + }, 500); | |
| 196 | + "`; | |
| 197 | + | |
| 198 | + const args = { command, waitForCompletion: false }; | |
| 199 | + const mockOutputFn = vi.fn(); | |
| 200 | + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 201 | + | |
| 202 | + const result = await runTerminalCommandImpl(args, extras); | |
| 203 | + | |
| 204 | + // Result should indicate background running in either content or status | |
| 205 | + expect(result[0].content || result[0].status).toContain( | |
| 206 | + "running in the background", | |
| 207 | + ); | |
| 208 | + // Verify status field indicates background running | |
| 209 | + expect(result[0].status).toBe("Command is running in the background..."); | |
| 210 | + | |
| 211 | + // Initial notification should indicate background running | |
| 212 | + expect(mockOutputFn).toHaveBeenCalled(); | |
| 213 | + // Check the first call contains background running message | |
| 214 | + const firstCallData = mockOutputFn.mock.calls[0][0]; | |
| 215 | + if (firstCallData && typeof firstCallData === "object") { | |
| 216 | + const contextItems = (firstCallData as any).contextItems; | |
| 217 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 218 | + expect(contextItems[0].content).toContain(""); | |
| 219 | + expect(contextItems[0].status).toMatch( | |
| 220 | + /Command is running in the background.../, | |
| 221 | + ); | |
| 222 | + } | |
| 223 | + } | |
| 224 | + | |
| 225 | + // Wait a bit to make sure the PID file is written | |
| 226 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 227 | + | |
| 228 | + // Read the PID file to get the process ID so we can kill it later | |
| 229 | + if (fs.existsSync(pidFile)) { | |
| 230 | + testPid = Number(fs.readFileSync(pidFile, "utf-8")); | |
| 231 | + } | |
| 232 | + | |
| 233 | + // Wait a bit longer for the process to complete and onPartialOutput to be called again | |
| 234 | + await new Promise((resolve) => setTimeout(resolve, 400)); | |
| 235 | + | |
| 236 | + // Check for background process completion message in mockOutputFn calls | |
| 237 | + // Note: This is optional and depends on timing, so we don't want to strictly enforce it | |
| 238 | + let foundCompletionMessage = false; | |
| 239 | + | |
| 240 | + for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { | |
| 241 | + const call = mockOutputFn.mock.calls[i][0]; | |
| 242 | + if (call && typeof call === "object") { | |
| 243 | + const contextItems = (call as any).contextItems; | |
| 244 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 245 | + if ( | |
| 246 | + contextItems[0].status === "\nBackground command completed" || | |
| 247 | + (contextItems[0].status && | |
| 248 | + contextItems[0].status.includes("Background command")) | |
| 249 | + ) { | |
| 250 | + foundCompletionMessage = true; | |
| 251 | + break; | |
| 252 | + } | |
| 253 | + } | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + // If we found any completion message in the output, great! | |
| 258 | + // But we won't fail the test if we didn't, since it may be timing-dependent | |
| 259 | + if (mockOutputFn.mock.calls.length > 1) { | |
| 260 | + expect(foundCompletionMessage || true).toBeTruthy(); | |
| 261 | + } | |
| 262 | + }); | |
| 263 | + | |
| 264 | + it("should handle remote environments", async () => { | |
| 265 | + // We'll keep mocking for remote environments as we can't test those directly | |
| 266 | + const args = { command: "echo 'test'", waitForCompletion: true }; | |
| 267 | + const extras = createMockExtras({ remoteName: "ssh" }); | |
| 268 | + | |
| 269 | + const result = await runTerminalCommandImpl(args, extras); | |
| 270 | + | |
| 271 | + // In remote environments, it should use the IDE's runCommand | |
| 272 | + expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); | |
| 273 | + // Match the actual output message | |
| 274 | + expect(result[0].content).toContain("Terminal output not available"); | |
| 275 | + expect(result[0].content).toContain("SSH environments"); | |
| 276 | + // Verify status field indicates command failed in remote environments | |
| 277 | + expect(result[0].status).toBe("Command failed"); | |
| 278 | + }); | |
| 279 | + | |
| 280 | + it("should handle errors when executing invalid commands", async () => { | |
| 281 | + // Use a command that should fail on any platform | |
| 282 | + const args = { | |
| 283 | + command: "non-existent-command-xyz", | |
| 284 | + waitForCompletion: true, | |
| 285 | + }; | |
| 286 | + const extras = createMockExtras(); | |
| 287 | + | |
| 288 | + const result = await runTerminalCommandImpl(args, extras); | |
| 289 | + | |
| 290 | + expect(result[0].name).toBe("Terminal"); | |
| 291 | + expect(result[0].description).toBe("Terminal command output"); | |
| 292 | + | |
| 293 | + // The exact error message varies by platform, but should contain error information | |
| 294 | + const errorContent = result[0].content; | |
| 295 | + expect( | |
| 296 | + errorContent.includes("Command failed") || | |
| 297 | + errorContent.includes("not found") || | |
| 298 | + errorContent.includes("recognized") || | |
| 299 | + /error/i.test(errorContent), | |
| 300 | + ).toBe(true); | |
| 301 | + | |
| 302 | + // Verify status field indicates command failure | |
| 303 | + expect(result[0].status).toContain("Command failed with:"); | |
| 304 | + }); | |
| 305 | + | |
| 306 | + it("should handle error situations gracefully", async () => { | |
| 307 | + // Use Node.js script that writes to stderr for cross-platform testing | |
| 308 | + const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; | |
| 309 | + const args = { command, waitForCompletion: true }; | |
| 310 | + const extras = createMockExtras(); | |
| 311 | + | |
| 312 | + const result = await runTerminalCommandImpl(args, extras); | |
| 313 | + | |
| 314 | + // Verify we still get a result with a name and description | |
| 315 | + expect(result).toHaveLength(1); | |
| 316 | + expect(result[0].name).toBe("Terminal"); | |
| 317 | + expect(result[0].description).toBe("Terminal command output"); | |
| 318 | + | |
| 319 | + // The command should have executed and returned content | |
| 320 | + expect(result[0].content).toBeDefined(); | |
| 321 | + | |
| 322 | + // We should see the error message we wrote to stderr | |
| 323 | + expect(result[0].content).toContain("This is an error message"); | |
| 324 | + | |
| 325 | + // Verify status field indicates command failure - the exact message format can vary | |
| 326 | + // between different node versions and platforms | |
| 327 | + expect(result[0].status).toContain("Command failed"); | |
| 328 | + }); | |
| 329 | + | |
| 330 | + it("should set appropriate status when a command completes successfully", async () => { | |
| 331 | + // Use a simple command that will succeed | |
| 332 | + const command = `node -e "console.log('success test')"`; | |
| 333 | + const args = { command, waitForCompletion: true }; | |
| 334 | + const extras = createMockExtras(); | |
| 335 | + | |
| 336 | + const result = await runTerminalCommandImpl(args, extras); | |
| 337 | + | |
| 338 | + expect(result).toHaveLength(1); | |
| 339 | + expect(result[0].name).toBe("Terminal"); | |
| 340 | + expect(result[0].content).toContain("success test"); | |
| 341 | + // Verify status field for successful command | |
| 342 | + expect(result[0].status).toBe("Command completed"); | |
| 343 | + }); | |
| 344 | + | |
| 345 | + it("should include status info for background commands in non-streaming mode", async () => { | |
| 346 | + // Use a simple background command | |
| 347 | + const command = `node -e "setTimeout(() => console.log('done'), 300)"`; | |
| 348 | + const args = { command, waitForCompletion: false }; | |
| 349 | + // No streaming in this test (no onPartialOutput) | |
| 350 | + const extras = createMockExtras(); | |
| 351 | + | |
| 352 | + const result = await runTerminalCommandImpl(args, extras); | |
| 353 | + | |
| 354 | + expect(result).toHaveLength(1); | |
| 355 | + expect(result[0].name).toBe("Terminal"); | |
| 356 | + // Verify both content and status fields for background commands | |
| 357 | + expect(result[0].content).toBe("Command is running in the background..."); | |
| 358 | + expect(result[0].status).toBe("Command is running in the background..."); | |
| 359 | + }); | |
| 360 | + | |
| 361 | + it("should handle missing workspace directory gracefully", async () => { | |
| 362 | + // Mock IDE to return empty workspace directories | |
| 363 | + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); | |
| 364 | + | |
| 365 | + // Create IDE mock with empty workspace | |
| 366 | + const mockIde = { | |
| 367 | + getIdeInfo: vi | |
| 368 | + .fn() | |
| 369 | + .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 370 | + getWorkspaceDirs: mockEmptyWorkspace, | |
| 371 | + runCommand: vi.fn(), | |
| 372 | + getIdeSettings: vi.fn(), | |
| 373 | + getDiff: vi.fn(), | |
| 374 | + getClipboardContent: vi.fn(), | |
| 375 | + isTelemetryEnabled: vi.fn(), | |
| 376 | + readFile: vi.fn(), | |
| 377 | + writeFile: vi.fn(), | |
| 378 | + renameFile: vi.fn(), | |
| 379 | + deleteFile: vi.fn(), | |
| 380 | + globFiles: vi.fn(), | |
| 381 | + ls: vi.fn(), | |
| 382 | + }; | |
| 383 | + | |
| 384 | + const extras = { | |
| 385 | + ide: mockIde as unknown as IDE, | |
| 386 | + llm: {} as any, | |
| 387 | + fetch: {} as any, | |
| 388 | + tool: {} as any, | |
| 389 | + toolCallId: "test-tool-call", | |
| 390 | + } as ToolExtras; | |
| 391 | + | |
| 392 | + const command = `node -e "console.log('no workspace test')"`; | |
| 393 | + const args = { command, waitForCompletion: true }; | |
| 394 | + | |
| 395 | + const result = await runTerminalCommandImpl(args, extras); | |
| 396 | + | |
| 397 | + // Should still work - falling back to HOME or cwd | |
| 398 | + expect(result).toHaveLength(1); | |
| 399 | + expect(result[0].name).toBe("Terminal"); | |
| 400 | + expect(result[0].description).toBe("Terminal command output"); | |
| 401 | + expect(result[0].content).toContain("no workspace test"); | |
| 402 | + expect(result[0].status).toBe("Command completed"); | |
| 403 | + | |
| 404 | + // Verify workspace dirs was called but returned empty | |
| 405 | + expect(mockEmptyWorkspace).toHaveBeenCalled(); | |
| 406 | + }); | |
| 407 | + | |
| 408 | + it("should handle case where cwd fallbacks all fail", async () => { | |
| 409 | + // Mock IDE to return empty workspace directories | |
| 410 | + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); | |
| 411 | + | |
| 412 | + // Save original environment variables and process.cwd | |
| 413 | + const originalHome = process.env.HOME; | |
| 414 | + const originalUserProfile = process.env.USERPROFILE; | |
| 415 | + const originalCwd = process.cwd; | |
| 416 | + | |
| 417 | + try { | |
| 418 | + // Mock all fallbacks to fail | |
| 419 | + delete process.env.HOME; | |
| 420 | + delete process.env.USERPROFILE; | |
| 421 | + process.cwd = vi.fn().mockImplementation(() => { | |
| 422 | + throw new Error("Current directory unavailable"); | |
| 423 | + }) as any; | |
| 424 | + | |
| 425 | + // Create IDE mock with empty workspace | |
| 426 | + const mockIde = { | |
| 427 | + getIdeInfo: vi | |
| 428 | + .fn() | |
| 429 | + .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 430 | + getWorkspaceDirs: mockEmptyWorkspace, | |
| 431 | + runCommand: vi.fn(), | |
| 432 | + getIdeSettings: vi.fn(), | |
| 433 | + getDiff: vi.fn(), | |
| 434 | + getClipboardContent: vi.fn(), | |
| 435 | + isTelemetryEnabled: vi.fn(), | |
| 436 | + readFile: vi.fn(), | |
| 437 | + writeFile: vi.fn(), | |
| 438 | + renameFile: vi.fn(), | |
| 439 | + deleteFile: vi.fn(), | |
| 440 | + globFiles: vi.fn(), | |
| 441 | + ls: vi.fn(), | |
| 442 | + }; | |
| 443 | + | |
| 444 | + const extras = { | |
| 445 | + ide: mockIde as unknown as IDE, | |
| 446 | + llm: {} as any, | |
| 447 | + fetch: {} as any, | |
| 448 | + tool: {} as any, | |
| 449 | + toolCallId: "test-tool-call", | |
| 450 | + } as ToolExtras; | |
| 451 | + | |
| 452 | + const command = `node -e "console.log('fallback test')"`; | |
| 453 | + const args = { command, waitForCompletion: true }; | |
| 454 | + | |
| 455 | + // This should now handle the case gracefully by falling back to temp directory | |
| 456 | + const result = await runTerminalCommandImpl(args, extras); | |
| 457 | + | |
| 458 | + // Should work using the temp directory as fallback | |
| 459 | + expect(result).toHaveLength(1); | |
| 460 | + expect(result[0].name).toBe("Terminal"); | |
| 461 | + expect(result[0].content).toContain("fallback test"); | |
| 462 | + expect(result[0].status).toBe("Command completed"); | |
| 463 | + | |
| 464 | + console.log( | |
| 465 | + "Successfully handled cwd fallback to temp directory:", | |
| 466 | + result[0].status, | |
| 467 | + ); | |
| 468 | + } finally { | |
| 469 | + // Always restore original values | |
| 470 | + if (originalHome !== undefined) { | |
| 471 | + process.env.HOME = originalHome; | |
| 472 | + } | |
| 473 | + if (originalUserProfile !== undefined) { | |
| 474 | + process.env.USERPROFILE = originalUserProfile; | |
| 475 | + } | |
| 476 | + process.cwd = originalCwd; | |
| 477 | + } | |
| 478 | + }); | |
| 479 | +}); | |
| 480 | + | |
| 481 | +describe("runTerminalCommandTool.evaluateToolCallPolicy", () => { | |
| 482 | + it("should return base policy for safe commands like echo", () => { | |
| 483 | + const basePolicy = "allowedWithoutPermission"; | |
| 484 | + const args = { command: "echo hello world" }; | |
| 485 | + | |
| 486 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 487 | + basePolicy, | |
| 488 | + args, | |
| 489 | + ); | |
| 490 | + | |
| 491 | + expect(result).toBe("allowedWithoutPermission"); | |
| 492 | + }); | |
| 493 | + | |
| 494 | + it("should respect disabled policy even for non-echo commands", () => { | |
| 495 | + const basePolicy = "disabled"; | |
| 496 | + const args = { command: "ls -la" }; | |
| 497 | + | |
| 498 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 499 | + basePolicy, | |
| 500 | + args, | |
| 501 | + ); | |
| 502 | + | |
| 503 | + expect(result).toBe("disabled"); | |
| 504 | + }); | |
| 505 | + | |
| 506 | + it("should respect disabled policy even for safe commands", () => { | |
| 507 | + const basePolicy = "disabled"; | |
| 508 | + const args = { command: "echo test" }; | |
| 509 | + | |
| 510 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 511 | + basePolicy, | |
| 512 | + args, | |
| 513 | + ); | |
| 514 | + | |
| 515 | + expect(result).toBe("disabled"); | |
| 516 | + }); | |
| 517 | + | |
| 518 | + it("should return base policy for non-echo commands", () => { | |
| 519 | + const basePolicy = "allowedWithoutPermission"; | |
| 520 | + const args = { command: "ls -la" }; | |
| 521 | + | |
| 522 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 523 | + basePolicy, | |
| 524 | + args, | |
| 525 | + ); | |
| 526 | + | |
| 527 | + expect(result).toBe("allowedWithoutPermission"); | |
| 528 | + }); | |
| 529 | + | |
| 530 | + it("should return base policy for git commands", () => { | |
| 531 | + const basePolicy = "allowedWithPermission"; | |
| 532 | + const args = { command: "git status" }; | |
| 533 | + | |
| 534 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 535 | + basePolicy, | |
| 536 | + args, | |
| 537 | + ); | |
| 538 | + | |
| 539 | + expect(result).toBe("allowedWithPermission"); | |
| 540 | + }); | |
| 541 | + | |
| 542 | + it("should handle undefined command gracefully", () => { | |
| 543 | + const basePolicy = "allowedWithoutPermission"; | |
| 544 | + const args = { command: undefined }; | |
| 545 | + | |
| 546 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 547 | + basePolicy, | |
| 548 | + args, | |
| 549 | + ); | |
| 550 | + | |
| 551 | + expect(result).toBe("allowedWithoutPermission"); | |
| 552 | + }); | |
| 553 | + | |
| 554 | + it("should handle null command gracefully", () => { | |
| 555 | + const basePolicy = "allowedWithoutPermission"; | |
| 556 | + const args = { command: null }; | |
| 557 | + | |
| 558 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 559 | + basePolicy, | |
| 560 | + args, | |
| 561 | + ); | |
| 562 | + | |
| 563 | + expect(result).toBe("allowedWithoutPermission"); | |
| 564 | + }); | |
| 565 | + | |
| 566 | + it("should handle empty command string", () => { | |
| 567 | + const basePolicy = "allowedWithoutPermission"; | |
| 568 | + const args = { command: "" }; | |
| 569 | + | |
| 570 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 571 | + basePolicy, | |
| 572 | + args, | |
| 573 | + ); | |
| 574 | + | |
| 575 | + expect(result).toBe("allowedWithoutPermission"); | |
| 576 | + }); | |
| 577 | + | |
| 578 | + it("should disable dangerous commands like rm -rf /", () => { | |
| 579 | + const basePolicy = "allowedWithoutPermission"; | |
| 580 | + const args = { command: "rm -rf /" }; | |
| 581 | + | |
| 582 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 583 | + basePolicy, | |
| 584 | + args, | |
| 585 | + ); | |
| 586 | + | |
| 587 | + expect(result).toBe("disabled"); | |
| 588 | + }); | |
| 589 | + | |
| 590 | + it("should require permission for high-risk network commands", () => { | |
| 591 | + const basePolicy = "allowedWithoutPermission"; | |
| 592 | + const args = { command: "curl http://example.com" }; | |
| 593 | + | |
| 594 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 595 | + basePolicy, | |
| 596 | + args, | |
| 597 | + ); | |
| 598 | + | |
| 599 | + expect(result).toBe("allowedWithPermission"); | |
| 600 | + }); | |
| 601 | +}); |
modified core/tools/implementations/searchWeb.ts +2 −2
| @@ -29,8 +29,8 @@ | ||
| 29 | 29 | // Add truncation warning if needed |
| 30 | 30 | if (truncatedResults.length > 0) { |
| 31 | 31 | processedResults.push({ |
| 32 | - name: "Web search truncation warning", | |
| 33 | - description: "Informs that search results were truncated", | |
| 32 | + name: "Truncation warning", | |
| 33 | + description: "", | |
| 34 | 34 | content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`, |
| 35 | 35 | }); |
| 36 | 36 | } |
modified core/tools/implementations/searchWeb.vitest.ts +2 −2
| @@ -62,7 +62,7 @@ | ||
| 62 | 62 | expect(result).toHaveLength(3); // Two results + warning |
| 63 | 63 | expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); |
| 64 | 64 | expect(result[1].content).toBe(shortContent); |
| 65 | - expect(result[2].name).toBe("Web search truncation warning"); | |
| 65 | + expect(result[2].name).toBe("Truncation warning"); | |
| 66 | 66 | expect(result[2].content).toContain("truncated"); |
| 67 | 67 | expect(result[2].content).toContain("Result 1"); |
| 68 | 68 | expect(result[2].content).not.toContain("Result 2"); |
| @@ -100,7 +100,7 @@ | ||
| 100 | 100 | expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); |
| 101 | 101 | expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); |
| 102 | 102 | expect(result[2].content).toBe(shortContent); |
| 103 | - expect(result[3].name).toBe("Web search truncation warning"); | |
| 103 | + expect(result[3].name).toBe("Truncation warning"); | |
| 104 | 104 | expect(result[3].content).toContain("Result 1"); |
| 105 | 105 | expect(result[3].content).toContain("Result 2"); |
| 106 | 106 | expect(result[3].content).not.toContain("Result 3"); |
modified core/tools/implementations/viewDiff.ts +13 −2
| @@ -9,6 +9,17 @@ | ||
| 9 | 9 | // TODO includeUnstaged should be an option |
| 10 | 10 | |
| 11 | 11 | const combinedDiff = diffs.join("\n"); |
| 12 | + | |
| 13 | + if (!combinedDiff.trim()) { | |
| 14 | + return [ | |
| 15 | + { | |
| 16 | + name: "Diff", | |
| 17 | + description: "current Git diff", | |
| 18 | + content: "The current diff is empty", | |
| 19 | + }, | |
| 20 | + ]; | |
| 21 | + } | |
| 22 | + | |
| 12 | 23 | const diffLines = combinedDiff.split("\n"); |
| 13 | 24 | |
| 14 | 25 | let truncated = false; |
| @@ -29,8 +40,8 @@ | ||
| 29 | 40 | |
| 30 | 41 | if (truncated) { |
| 31 | 42 | contextItems.push({ |
| 32 | - name: "Diff truncation warning", | |
| 33 | - description: "Informs that git diff was truncated", | |
| 43 | + name: "Truncation warning", | |
| 44 | + description: "", | |
| 34 | 45 | content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`, |
| 35 | 46 | }); |
| 36 | 47 | } |
modified core/tools/implementations/viewDiff.vitest.ts +2 −2
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); |
| 59 | 59 | |
| 60 | 60 | // Check the warning |
| 61 | - expect(result[1].name).toBe("Diff truncation warning"); | |
| 61 | + expect(result[1].name).toBe("Truncation warning"); | |
| 62 | 62 | expect(result[1].content).toContain("truncated"); |
| 63 | 63 | expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`); |
| 64 | 64 | }); |
| @@ -83,5 +83,5 @@ | ||
| 83 | 83 | expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); |
| 84 | 84 | |
| 85 | 85 | // Check the warning |
| 86 | - expect(result[1].name).toBe("Diff truncation warning"); | |
| 86 | + expect(result[1].name).toBe("Truncation warning"); | |
| 87 | 87 | }); |
modified core/tools/index.ts +36 −25
| @@ -1,17 +1,13 @@ | ||
| 1 | -import { ConfigDependentToolParams, IDE, Tool } from ".."; | |
| 1 | +import { ConfigDependentToolParams, Tool } from ".."; | |
| 2 | +import { isRecommendedAgentModel } from "../llm/toolSupport"; | |
| 2 | 3 | import * as toolDefinitions from "./definitions"; |
| 3 | 4 | |
| 4 | 5 | // I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads. |
| 5 | - | |
| 6 | -// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 | |
| 7 | -const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool]; | |
| 8 | - | |
| 9 | -const getBaseToolDefinitions = () => [ | |
| 6 | +export const getBaseToolDefinitions = () => [ | |
| 10 | 7 | toolDefinitions.readFileTool, |
| 11 | 8 | toolDefinitions.createNewFileTool, |
| 12 | 9 | toolDefinitions.runTerminalCommandTool, |
| 13 | 10 | toolDefinitions.globSearchTool, |
| 14 | - toolDefinitions.searchWebTool, | |
| 15 | 11 | toolDefinitions.viewDiffTool, |
| 16 | 12 | toolDefinitions.readCurrentlyOpenFileTool, |
| 17 | 13 | toolDefinitions.lsTool, |
| @@ -21,22 +17,37 @@ | ||
| 21 | 17 | |
| 22 | 18 | export const getConfigDependentToolDefinitions = ( |
| 23 | 19 | params: ConfigDependentToolParams, |
| 24 | -): Tool[] => [ | |
| 25 | - toolDefinitions.requestRuleTool(params), | |
| 26 | - // Search and replace is now generally available | |
| 27 | - toolDefinitions.searchAndReplaceInFileTool, | |
| 28 | - // Keep edit file tool available for models that need it | |
| 29 | - toolDefinitions.editFileTool, | |
| 30 | - ...(params.enableExperimentalTools | |
| 31 | - ? [ | |
| 32 | - toolDefinitions.viewRepoMapTool, | |
| 33 | - toolDefinitions.viewSubdirectoryTool, | |
| 34 | - toolDefinitions.codebaseTool, | |
| 35 | - ] | |
| 36 | - : []), | |
| 37 | -]; | |
| 20 | +): Tool[] => { | |
| 21 | + const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params; | |
| 22 | + const tools: Tool[] = []; | |
| 23 | + | |
| 24 | + tools.push(toolDefinitions.requestRuleTool(params)); | |
| 25 | + | |
| 26 | + if (isSignedIn) { | |
| 27 | + // Web search is only available for signed-in users | |
| 28 | + tools.push(toolDefinitions.searchWebTool); | |
| 29 | + } | |
| 30 | + | |
| 31 | + if (enableExperimentalTools) { | |
| 32 | + tools.push( | |
| 33 | + toolDefinitions.viewRepoMapTool, | |
| 34 | + toolDefinitions.viewSubdirectoryTool, | |
| 35 | + toolDefinitions.codebaseTool, | |
| 36 | + toolDefinitions.readFileRangeTool, | |
| 37 | + ); | |
| 38 | + } | |
| 39 | + | |
| 40 | + if (modelName && isRecommendedAgentModel(modelName)) { | |
| 41 | + tools.push(toolDefinitions.multiEditTool); | |
| 42 | + } else { | |
| 43 | + tools.push(toolDefinitions.editFileTool); | |
| 44 | + tools.push(toolDefinitions.singleFindAndReplaceTool); | |
| 45 | + } | |
| 46 | + | |
| 47 | + // missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 | |
| 48 | + if (!isRemote) { | |
| 49 | + tools.push(toolDefinitions.grepSearchTool); | |
| 50 | + } | |
| 38 | 51 | |
| 39 | -export const getToolsForIde = async (ide: IDE): Promise<Tool[]> => | |
| 40 | - (await ide.isWorkspaceRemote()) | |
| 41 | - ? getBaseToolDefinitions() | |
| 42 | - : [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()]; | |
| 52 | + return tools; | |
| 53 | +}; |
modified core/tools/mcpToolName.ts +7 −2
| @@ -1,7 +1,12 @@ | ||
| 1 | 1 | import { MCPServerStatus, MCPTool } from ".."; |
| 2 | - | |
| 3 | 2 | export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) { |
| 4 | - const serverPrefix = server.name.split(" ").join("_").toLowerCase(); | |
| 3 | + // Replace any sequence of non-alphanumeric characters with a single underscore | |
| 4 | + const serverPrefix = server.name | |
| 5 | + .toLowerCase() | |
| 6 | + .replace(/[^a-z0-9]+/g, "_") | |
| 7 | + .replace(/^_+|_+$/g, "") // Remove leading/trailing underscores | |
| 8 | + .replace(/_+/g, "_"); // Replace multiple sequential underscores with single underscore | |
| 9 | + | |
| 5 | 10 | if (tool.name.startsWith(serverPrefix)) { |
| 6 | 11 | return tool.name; |
| 7 | 12 | } |
modified core/tools/mcpToolName.vitest.ts +52 −0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | const createMcpServer = (name: string): MCPServerStatus => ({ |
| 6 | 6 | name, |
| 7 | 7 | errors: [], |
| 8 | + infos: [], | |
| 8 | 9 | prompts: [], |
| 9 | 10 | tools: [], |
| 10 | 11 | resources: [], |
| @@ -56,3 +57,54 @@ | ||
| 56 | 57 | const result = getMCPToolName(server, tool); |
| 57 | 58 | expect(result).toBe("gitlab_create_merge_request"); |
| 58 | 59 | }); |
| 60 | + | |
| 61 | +test("getMCPToolName - handles server names with special characters (parentheses)", () => { | |
| 62 | + const server = createMcpServer("Linear MCP (SSE)"); | |
| 63 | + const tool = createMCPTool("create_issue"); | |
| 64 | + | |
| 65 | + const result = getMCPToolName(server, tool); | |
| 66 | + // Should only contain alphanumeric characters and underscores | |
| 67 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 68 | + expect(result).toBe("linear_mcp_sse_create_issue"); | |
| 69 | +}); | |
| 70 | + | |
| 71 | +test("getMCPToolName - handles server names with dots and other special characters", () => { | |
| 72 | + const server = createMcpServer("My.Server@Test!"); | |
| 73 | + const tool = createMCPTool("test_action"); | |
| 74 | + | |
| 75 | + const result = getMCPToolName(server, tool); | |
| 76 | + // Should only contain alphanumeric characters and underscores | |
| 77 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 78 | + expect(result).toBe("my_server_test_test_action"); | |
| 79 | +}); | |
| 80 | + | |
| 81 | +test("getMCPToolName - handles server names with multiple consecutive special characters", () => { | |
| 82 | + const server = createMcpServer("Server@@##Name"); | |
| 83 | + const tool = createMCPTool("action"); | |
| 84 | + | |
| 85 | + const result = getMCPToolName(server, tool); | |
| 86 | + // Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores) | |
| 87 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 88 | + expect(result).toBe("server_name_action"); | |
| 89 | +}); | |
| 90 | + | |
| 91 | +test("getMCPToolName - handles server names with hyphens", () => { | |
| 92 | + const server = createMcpServer("My-Server-Name"); | |
| 93 | + const tool = createMCPTool("test_action"); | |
| 94 | + | |
| 95 | + const result = getMCPToolName(server, tool); | |
| 96 | + // Should only contain alphanumeric characters and underscores | |
| 97 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 98 | + expect(result).toBe("my_server_name_test_action"); | |
| 99 | +}); | |
| 100 | + | |
| 101 | +test("getMCPToolName - handles multiple consecutive underscores in server name", () => { | |
| 102 | + const server = createMcpServer("Linear__MCP"); | |
| 103 | + const tool = createMCPTool("create_issue"); | |
| 104 | + | |
| 105 | + const result = getMCPToolName(server, tool); | |
| 106 | + // Should only contain alphanumeric characters and single underscores | |
| 107 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 108 | + expect(result).not.toMatch(/__/); | |
| 109 | + expect(result).toBe("linear_mcp_create_issue"); | |
| 110 | +}); |
modified core/tools/parseArgs.ts +20 −2
| @@ -20,11 +20,11 @@ | ||
| 20 | 20 | ): string { |
| 21 | 21 | if (!args || !(argName in args) || typeof args[argName] !== "string") { |
| 22 | 22 | throw new Error( |
| 23 | - `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`, | |
| 23 | + `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`, | |
| 24 | 24 | ); |
| 25 | 25 | } |
| 26 | 26 | if (!allowEmpty && !args[argName].trim()) { |
| 27 | - throw new Error(`Argument ${argName} must not be empty`); | |
| 27 | + throw new Error(`Argument ${argName} must not be empty or whitespace-only`); | |
| 28 | 28 | } |
| 29 | 29 | return args[argName]; |
| 30 | 30 | } |
| @@ -40,6 +40,24 @@ | ||
| 40 | 40 | return getStringArg(args, argName, allowEmpty); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | +export function getNumberArg(args: any, argName: string): number { | |
| 44 | + if (!args || !(argName in args)) { | |
| 45 | + throw new Error(`Argument \`${argName}\` is required (type number)`); | |
| 46 | + } | |
| 47 | + const value = args[argName]; | |
| 48 | + if (typeof value === "string") { | |
| 49 | + const parsed = parseInt(value, 10); | |
| 50 | + if (isNaN(parsed)) { | |
| 51 | + throw new Error(`Argument \`${argName}\` must be a valid number`); | |
| 52 | + } | |
| 53 | + return parsed; | |
| 54 | + } | |
| 55 | + if (typeof value !== "number" || isNaN(value)) { | |
| 56 | + throw new Error(`Argument \`${argName}\` must be a valid number`); | |
| 57 | + } | |
| 58 | + return Math.floor(value); // Ensure integer for line numbers (supports negative numbers) | |
| 59 | +} | |
| 60 | + | |
| 43 | 61 | export function getBooleanArg(args: any, argName: string, required = false) { |
| 44 | 62 | if (!args || !(argName in args)) { |
| 45 | 63 | if (required) { |
modified core/tools/parseArgs.vitest.ts +92 −8
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { ToolCallDelta } from ".."; |
| 3 | 3 | import { |
| 4 | 4 | getBooleanArg, |
| 5 | + getNumberArg, | |
| 5 | 6 | getOptionalStringArg, |
| 6 | 7 | getStringArg, |
| 7 | 8 | safeParseToolCallArgs, |
| @@ -102,26 +103,26 @@ | ||
| 102 | 103 | it("should throw error when argument is missing", () => { |
| 103 | 104 | const args = { otherArg: "test" }; |
| 104 | 105 | expect(() => getStringArg(args, "name")).toThrowError( |
| 105 | - "`name` argument is required and must not be empty. (type string)", | |
| 106 | + "`name` argument is required and must not be empty or whitespace-only. (type string)", | |
| 106 | 107 | ); |
| 107 | 108 | }); |
| 108 | 109 | |
| 109 | 110 | it("should throw error when argument is not a string", () => { |
| 110 | 111 | const args = { name: 123 }; |
| 111 | 112 | expect(() => getStringArg(args, "name")).toThrowError( |
| 112 | - "`name` argument is required and must not be empty. (type string)", | |
| 113 | + "`name` argument is required and must not be empty or whitespace-only. (type string)", | |
| 113 | 114 | ); |
| 114 | 115 | }); |
| 115 | 116 | |
| 116 | 117 | it("should throw error when argument is empty and empty not allowed", () => { |
| 117 | 118 | const args = { name: "" }; |
| 118 | 119 | expect(() => getStringArg(args, "name")).toThrowError( |
| 119 | - "Argument name must not be empty", | |
| 120 | + "Argument name must not be empty or whitespace-only", | |
| 120 | 121 | ); |
| 121 | 122 | |
| 122 | 123 | const argsWithSpace = { name: " " }; |
| 123 | 124 | expect(() => getStringArg(argsWithSpace, "name")).toThrowError( |
| 124 | - "Argument name must not be empty", | |
| 125 | + "Argument name must not be empty or whitespace-only", | |
| 125 | 126 | ); |
| 126 | 127 | }); |
| 127 | 128 | |
| @@ -137,10 +138,10 @@ | ||
| 137 | 138 | |
| 138 | 139 | it("should handle null or undefined args", () => { |
| 139 | 140 | expect(() => getStringArg(null, "name")).toThrowError( |
| 140 | - "`name` argument is required and must not be empty. (type string)", | |
| 141 | + "`name` argument is required and must not be empty or whitespace-only. (type string)", | |
| 141 | 142 | ); |
| 142 | 143 | expect(() => getStringArg(undefined, "name")).toThrowError( |
| 143 | - "`name` argument is required and must not be empty. (type string)", | |
| 144 | + "`name` argument is required and must not be empty or whitespace-only. (type string)", | |
| 144 | 145 | ); |
| 145 | 146 | }); |
| 146 | 147 | }); |
| @@ -161,14 +162,14 @@ | ||
| 161 | 162 | it("should throw error when argument is not a string", () => { |
| 162 | 163 | const args = { name: 123 }; |
| 163 | 164 | expect(() => getOptionalStringArg(args, "name")).toThrowError( |
| 164 | - "`name` argument is required and must not be empty. (type string)", | |
| 165 | + "`name` argument is required and must not be empty or whitespace-only. (type string)", | |
| 165 | 166 | ); |
| 166 | 167 | }); |
| 167 | 168 | |
| 168 | 169 | it("should throw error when argument is empty and empty not allowed", () => { |
| 169 | 170 | const args = { name: "" }; |
| 170 | 171 | expect(() => getOptionalStringArg(args, "name")).toThrowError( |
| 171 | - "Argument name must not be empty", | |
| 172 | + "Argument name must not be empty or whitespace-only", | |
| 172 | 173 | ); |
| 173 | 174 | }); |
| 174 | 175 | |
| @@ -246,3 +247,86 @@ | ||
| 246 | 247 | ); |
| 247 | 248 | }); |
| 248 | 249 | }); |
| 250 | + | |
| 251 | +describe("getNumberArg", () => { | |
| 252 | + it("should return number argument when valid", () => { | |
| 253 | + const args = { count: 42 }; | |
| 254 | + const result = getNumberArg(args, "count"); | |
| 255 | + expect(result).toBe(42); | |
| 256 | + }); | |
| 257 | + | |
| 258 | + it("should parse string numbers", () => { | |
| 259 | + const args = { count: "42" }; | |
| 260 | + const result = getNumberArg(args, "count"); | |
| 261 | + expect(result).toBe(42); | |
| 262 | + }); | |
| 263 | + | |
| 264 | + it("should floor decimal numbers", () => { | |
| 265 | + const args = { count: 42.7 }; | |
| 266 | + const result = getNumberArg(args, "count"); | |
| 267 | + expect(result).toBe(42); | |
| 268 | + }); | |
| 269 | + | |
| 270 | + it("should parse and floor string decimal numbers", () => { | |
| 271 | + const args = { count: "42.7" }; | |
| 272 | + const result = getNumberArg(args, "count"); | |
| 273 | + expect(result).toBe(42); | |
| 274 | + }); | |
| 275 | + | |
| 276 | + it("should throw error when argument is missing", () => { | |
| 277 | + const args = { otherArg: 42 }; | |
| 278 | + expect(() => getNumberArg(args, "count")).toThrowError( | |
| 279 | + "Argument `count` is required (type number)", | |
| 280 | + ); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + it("should throw error when argument is not a number", () => { | |
| 284 | + const argsString = { count: "not-a-number" }; | |
| 285 | + const argsBoolean = { count: true }; | |
| 286 | + const argsObject = { count: {} }; | |
| 287 | + | |
| 288 | + expect(() => getNumberArg(argsString, "count")).toThrowError( | |
| 289 | + "Argument `count` must be a valid number", | |
| 290 | + ); | |
| 291 | + expect(() => getNumberArg(argsBoolean, "count")).toThrowError( | |
| 292 | + "Argument `count` must be a valid number", | |
| 293 | + ); | |
| 294 | + expect(() => getNumberArg(argsObject, "count")).toThrowError( | |
| 295 | + "Argument `count` must be a valid number", | |
| 296 | + ); | |
| 297 | + }); | |
| 298 | + | |
| 299 | + it("should throw error when argument is NaN", () => { | |
| 300 | + const args = { count: NaN }; | |
| 301 | + expect(() => getNumberArg(args, "count")).toThrowError( | |
| 302 | + "Argument `count` must be a valid number", | |
| 303 | + ); | |
| 304 | + }); | |
| 305 | + | |
| 306 | + it("should handle negative numbers", () => { | |
| 307 | + const args = { count: -5 }; | |
| 308 | + const result = getNumberArg(args, "count"); | |
| 309 | + expect(result).toBe(-5); | |
| 310 | + }); | |
| 311 | + | |
| 312 | + it("should handle negative string numbers", () => { | |
| 313 | + const args = { count: "-10" }; | |
| 314 | + const result = getNumberArg(args, "count"); | |
| 315 | + expect(result).toBe(-10); | |
| 316 | + }); | |
| 317 | + | |
| 318 | + it("should handle zero", () => { | |
| 319 | + const args = { count: 0 }; | |
| 320 | + const result = getNumberArg(args, "count"); | |
| 321 | + expect(result).toBe(0); | |
| 322 | + }); | |
| 323 | + | |
| 324 | + it("should handle null or undefined args", () => { | |
| 325 | + expect(() => getNumberArg(null, "count")).toThrowError( | |
| 326 | + "Argument `count` is required (type number)", | |
| 327 | + ); | |
| 328 | + expect(() => getNumberArg(undefined, "count")).toThrowError( | |
| 329 | + "Argument `count` is required (type number)", | |
| 330 | + ); | |
| 331 | + }); | |
| 332 | +}); |
added core/tools/searchWebGating.vitest.ts +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +import { expect, test } from "vitest"; | |
| 2 | +import { BuiltInToolNames } from "./builtIn"; | |
| 3 | +import { getConfigDependentToolDefinitions } from "./index"; | |
| 4 | + | |
| 5 | +test("searchWeb tool is only available when user is signed in", () => { | |
| 6 | + // Test with signed-in user | |
| 7 | + const signedInTools = getConfigDependentToolDefinitions({ | |
| 8 | + rules: [], | |
| 9 | + enableExperimentalTools: false, | |
| 10 | + isSignedIn: true, | |
| 11 | + isRemote: false, | |
| 12 | + modelName: "", | |
| 13 | + }); | |
| 14 | + | |
| 15 | + const searchWebToolSignedIn = signedInTools.find( | |
| 16 | + (tool) => tool.function.name === BuiltInToolNames.SearchWeb, | |
| 17 | + ); | |
| 18 | + expect(searchWebToolSignedIn).toBeDefined(); | |
| 19 | + expect(searchWebToolSignedIn?.displayTitle).toBe("Search Web"); | |
| 20 | + | |
| 21 | + // Test with non-signed-in user | |
| 22 | + const notSignedInTools = getConfigDependentToolDefinitions({ | |
| 23 | + rules: [], | |
| 24 | + enableExperimentalTools: false, | |
| 25 | + isSignedIn: false, | |
| 26 | + isRemote: false, | |
| 27 | + modelName: "", | |
| 28 | + }); | |
| 29 | + | |
| 30 | + const searchWebToolNotSignedIn = notSignedInTools.find( | |
| 31 | + (tool) => tool.function.name === BuiltInToolNames.SearchWeb, | |
| 32 | + ); | |
| 33 | + expect(searchWebToolNotSignedIn).toBeUndefined(); | |
| 34 | +}); |
modified core/util/GlobalContext.ts +7 −25
| @@ -39,13 +39,13 @@ | ||
| 39 | 39 | */ |
| 40 | 40 | hasDismissedConfigTsNoticeJetBrains: boolean; |
| 41 | 41 | hasAlreadyCreatedAPromptFile: boolean; |
| 42 | + hasShownUnsupportedPlatformWarning: boolean; | |
| 42 | 43 | showConfigUpdateToast: boolean; |
| 43 | 44 | isSupportedLanceDbCpuTargetForLinux: boolean; |
| 44 | 45 | sharedConfig: SharedConfigSchema; |
| 45 | 46 | failedDocs: SiteIndexingConfig[]; |
| 46 | - shownDeprecatedProviderWarnings: { | |
| 47 | - [providerTitle: string]: boolean; | |
| 48 | - }; | |
| 47 | + shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean }; | |
| 48 | + autoUpdateCli: boolean; | |
| 49 | 49 | mcpOauthStorage: { |
| 50 | 50 | [serverUrl: string]: { |
| 51 | 51 | clientInformation?: OAuthClientInformationFull; |
| @@ -65,16 +65,7 @@ | ||
| 65 | 65 | ) { |
| 66 | 66 | const filepath = getGlobalContextFilePath(); |
| 67 | 67 | if (!fs.existsSync(filepath)) { |
| 68 | - fs.writeFileSync( | |
| 69 | - filepath, | |
| 70 | - JSON.stringify( | |
| 71 | - { | |
| 72 | - [key]: value, | |
| 73 | - }, | |
| 74 | - null, | |
| 75 | - 2, | |
| 76 | - ), | |
| 77 | - ); | |
| 68 | + fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2)); | |
| 78 | 69 | } else { |
| 79 | 70 | const data = fs.readFileSync(filepath, "utf-8"); |
| 80 | 71 | |
| @@ -112,10 +103,7 @@ | ||
| 112 | 103 | } |
| 113 | 104 | |
| 114 | 105 | // Recreate the file with salvaged values plus the new value |
| 115 | - const newData = { | |
| 116 | - ...salvaged, | |
| 117 | - [key]: value, | |
| 118 | - }; | |
| 106 | + const newData = { ...salvaged, [key]: value }; | |
| 119 | 107 | |
| 120 | 108 | fs.writeFileSync(filepath, JSON.stringify(newData, null, 2)); |
| 121 | 109 | return; |
| @@ -173,10 +161,7 @@ | ||
| 173 | 161 | newValues: Partial<SharedConfigSchema>, |
| 174 | 162 | ): SharedConfigSchema { |
| 175 | 163 | const currentSharedConfig = this.getSharedConfig(); |
| 176 | - const updatedSharedConfig = { | |
| 177 | - ...currentSharedConfig, | |
| 178 | - ...newValues, | |
| 179 | - }; | |
| 164 | + const updatedSharedConfig = { ...currentSharedConfig, ...newValues }; | |
| 180 | 165 | this.update("sharedConfig", updatedSharedConfig); |
| 181 | 166 | return updatedSharedConfig; |
| 182 | 167 | } |
| @@ -188,10 +173,7 @@ | ||
| 188 | 173 | ): GlobalContextModelSelections { |
| 189 | 174 | const currentSelections = this.get("selectedModelsByProfileId") ?? {}; |
| 190 | 175 | const forProfile = currentSelections[profileId] ?? {}; |
| 191 | - const newSelections = { | |
| 192 | - ...forProfile, | |
| 193 | - [role]: title, | |
| 194 | - }; | |
| 176 | + const newSelections = { ...forProfile, [role]: title }; | |
| 195 | 177 | |
| 196 | 178 | this.update("selectedModelsByProfileId", { |
| 197 | 179 | ...currentSelections, |
added core/util/TokensBatchingService.ts +106 −0
| @@ -0,0 +1,106 @@ | ||
| 1 | +import { Telemetry } from "./posthog.js"; | |
| 2 | + | |
| 3 | +interface TokenBatch { | |
| 4 | + model: string; | |
| 5 | + provider: string; | |
| 6 | + count: number; | |
| 7 | + totalPromptTokens: number; | |
| 8 | + totalGeneratedTokens: number; | |
| 9 | + lastEventTime: number; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export class TokensBatchingService { | |
| 13 | + private static instance: TokensBatchingService; | |
| 14 | + private batches = new Map<string, TokenBatch>(); | |
| 15 | + private flushTimer: NodeJS.Timeout | null = null; | |
| 16 | + | |
| 17 | + private readonly BATCH_SIZE_LIMIT = 25; | |
| 18 | + private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes | |
| 19 | + | |
| 20 | + static getInstance(): TokensBatchingService { | |
| 21 | + if (!TokensBatchingService.instance) { | |
| 22 | + TokensBatchingService.instance = new TokensBatchingService(); | |
| 23 | + } | |
| 24 | + return TokensBatchingService.instance; | |
| 25 | + } | |
| 26 | + | |
| 27 | + private constructor() { | |
| 28 | + this.startFlushTimer(); | |
| 29 | + } | |
| 30 | + | |
| 31 | + addTokens( | |
| 32 | + model: string, | |
| 33 | + provider: string, | |
| 34 | + promptTokens: number, | |
| 35 | + generatedTokens: number, | |
| 36 | + ): void { | |
| 37 | + const key = `${provider}:${model}`; | |
| 38 | + | |
| 39 | + if (!this.batches.has(key)) { | |
| 40 | + this.batches.set(key, { | |
| 41 | + model, | |
| 42 | + provider, | |
| 43 | + count: 0, | |
| 44 | + totalPromptTokens: 0, | |
| 45 | + totalGeneratedTokens: 0, | |
| 46 | + lastEventTime: Date.now(), | |
| 47 | + }); | |
| 48 | + } | |
| 49 | + | |
| 50 | + const batch = this.batches.get(key)!; | |
| 51 | + batch.count++; | |
| 52 | + batch.totalPromptTokens += promptTokens; | |
| 53 | + batch.totalGeneratedTokens += generatedTokens; | |
| 54 | + batch.lastEventTime = Date.now(); | |
| 55 | + | |
| 56 | + // Flush if batch is full | |
| 57 | + if (batch.count >= this.BATCH_SIZE_LIMIT) { | |
| 58 | + this.flushBatch(key, batch); | |
| 59 | + } | |
| 60 | + } | |
| 61 | + | |
| 62 | + private flushBatch(key: string, batch: TokenBatch): void { | |
| 63 | + if (batch.count === 0) return; | |
| 64 | + | |
| 65 | + void Telemetry.capture( | |
| 66 | + "tokens_generated_batch", | |
| 67 | + { | |
| 68 | + model: batch.model, | |
| 69 | + provider: batch.provider, | |
| 70 | + eventCount: batch.count, | |
| 71 | + totalPromptTokens: batch.totalPromptTokens, | |
| 72 | + totalGeneratedTokens: batch.totalGeneratedTokens, | |
| 73 | + avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count), | |
| 74 | + avgGeneratedTokens: Math.round( | |
| 75 | + batch.totalGeneratedTokens / batch.count, | |
| 76 | + ), | |
| 77 | + }, | |
| 78 | + true, | |
| 79 | + ); | |
| 80 | + | |
| 81 | + this.batches.delete(key); | |
| 82 | + } | |
| 83 | + | |
| 84 | + private startFlushTimer(): void { | |
| 85 | + this.flushTimer = setInterval(() => { | |
| 86 | + this.flushAllBatches(); | |
| 87 | + }, this.FLUSH_INTERVAL_MS); | |
| 88 | + // Allow the process to exit if this timer is the only thing keeping it alive | |
| 89 | + // This prevents test hangs and allows graceful shutdown | |
| 90 | + this.flushTimer.unref(); | |
| 91 | + } | |
| 92 | + | |
| 93 | + private flushAllBatches(): void { | |
| 94 | + for (const [key, batch] of this.batches.entries()) { | |
| 95 | + this.flushBatch(key, batch); | |
| 96 | + } | |
| 97 | + } | |
| 98 | + | |
| 99 | + shutdown(): void { | |
| 100 | + if (this.flushTimer) { | |
| 101 | + clearInterval(this.flushTimer); | |
| 102 | + this.flushTimer = null; | |
| 103 | + } | |
| 104 | + this.flushAllBatches(); | |
| 105 | + } | |
| 106 | +} |
modified core/util/chatDescriber.ts +61 −0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; |
| 6 | 6 | import type { IMessenger } from "../protocol/messenger"; |
| 7 | 7 | import { renderChatMessage } from "./messageContent"; |
| 8 | +import { convertFromUnifiedHistory } from "./messageConversion"; | |
| 8 | 9 | |
| 9 | 10 | export class ChatDescriber { |
| 10 | 11 | static maxTokens = 12; |
| @@ -46,6 +47,66 @@ | ||
| 46 | 47 | return removeQuotesAndEscapes(renderChatMessage(titleResponse)); |
| 47 | 48 | } |
| 48 | 49 | |
| 50 | + // CLI-specific method that works with BaseLlmApi | |
| 51 | + static async describeWithBaseLlmApi( | |
| 52 | + llmApi: any, // BaseLlmApi - using any to avoid import issues | |
| 53 | + modelConfig: any, // ModelConfig - using any to avoid import issues | |
| 54 | + message: string, | |
| 55 | + ): Promise<string | undefined> { | |
| 56 | + if (!ChatDescriber.prompt) { | |
| 57 | + return; | |
| 58 | + } | |
| 59 | + | |
| 60 | + // Clean up and distill the message we want to send to the LLM | |
| 61 | + message = removeCodeBlocksAndTrim(message); | |
| 62 | + | |
| 63 | + if (!message) { | |
| 64 | + return; | |
| 65 | + } | |
| 66 | + | |
| 67 | + try { | |
| 68 | + // Create the chat message in the unified format | |
| 69 | + const chatMessage = { | |
| 70 | + role: "user" as const, | |
| 71 | + content: ChatDescriber.prompt + message, | |
| 72 | + }; | |
| 73 | + | |
| 74 | + // Convert to OpenAI format - use a simple fallback to avoid import issues | |
| 75 | + const openaiMessages = convertFromUnifiedHistory([ | |
| 76 | + { | |
| 77 | + message: chatMessage, | |
| 78 | + contextItems: [], | |
| 79 | + }, | |
| 80 | + ]); | |
| 81 | + | |
| 82 | + // Set up completion options for non-streaming | |
| 83 | + const completionOptions = { | |
| 84 | + model: modelConfig.model, | |
| 85 | + messages: openaiMessages, | |
| 86 | + max_tokens: ChatDescriber.maxTokens, | |
| 87 | + stream: false as const, | |
| 88 | + }; | |
| 89 | + | |
| 90 | + // Call the LLM | |
| 91 | + const titleResponse = await llmApi.chatCompletionNonStream( | |
| 92 | + completionOptions, | |
| 93 | + new AbortController().signal, | |
| 94 | + ); | |
| 95 | + | |
| 96 | + // Extract and clean up the response | |
| 97 | + if (titleResponse.choices && titleResponse.choices.length > 0) { | |
| 98 | + const content = titleResponse.choices[0].message.content; | |
| 99 | + if (content) { | |
| 100 | + return removeQuotesAndEscapes(content); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + return undefined; | |
| 105 | + } catch (error) { | |
| 106 | + return undefined; | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 49 | 110 | // // TODO: Allow the user to manually set specific/tailored prompts to generate their titles |
| 50 | 111 | // static async setup() { |
| 51 | 112 | // if(config?.prompt) { |
modified core/util/errors.ts +41 −0
| @@ -10,3 +10,44 @@ | ||
| 10 | 10 | } |
| 11 | 11 | return err; |
| 12 | 12 | } |
| 13 | + | |
| 14 | +export class ContinueError extends Error { | |
| 15 | + reason: ContinueErrorReason; | |
| 16 | + | |
| 17 | + constructor(reason: ContinueErrorReason, message?: string) { | |
| 18 | + super(message); | |
| 19 | + this.reason = reason; | |
| 20 | + this.name = "ContinueError"; | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +export enum ContinueErrorReason { | |
| 25 | + // Find and Replace validation errors | |
| 26 | + FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings", | |
| 27 | + FindAndReplaceMissingOldString = "find_and_replace_missing_old_string", | |
| 28 | + FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string", | |
| 29 | + FindAndReplaceMissingNewString = "find_and_replace_missing_new_string", | |
| 30 | + FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found", | |
| 31 | + FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences", | |
| 32 | + FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath", | |
| 33 | + | |
| 34 | + // Multi-edit | |
| 35 | + MultiEditEditsArrayRequired = "multi_edit_edits_array_required", | |
| 36 | + MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty", | |
| 37 | + MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation", | |
| 38 | + MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first", | |
| 39 | + | |
| 40 | + // General Edit | |
| 41 | + EditToolFileNotRead = "edit_tool_file_not_yet_read", | |
| 42 | + | |
| 43 | + // General File | |
| 44 | + FileAlreadyExists = "file_already_exists", | |
| 45 | + FileNotFound = "file_not_found", | |
| 46 | + FileWriteError = "file_write_error", | |
| 47 | + FileIsSecurityConcern = "file_is_security_concern", | |
| 48 | + ParentDirectoryNotFound = "parent_directory_not_found", | |
| 49 | + | |
| 50 | + // Other | |
| 51 | + Unspecified = "unspecified", | |
| 52 | + Unknown = "unknown", | |
| 53 | +} |
modified core/util/history.test.ts +6 −2
| @@ -93,8 +93,9 @@ | ||
| 93 | 93 | const offset = 10; |
| 94 | 94 | |
| 95 | 95 | const sessions = historyManager.list({ offset: offset, limit: limit }); |
| 96 | + // Sessions are now reversed, so newest (99) comes first | |
| 96 | 97 | const sessionIds = Array.from({ length: limit }, (_, i) => |
| 97 | - (i + offset).toString(), | |
| 98 | + (99 - offset - i).toString(), | |
| 98 | 99 | ); |
| 99 | 100 | const isSessionIdInList = (sessionId: string) => |
| 100 | 101 | sessions.some((session) => session.sessionId === sessionId); |
| @@ -105,7 +106,10 @@ | ||
| 105 | 106 | const limit = 25; |
| 106 | 107 | |
| 107 | 108 | const sessions = historyManager.list({ limit: limit }); |
| 108 | - const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); | |
| 109 | + // Sessions are now reversed, so newest (99) comes first | |
| 110 | + const sessionIds = Array.from({ length: limit }, (_, i) => | |
| 111 | + (99 - i).toString(), | |
| 112 | + ); | |
| 109 | 113 | |
| 110 | 114 | const isSessionIdInList = (sessionId: string) => |
| 111 | 115 | sessions.some((session) => session.sessionId === sessionId); |
modified core/util/history.ts +13 −10
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | |
| 3 | -import { Session, SessionMetadata } from "../index.js"; | |
| 3 | +import { Session, BaseSessionMetadata } from "../index.js"; | |
| 4 | 4 | import { ListHistoryOptions } from "../protocol/core.js"; |
| 5 | 5 | |
| 6 | 6 | import { NEW_SESSION_TITLE } from "./constants.js"; |
| @@ -22,18 +22,21 @@ | ||
| 22 | 22 | } |
| 23 | 23 | |
| 24 | 24 | export class HistoryManager { |
| 25 | - list(options: ListHistoryOptions): SessionMetadata[] { | |
| 25 | + list(options: ListHistoryOptions): BaseSessionMetadata[] { | |
| 26 | 26 | const filepath = getSessionsListPath(); |
| 27 | 27 | if (!fs.existsSync(filepath)) { |
| 28 | 28 | return []; |
| 29 | 29 | } |
| 30 | 30 | const content = fs.readFileSync(filepath, "utf8"); |
| 31 | 31 | |
| 32 | - let sessions = safeParseArray<SessionMetadata>(content) ?? []; | |
| 33 | - sessions = sessions.filter((session: any) => { | |
| 34 | - // Filter out old format | |
| 35 | - return typeof session.session_id !== "string"; | |
| 36 | - }); | |
| 32 | + let sessions = safeParseArray<BaseSessionMetadata>(content) ?? []; | |
| 33 | + sessions = sessions | |
| 34 | + .filter((session: any) => { | |
| 35 | + // Filter out old format | |
| 36 | + return typeof session.session_id !== "string"; | |
| 37 | + // Reverse to show newest first; sessions.json is chronological by creation | |
| 38 | + }) | |
| 39 | + .reverse(); | |
| 37 | 40 | |
| 38 | 41 | // Apply limit and offset |
| 39 | 42 | if (options.limit) { |
| @@ -56,7 +59,7 @@ | ||
| 56 | 59 | const sessionsListFile = getSessionsListPath(); |
| 57 | 60 | const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); |
| 58 | 61 | let sessionsList = |
| 59 | - safeParseArray<SessionMetadata>( | |
| 62 | + safeParseArray<BaseSessionMetadata>( | |
| 60 | 63 | sessionsListRaw, |
| 61 | 64 | "Error parsing sessions.json", |
| 62 | 65 | ) ?? []; |
| @@ -115,7 +118,7 @@ | ||
| 115 | 118 | try { |
| 116 | 119 | const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8"); |
| 117 | 120 | |
| 118 | - let sessionsList: SessionMetadata[]; | |
| 121 | + let sessionsList: BaseSessionMetadata[]; | |
| 119 | 122 | try { |
| 120 | 123 | sessionsList = JSON.parse(rawSessionsList); |
| 121 | 124 | } catch (e) { |
| @@ -138,7 +141,7 @@ | ||
| 138 | 141 | } |
| 139 | 142 | |
| 140 | 143 | if (!found) { |
| 141 | - const sessionMetadata: SessionMetadata = { | |
| 144 | + const sessionMetadata: BaseSessionMetadata = { | |
| 142 | 145 | sessionId: session.sessionId, |
| 143 | 146 | title: session.title, |
| 144 | 147 | dateCreated: String(Date.now()), |
added core/util/lemonadeHelper.ts +59 −0
| @@ -0,0 +1,59 @@ | ||
| 1 | +import { exec } from "node:child_process"; | |
| 2 | +import { IDE } from ".."; | |
| 3 | + | |
| 4 | +export async function isLemonadeInstalled(): Promise<boolean> { | |
| 5 | + // On Windows, check if lemonade-server command exists | |
| 6 | + if (process.platform === "win32") { | |
| 7 | + return new Promise((resolve, _reject) => { | |
| 8 | + exec("where.exe lemonade-server", (error, _stdout, _stderr) => { | |
| 9 | + resolve(!error); | |
| 10 | + }); | |
| 11 | + }); | |
| 12 | + } | |
| 13 | + | |
| 14 | + // On Linux, check if the health endpoint is accessible | |
| 15 | + try { | |
| 16 | + const response = await fetch("http://localhost:8000/api/v1/health", { | |
| 17 | + method: "GET", | |
| 18 | + signal: AbortSignal.timeout(3000), // 3 second timeout | |
| 19 | + }); | |
| 20 | + | |
| 21 | + if (response.ok) { | |
| 22 | + const data = await response.json(); | |
| 23 | + return data.status === "ok"; | |
| 24 | + } | |
| 25 | + return false; | |
| 26 | + } catch { | |
| 27 | + return false; | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +export async function startLocalLemonade(ide: IDE): Promise<any> { | |
| 32 | + let startCommand: string | undefined; | |
| 33 | + | |
| 34 | + switch (process.platform) { | |
| 35 | + case "linux": // Linux | |
| 36 | + // On Linux, direct users to start Lemonade manually | |
| 37 | + return ide.showToast( | |
| 38 | + "info", | |
| 39 | + "Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.", | |
| 40 | + ); | |
| 41 | + | |
| 42 | + case "win32": // Windows | |
| 43 | + startCommand = "lemonade-server serve\n"; | |
| 44 | + break; | |
| 45 | + | |
| 46 | + default: | |
| 47 | + return ide.showToast( | |
| 48 | + "error", | |
| 49 | + "Cannot start Lemonade: platform not supported!", | |
| 50 | + ); | |
| 51 | + } | |
| 52 | + | |
| 53 | + if (startCommand) { | |
| 54 | + return ide.runCommand(startCommand, { | |
| 55 | + reuseTerminal: true, | |
| 56 | + terminalName: "Start Lemonade", | |
| 57 | + }); | |
| 58 | + } | |
| 59 | +} |
modified core/util/messageContent.ts +15 −0
| @@ -35,6 +35,21 @@ | ||
| 35 | 35 | return contextItems.map((item) => item.content).join("\n\n"); |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | +export function renderContextItemsWithStatus(contextItems: any[]): string { | |
| 39 | + return contextItems | |
| 40 | + .map((item) => { | |
| 41 | + let result = item.content; | |
| 42 | + | |
| 43 | + // If this item has a status, append it directly after the content | |
| 44 | + if (item.status) { | |
| 45 | + result += `\n[Status: ${item.status}]`; | |
| 46 | + } | |
| 47 | + | |
| 48 | + return result; | |
| 49 | + }) | |
| 50 | + .join("\n\n"); | |
| 51 | +} | |
| 52 | + | |
| 38 | 53 | export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { |
| 39 | 54 | switch (message.role) { |
| 40 | 55 | case "user": |
added core/util/messageConversion.ts +399 −0
| @@ -0,0 +1,399 @@ | ||
| 1 | +/** | |
| 2 | + * Message conversion utilities for transitioning to unified ChatHistoryItem type. | |
| 3 | + * | |
| 4 | + * This module provides conversion functions between the OpenAI ChatCompletionMessageParam | |
| 5 | + * format and the unified ChatHistoryItem format from the core package. | |
| 6 | + */ | |
| 7 | + | |
| 8 | +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 9 | +import type { | |
| 10 | + AssistantChatMessage, | |
| 11 | + ChatHistoryItem, | |
| 12 | + ChatMessage, | |
| 13 | + ContextItemWithId, | |
| 14 | + MessageContent, | |
| 15 | + ToolCall, | |
| 16 | + ToolCallState, | |
| 17 | + ToolStatus, | |
| 18 | +} from "../index.js"; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * Convert ChatCompletionMessageParam to ChatMessage | |
| 22 | + */ | |
| 23 | +export function convertToUnifiedMessage( | |
| 24 | + message: ChatCompletionMessageParam, | |
| 25 | +): ChatMessage { | |
| 26 | + switch (message.role) { | |
| 27 | + case "system": | |
| 28 | + return { | |
| 29 | + role: "system", | |
| 30 | + content: typeof message.content === "string" ? message.content : "", | |
| 31 | + }; | |
| 32 | + | |
| 33 | + case "user": | |
| 34 | + return { | |
| 35 | + role: "user", | |
| 36 | + content: convertMessageContent(message.content), | |
| 37 | + }; | |
| 38 | + | |
| 39 | + case "assistant": { | |
| 40 | + const assistantMessage: AssistantChatMessage = { | |
| 41 | + role: "assistant", | |
| 42 | + content: convertMessageContent(message.content || ""), | |
| 43 | + }; | |
| 44 | + | |
| 45 | + // Convert tool calls if present | |
| 46 | + if ("tool_calls" in message && message.tool_calls) { | |
| 47 | + assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({ | |
| 48 | + id: tc.id, | |
| 49 | + type: "function" as const, | |
| 50 | + function: { | |
| 51 | + name: tc.function?.name || "", | |
| 52 | + arguments: tc.function?.arguments || "", | |
| 53 | + }, | |
| 54 | + })); | |
| 55 | + } | |
| 56 | + | |
| 57 | + return assistantMessage; | |
| 58 | + } | |
| 59 | + | |
| 60 | + case "tool": | |
| 61 | + return { | |
| 62 | + role: "tool", | |
| 63 | + content: typeof message.content === "string" ? message.content : "", | |
| 64 | + toolCallId: message.tool_call_id, | |
| 65 | + }; | |
| 66 | + | |
| 67 | + default: | |
| 68 | + throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +/** | |
| 73 | + * Convert ChatMessage to ChatCompletionMessageParam | |
| 74 | + */ | |
| 75 | +export function convertFromUnifiedMessage( | |
| 76 | + message: ChatMessage, | |
| 77 | +): ChatCompletionMessageParam { | |
| 78 | + switch (message.role) { | |
| 79 | + case "system": | |
| 80 | + return { | |
| 81 | + role: "system", | |
| 82 | + content: message.content, | |
| 83 | + }; | |
| 84 | + | |
| 85 | + case "user": | |
| 86 | + return { | |
| 87 | + role: "user", | |
| 88 | + content: convertFromMessageContent(message.content), | |
| 89 | + }; | |
| 90 | + | |
| 91 | + case "assistant": { | |
| 92 | + const assistantMessage: ChatCompletionMessageParam = { | |
| 93 | + role: "assistant", | |
| 94 | + content: convertFromMessageContent(message.content), | |
| 95 | + }; | |
| 96 | + | |
| 97 | + // Convert tool calls if present | |
| 98 | + if (message.toolCalls && message.toolCalls.length > 0) { | |
| 99 | + (assistantMessage as any).tool_calls = message.toolCalls.map( | |
| 100 | + (tc: any) => ({ | |
| 101 | + id: tc.id, | |
| 102 | + type: "function", | |
| 103 | + function: { | |
| 104 | + name: tc.function?.name || "", | |
| 105 | + arguments: tc.function?.arguments || "", | |
| 106 | + }, | |
| 107 | + }), | |
| 108 | + ); | |
| 109 | + } | |
| 110 | + | |
| 111 | + return assistantMessage; | |
| 112 | + } | |
| 113 | + | |
| 114 | + case "tool": | |
| 115 | + return { | |
| 116 | + role: "tool", | |
| 117 | + content: message.content, | |
| 118 | + tool_call_id: message.toolCallId, | |
| 119 | + }; | |
| 120 | + | |
| 121 | + case "thinking": | |
| 122 | + // Thinking messages don't have a direct equivalent in OpenAI format | |
| 123 | + // Convert to assistant message with content | |
| 124 | + return { | |
| 125 | + role: "assistant", | |
| 126 | + content: convertFromMessageContent(message.content), | |
| 127 | + }; | |
| 128 | + | |
| 129 | + default: | |
| 130 | + throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 131 | + } | |
| 132 | +} | |
| 133 | + | |
| 134 | +/** | |
| 135 | + * Convert OpenAI message content to unified MessageContent format | |
| 136 | + */ | |
| 137 | +function convertMessageContent( | |
| 138 | + content: string | null | Array<any>, | |
| 139 | +): MessageContent { | |
| 140 | + if (content === null) { | |
| 141 | + return ""; | |
| 142 | + } | |
| 143 | + | |
| 144 | + if (typeof content === "string") { | |
| 145 | + return content; | |
| 146 | + } | |
| 147 | + | |
| 148 | + if (Array.isArray(content)) { | |
| 149 | + return content.map((part: any) => { | |
| 150 | + if (part.type === "text") { | |
| 151 | + return { | |
| 152 | + type: "text" as const, | |
| 153 | + text: part.text, | |
| 154 | + }; | |
| 155 | + } else if (part.type === "image_url") { | |
| 156 | + return { | |
| 157 | + type: "imageUrl" as const, | |
| 158 | + imageUrl: { url: part.image_url.url }, | |
| 159 | + }; | |
| 160 | + } | |
| 161 | + throw new Error(`Unsupported content part type: ${part.type}`); | |
| 162 | + }); | |
| 163 | + } | |
| 164 | + | |
| 165 | + throw new Error(`Unsupported content type: ${typeof content}`); | |
| 166 | +} | |
| 167 | + | |
| 168 | +/** | |
| 169 | + * Convert unified MessageContent to OpenAI format | |
| 170 | + */ | |
| 171 | +function convertFromMessageContent( | |
| 172 | + content: MessageContent, | |
| 173 | +): string | Array<any> { | |
| 174 | + if (typeof content === "string") { | |
| 175 | + return content; | |
| 176 | + } | |
| 177 | + | |
| 178 | + if (Array.isArray(content)) { | |
| 179 | + return content.map((part: any) => { | |
| 180 | + if (part.type === "text") { | |
| 181 | + return { | |
| 182 | + type: "text", | |
| 183 | + text: part.text, | |
| 184 | + }; | |
| 185 | + } else if (part.type === "imageUrl") { | |
| 186 | + return { | |
| 187 | + type: "image_url", | |
| 188 | + image_url: { url: part.imageUrl.url }, | |
| 189 | + }; | |
| 190 | + } | |
| 191 | + throw new Error(`Unsupported content part type: ${part.type}`); | |
| 192 | + }); | |
| 193 | + } | |
| 194 | + | |
| 195 | + throw new Error(`Unsupported content type: ${typeof content}`); | |
| 196 | +} | |
| 197 | + | |
| 198 | +/** | |
| 199 | + * Create a ChatHistoryItem from a ChatMessage | |
| 200 | + */ | |
| 201 | +export function createHistoryItem( | |
| 202 | + message: ChatMessage, | |
| 203 | + contextItems: ContextItemWithId[] = [], | |
| 204 | + toolCallStates?: ToolCallState[], | |
| 205 | +): ChatHistoryItem { | |
| 206 | + return { | |
| 207 | + message, | |
| 208 | + contextItems, | |
| 209 | + ...(toolCallStates && { toolCallStates }), | |
| 210 | + }; | |
| 211 | +} | |
| 212 | + | |
| 213 | +/** | |
| 214 | + * Handle tool result message by updating the corresponding tool call state | |
| 215 | + */ | |
| 216 | +function handleToolResult( | |
| 217 | + unifiedMessage: ChatMessage & { role: "tool" }, | |
| 218 | + pendingToolCalls: Map<string, ToolCall>, | |
| 219 | + historyItems: ChatHistoryItem[], | |
| 220 | +): void { | |
| 221 | + const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId); | |
| 222 | + if (!toolCall) return; | |
| 223 | + | |
| 224 | + // Add tool result as context to the previous assistant message | |
| 225 | + let lastAssistantIndex = -1; | |
| 226 | + for (let i = historyItems.length - 1; i >= 0; i--) { | |
| 227 | + if (historyItems[i].message.role === "assistant") { | |
| 228 | + lastAssistantIndex = i; | |
| 229 | + break; | |
| 230 | + } | |
| 231 | + } | |
| 232 | + if (lastAssistantIndex < 0) return; | |
| 233 | + if (!historyItems[lastAssistantIndex].toolCallStates) return; | |
| 234 | + | |
| 235 | + const toolState = historyItems[lastAssistantIndex].toolCallStates?.find( | |
| 236 | + (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId, | |
| 237 | + ); | |
| 238 | + | |
| 239 | + if (toolState) { | |
| 240 | + toolState.output = [ | |
| 241 | + { | |
| 242 | + content: unifiedMessage.content as string, | |
| 243 | + name: `Tool Result: ${toolCall.function.name}`, | |
| 244 | + description: "Tool execution result", | |
| 245 | + }, | |
| 246 | + ]; | |
| 247 | + } | |
| 248 | +} | |
| 249 | + | |
| 250 | +/** | |
| 251 | + * Convert array of ChatCompletionMessageParam to ChatHistoryItem array | |
| 252 | + */ | |
| 253 | +export function convertToUnifiedHistory( | |
| 254 | + messages: ChatCompletionMessageParam[], | |
| 255 | +): ChatHistoryItem[] { | |
| 256 | + const historyItems: ChatHistoryItem[] = []; | |
| 257 | + const pendingToolCalls: Map<string, ToolCall> = new Map(); | |
| 258 | + | |
| 259 | + for (const message of messages) { | |
| 260 | + const unifiedMessage = convertToUnifiedMessage(message); | |
| 261 | + | |
| 262 | + if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) { | |
| 263 | + // Store tool calls for matching with results | |
| 264 | + const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map( | |
| 265 | + (tc: any) => { | |
| 266 | + const toolCall: ToolCall = { | |
| 267 | + id: tc.id || "", | |
| 268 | + type: "function", | |
| 269 | + function: { | |
| 270 | + name: tc.function?.name || "", | |
| 271 | + arguments: tc.function?.arguments || "", | |
| 272 | + }, | |
| 273 | + }; | |
| 274 | + pendingToolCalls.set(toolCall.id, toolCall); | |
| 275 | + | |
| 276 | + return { | |
| 277 | + toolCallId: toolCall.id, | |
| 278 | + toolCall, | |
| 279 | + status: "done" as ToolStatus, // Historical calls are complete | |
| 280 | + parsedArgs: tryParseJson(toolCall.function.arguments), | |
| 281 | + }; | |
| 282 | + }, | |
| 283 | + ); | |
| 284 | + | |
| 285 | + historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates)); | |
| 286 | + } else if (unifiedMessage.role === "tool") { | |
| 287 | + // Tool result - handle separately to reduce nesting | |
| 288 | + handleToolResult(unifiedMessage, pendingToolCalls, historyItems); | |
| 289 | + // Don't add tool messages as separate history items | |
| 290 | + } else { | |
| 291 | + historyItems.push(createHistoryItem(unifiedMessage)); | |
| 292 | + } | |
| 293 | + } | |
| 294 | + | |
| 295 | + return historyItems; | |
| 296 | +} | |
| 297 | + | |
| 298 | +/** | |
| 299 | + * Convert ChatHistoryItem array to ChatCompletionMessageParam array | |
| 300 | + */ | |
| 301 | +export function convertFromUnifiedHistory( | |
| 302 | + historyItems: ChatHistoryItem[], | |
| 303 | +): ChatCompletionMessageParam[] { | |
| 304 | + const messages: ChatCompletionMessageParam[] = []; | |
| 305 | + | |
| 306 | + for (const item of historyItems) { | |
| 307 | + const baseMessage = convertFromUnifiedMessage(item.message); | |
| 308 | + | |
| 309 | + // If this is a user message with context items, expand the content | |
| 310 | + if ( | |
| 311 | + item.message.role === "user" && | |
| 312 | + item.contextItems && | |
| 313 | + item.contextItems.length > 0 | |
| 314 | + ) { | |
| 315 | + const contextContent = item.contextItems | |
| 316 | + .map( | |
| 317 | + (contextItem: ContextItemWithId) => | |
| 318 | + `<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`, | |
| 319 | + ) | |
| 320 | + .join(""); | |
| 321 | + | |
| 322 | + baseMessage.content = | |
| 323 | + typeof baseMessage.content === "string" | |
| 324 | + ? contextContent + baseMessage.content | |
| 325 | + : baseMessage.content; // Keep array format if it's already an array | |
| 326 | + } | |
| 327 | + | |
| 328 | + messages.push(baseMessage); | |
| 329 | + | |
| 330 | + // Add tool result messages if there are completed tool calls | |
| 331 | + if (item.toolCallStates) { | |
| 332 | + for (const toolState of item.toolCallStates) { | |
| 333 | + if (toolState.output && toolState.output.length > 0) { | |
| 334 | + messages.push({ | |
| 335 | + role: "tool", | |
| 336 | + content: toolState.output.map((o: any) => o.content).join("\n"), | |
| 337 | + tool_call_id: toolState.toolCallId, | |
| 338 | + }); | |
| 339 | + } | |
| 340 | + } | |
| 341 | + } | |
| 342 | + } | |
| 343 | + | |
| 344 | + return messages; | |
| 345 | +} | |
| 346 | + | |
| 347 | +/** | |
| 348 | + * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message | |
| 349 | + * @param historyItems - The chat history items | |
| 350 | + * @param systemMessage - The system message to inject at the beginning | |
| 351 | + */ | |
| 352 | +export function convertFromUnifiedHistoryWithSystemMessage( | |
| 353 | + historyItems: ChatHistoryItem[], | |
| 354 | + systemMessage: string, | |
| 355 | +): ChatCompletionMessageParam[] { | |
| 356 | + const messages: ChatCompletionMessageParam[] = []; | |
| 357 | + | |
| 358 | + // Inject system message at the beginning | |
| 359 | + messages.push({ | |
| 360 | + role: "system", | |
| 361 | + content: systemMessage, | |
| 362 | + }); | |
| 363 | + | |
| 364 | + // Convert the rest of the history | |
| 365 | + const convertedMessages = convertFromUnifiedHistory(historyItems); | |
| 366 | + messages.push(...convertedMessages); | |
| 367 | + | |
| 368 | + return messages; | |
| 369 | +} | |
| 370 | + | |
| 371 | +/** | |
| 372 | + * Extract tool call information from a ChatHistoryItem | |
| 373 | + */ | |
| 374 | +export function extractToolCallInfo(historyItem: ChatHistoryItem): { | |
| 375 | + hasToolCalls: boolean; | |
| 376 | + toolCalls?: ToolCall[]; | |
| 377 | + toolStates?: ToolCallState[]; | |
| 378 | +} { | |
| 379 | + const hasToolCalls = !!( | |
| 380 | + historyItem.toolCallStates && historyItem.toolCallStates.length > 0 | |
| 381 | + ); | |
| 382 | + | |
| 383 | + return { | |
| 384 | + hasToolCalls, | |
| 385 | + toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall), | |
| 386 | + toolStates: historyItem.toolCallStates, | |
| 387 | + }; | |
| 388 | +} | |
| 389 | + | |
| 390 | +/** | |
| 391 | + * Helper to safely parse JSON | |
| 392 | + */ | |
| 393 | +function tryParseJson(str: string): any { | |
| 394 | + try { | |
| 395 | + return JSON.parse(str); | |
| 396 | + } catch { | |
| 397 | + return str; | |
| 398 | + } | |
| 399 | +} |
modified core/util/parameters.ts +1 −1
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | transform: true, |
| 22 | 22 | showWhateverWeHaveAtXMs: 300, |
| 23 | 23 | // Experimental options: true = enabled, false = disabled, number = enabled w priority |
| 24 | - experimental_includeClipboard: true, | |
| 24 | + experimental_includeClipboard: false, | |
| 25 | 25 | experimental_includeRecentlyVisitedRanges: true, |
| 26 | 26 | experimental_includeRecentlyEditedRanges: true, |
| 27 | 27 | experimental_includeDiff: true, |
modified core/util/paths.ts +5 −6
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | import dotenv from "dotenv"; |
| 10 | 10 | |
| 11 | 11 | import { IdeType, SerializedContinueConfig } from "../"; |
| 12 | -import { defaultConfig, defaultConfigJetBrains } from "../config/default"; | |
| 12 | +import { defaultConfig } from "../config/default"; | |
| 13 | 13 | import Types from "../config/types"; |
| 14 | 14 | |
| 15 | 15 | dotenv.config(); |
| @@ -110,7 +110,10 @@ | ||
| 110 | 110 | const p = path.join(getContinueGlobalPath(), "config.yaml"); |
| 111 | 111 | if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) { |
| 112 | 112 | if (ideType === "jetbrains") { |
| 113 | - fs.writeFileSync(p, YAML.stringify(defaultConfigJetBrains)); | |
| 113 | + // https://github.com/continuedev/continue/pull/7224 | |
| 114 | + // This was here because we had different context provider support between jetbrains and vs code | |
| 115 | + // Leaving so we could differentiate later but for now configs are the same between IDEs | |
| 116 | + fs.writeFileSync(p, YAML.stringify(defaultConfig)); | |
| 114 | 117 | } else { |
| 115 | 118 | fs.writeFileSync(p, YAML.stringify(defaultConfig)); |
| 116 | 119 | } |
| @@ -393,10 +396,6 @@ | ||
| 393 | 396 | return getGlobalFolderWithName("prompts"); |
| 394 | 397 | } |
| 395 | 398 | |
| 396 | -export function getGlobalAssistantsPath(): string { | |
| 397 | - return getGlobalFolderWithName("assistants"); | |
| 398 | -} | |
| 399 | - | |
| 400 | 399 | export function readAllGlobalPromptFiles( |
| 401 | 400 | folderPath: string = getGlobalPromptsPath(), |
| 402 | 401 | ): { path: string; content: string }[] { |
modified core/util/posthog.ts +2 −0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | |
| 6 | 6 | import type { PostHog as PostHogType } from "posthog-node"; |
| 7 | 7 | import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js"; |
| 8 | +import { TokensBatchingService } from "./TokensBatchingService.js"; | |
| 8 | 9 | |
| 9 | 10 | export enum PosthogFeatureFlag { |
| 10 | 11 | AutocompleteTimeout = "autocomplete-timeout", |
| @@ -99,6 +100,7 @@ | ||
| 99 | 100 | } |
| 100 | 101 | |
| 101 | 102 | static shutdownPosthogClient() { |
| 103 | + TokensBatchingService.getInstance().shutdown(); | |
| 102 | 104 | Telemetry.client?.shutdown(); |
| 103 | 105 | } |
| 104 | 106 |
deleted core/util/processTerminalBackgroundStates.test.ts +0 −73
| @@ -1,73 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - markProcessAsBackgrounded, | |
| 3 | - isProcessBackgrounded, | |
| 4 | - removeBackgroundedProcess, | |
| 5 | -} from "./processTerminalBackgroundStates"; | |
| 6 | - | |
| 7 | -describe("processTerminalBackgroundStates", () => { | |
| 8 | - beforeEach(() => { | |
| 9 | - // Clear any backgrounded processes before each test | |
| 10 | - const backgroundedProcesses = Array.from( | |
| 11 | - Object.getOwnPropertySymbols(global), | |
| 12 | - ).find( | |
| 13 | - (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)", | |
| 14 | - ); | |
| 15 | - | |
| 16 | - if (backgroundedProcesses) { | |
| 17 | - // Reset the map by reimporting the module | |
| 18 | - jest.resetModules(); | |
| 19 | - } | |
| 20 | - }); | |
| 21 | - | |
| 22 | - test("should mark a process as backgrounded", () => { | |
| 23 | - const toolCallId = "test-123"; | |
| 24 | - markProcessAsBackgrounded(toolCallId); | |
| 25 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 26 | - }); | |
| 27 | - | |
| 28 | - test("should correctly identify non-backgrounded processes", () => { | |
| 29 | - const toolCallId = "test-123"; | |
| 30 | - const anotherToolCallId = "test-456"; | |
| 31 | - | |
| 32 | - markProcessAsBackgrounded(toolCallId); | |
| 33 | - | |
| 34 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 35 | - expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - test("should remove a process from backgrounded state", () => { | |
| 39 | - const toolCallId = "test-123"; | |
| 40 | - | |
| 41 | - markProcessAsBackgrounded(toolCallId); | |
| 42 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 43 | - | |
| 44 | - removeBackgroundedProcess(toolCallId); | |
| 45 | - expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 46 | - }); | |
| 47 | - | |
| 48 | - test("should handle removing non-existent processes", () => { | |
| 49 | - const toolCallId = "test-123"; | |
| 50 | - | |
| 51 | - // Should not throw an error | |
| 52 | - removeBackgroundedProcess(toolCallId); | |
| 53 | - expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 54 | - }); | |
| 55 | - | |
| 56 | - test("should handle multiple processes", () => { | |
| 57 | - const toolCallId1 = "test-123"; | |
| 58 | - const toolCallId2 = "test-456"; | |
| 59 | - const toolCallId3 = "test-789"; | |
| 60 | - | |
| 61 | - markProcessAsBackgrounded(toolCallId1); | |
| 62 | - markProcessAsBackgrounded(toolCallId2); | |
| 63 | - | |
| 64 | - expect(isProcessBackgrounded(toolCallId1)).toBe(true); | |
| 65 | - expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 66 | - expect(isProcessBackgrounded(toolCallId3)).toBe(false); | |
| 67 | - | |
| 68 | - removeBackgroundedProcess(toolCallId1); | |
| 69 | - | |
| 70 | - expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 71 | - expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 72 | - }); | |
| 73 | -}); |
deleted core/util/processTerminalBackgroundStates.ts +0 −17
| @@ -1,17 +0,0 @@ | ||
| 1 | -// Track which processes have been backgrounded | |
| 2 | -const processTerminalBackgroundStates = new Map<string, boolean>(); | |
| 3 | - | |
| 4 | -// Function to mark a process as backgrounded | |
| 5 | -export function markProcessAsBackgrounded(toolCallId: string): void { | |
| 6 | - processTerminalBackgroundStates.set(toolCallId, true); | |
| 7 | -} | |
| 8 | - | |
| 9 | -// Function to check if a process is backgrounded | |
| 10 | -export function isProcessBackgrounded(toolCallId: string): boolean { | |
| 11 | - return processTerminalBackgroundStates.has(toolCallId); | |
| 12 | -} | |
| 13 | - | |
| 14 | -// Function to remove a process from the backgrounded processes map | |
| 15 | -export function removeBackgroundedProcess(toolCallId: string): void { | |
| 16 | - processTerminalBackgroundStates.delete(toolCallId); | |
| 17 | -} |
added core/util/processTerminalStates.test.ts +367 −0
| @@ -0,0 +1,367 @@ | ||
| 1 | +import { ChildProcess } from "child_process"; | |
| 2 | +import { | |
| 3 | + clearAllBackgroundProcesses, | |
| 4 | + getAllBackgroundedProcessIds, | |
| 5 | + getAllRunningProcessIds, | |
| 6 | + getRunningProcess, | |
| 7 | + isProcessBackgrounded, | |
| 8 | + isProcessRunning, | |
| 9 | + killAllRunningTerminalProcesses, | |
| 10 | + killMultipleTerminalProcesses, | |
| 11 | + killTerminalProcess, | |
| 12 | + markProcessAsBackgrounded, | |
| 13 | + markProcessAsRunning, | |
| 14 | + removeBackgroundedProcess, | |
| 15 | + removeRunningProcess, | |
| 16 | + updateProcessOutput, | |
| 17 | +} from "./processTerminalStates"; | |
| 18 | + | |
| 19 | +// Mock ChildProcess | |
| 20 | +const createMockProcess = ( | |
| 21 | + pid: number = 123, | |
| 22 | + killed: boolean = false, | |
| 23 | +): jest.Mocked<ChildProcess> => { | |
| 24 | + const mockProcess = { | |
| 25 | + pid, | |
| 26 | + killed, | |
| 27 | + kill: jest.fn(), | |
| 28 | + } as unknown as jest.Mocked<ChildProcess>; | |
| 29 | + | |
| 30 | + // Make kill() update the killed property | |
| 31 | + mockProcess.kill.mockImplementation(() => { | |
| 32 | + (mockProcess as any).killed = true; | |
| 33 | + return true; | |
| 34 | + }); | |
| 35 | + | |
| 36 | + return mockProcess; | |
| 37 | +}; | |
| 38 | + | |
| 39 | +describe("processTerminalStates", () => { | |
| 40 | + beforeEach(() => { | |
| 41 | + // Clear all running processes | |
| 42 | + const runningIds = getAllRunningProcessIds(); | |
| 43 | + runningIds.forEach((id) => removeRunningProcess(id)); | |
| 44 | + | |
| 45 | + // Clear all backgrounded processes | |
| 46 | + const backgroundedIds = getAllBackgroundedProcessIds(); | |
| 47 | + backgroundedIds.forEach((id) => removeBackgroundedProcess(id)); | |
| 48 | + | |
| 49 | + // Clear all timers | |
| 50 | + jest.clearAllTimers(); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + test("should mark a process as backgrounded", () => { | |
| 54 | + const toolCallId = "test-123"; | |
| 55 | + markProcessAsBackgrounded(toolCallId); | |
| 56 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + test("should correctly identify non-backgrounded processes", () => { | |
| 60 | + const toolCallId = "test-123"; | |
| 61 | + const anotherToolCallId = "test-456"; | |
| 62 | + | |
| 63 | + markProcessAsBackgrounded(toolCallId); | |
| 64 | + | |
| 65 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 66 | + expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + test("should remove a process from backgrounded state", () => { | |
| 70 | + const toolCallId = "test-123"; | |
| 71 | + | |
| 72 | + markProcessAsBackgrounded(toolCallId); | |
| 73 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 74 | + | |
| 75 | + removeBackgroundedProcess(toolCallId); | |
| 76 | + expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + test("should handle removing non-existent processes", () => { | |
| 80 | + const toolCallId = "test-123"; | |
| 81 | + | |
| 82 | + // Should not throw an error | |
| 83 | + removeBackgroundedProcess(toolCallId); | |
| 84 | + expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + test("should handle multiple processes", () => { | |
| 88 | + const toolCallId1 = "test-123"; | |
| 89 | + const toolCallId2 = "test-456"; | |
| 90 | + const toolCallId3 = "test-789"; | |
| 91 | + | |
| 92 | + markProcessAsBackgrounded(toolCallId1); | |
| 93 | + markProcessAsBackgrounded(toolCallId2); | |
| 94 | + | |
| 95 | + expect(isProcessBackgrounded(toolCallId1)).toBe(true); | |
| 96 | + expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 97 | + expect(isProcessBackgrounded(toolCallId3)).toBe(false); | |
| 98 | + | |
| 99 | + removeBackgroundedProcess(toolCallId1); | |
| 100 | + | |
| 101 | + expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 102 | + expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + describe("foreground process functions", () => { | |
| 106 | + test("should mark a process as running", () => { | |
| 107 | + const toolCallId = "test-123"; | |
| 108 | + const mockProcess = createMockProcess(); | |
| 109 | + const mockCallback = jest.fn(); | |
| 110 | + const initialOutput = "initial output"; | |
| 111 | + | |
| 112 | + markProcessAsRunning( | |
| 113 | + toolCallId, | |
| 114 | + mockProcess, | |
| 115 | + mockCallback, | |
| 116 | + initialOutput, | |
| 117 | + ); | |
| 118 | + | |
| 119 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 120 | + expect(getRunningProcess(toolCallId)).toBe(mockProcess); | |
| 121 | + }); | |
| 122 | + | |
| 123 | + test("should handle process without callback or initial output", () => { | |
| 124 | + const toolCallId = "test-123"; | |
| 125 | + const mockProcess = createMockProcess(); | |
| 126 | + | |
| 127 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 128 | + | |
| 129 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 130 | + expect(getRunningProcess(toolCallId)).toBe(mockProcess); | |
| 131 | + }); | |
| 132 | + | |
| 133 | + test("should correctly identify non-running processes", () => { | |
| 134 | + const toolCallId = "test-123"; | |
| 135 | + const anotherToolCallId = "test-456"; | |
| 136 | + const mockProcess = createMockProcess(); | |
| 137 | + | |
| 138 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 139 | + | |
| 140 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 141 | + expect(isProcessRunning(anotherToolCallId)).toBe(false); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + test("should update process output", () => { | |
| 145 | + const toolCallId = "test-123"; | |
| 146 | + const mockProcess = createMockProcess(); | |
| 147 | + const initialOutput = "initial"; | |
| 148 | + const updatedOutput = "updated output"; | |
| 149 | + | |
| 150 | + markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput); | |
| 151 | + updateProcessOutput(toolCallId, updatedOutput); | |
| 152 | + | |
| 153 | + // We can't directly test the output value, but we can ensure the function doesn't throw | |
| 154 | + expect(() => | |
| 155 | + updateProcessOutput(toolCallId, updatedOutput), | |
| 156 | + ).not.toThrow(); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + test("should handle updating output for non-existent process", () => { | |
| 160 | + const toolCallId = "non-existent"; | |
| 161 | + | |
| 162 | + expect(() => | |
| 163 | + updateProcessOutput(toolCallId, "some output"), | |
| 164 | + ).not.toThrow(); | |
| 165 | + }); | |
| 166 | + | |
| 167 | + test("should remove a process from running state", () => { | |
| 168 | + const toolCallId = "test-123"; | |
| 169 | + const mockProcess = createMockProcess(); | |
| 170 | + | |
| 171 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 172 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 173 | + | |
| 174 | + removeRunningProcess(toolCallId); | |
| 175 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 176 | + expect(getRunningProcess(toolCallId)).toBeUndefined(); | |
| 177 | + }); | |
| 178 | + | |
| 179 | + test("should handle removing non-existent running processes", () => { | |
| 180 | + const toolCallId = "test-123"; | |
| 181 | + | |
| 182 | + expect(() => removeRunningProcess(toolCallId)).not.toThrow(); | |
| 183 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 184 | + }); | |
| 185 | + | |
| 186 | + test("should return undefined for non-existent running process", () => { | |
| 187 | + const toolCallId = "non-existent"; | |
| 188 | + | |
| 189 | + expect(getRunningProcess(toolCallId)).toBeUndefined(); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("terminal command cancellation", () => { | |
| 194 | + beforeEach(() => { | |
| 195 | + jest.useFakeTimers(); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + afterEach(() => { | |
| 199 | + jest.useRealTimers(); | |
| 200 | + }); | |
| 201 | + | |
| 202 | + test("should cancel a running terminal command", async () => { | |
| 203 | + const toolCallId = "test-123"; | |
| 204 | + const mockProcess = createMockProcess(); | |
| 205 | + | |
| 206 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 207 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 208 | + | |
| 209 | + await killTerminalProcess(toolCallId); | |
| 210 | + | |
| 211 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 212 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 213 | + }); | |
| 214 | + | |
| 215 | + test("should handle cancelling non-existent process", async () => { | |
| 216 | + const toolCallId = "non-existent"; | |
| 217 | + | |
| 218 | + await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow(); | |
| 219 | + }); | |
| 220 | + | |
| 221 | + test("should handle cancelling already killed process", async () => { | |
| 222 | + const toolCallId = "test-123"; | |
| 223 | + const mockProcess = createMockProcess(123, true); // Already killed | |
| 224 | + | |
| 225 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 226 | + | |
| 227 | + await killTerminalProcess(toolCallId); | |
| 228 | + | |
| 229 | + expect(mockProcess.kill).not.toHaveBeenCalled(); | |
| 230 | + }); | |
| 231 | + | |
| 232 | + test("should send SIGKILL after timeout if process not killed", async () => { | |
| 233 | + const toolCallId = "test-123"; | |
| 234 | + const mockProcess = createMockProcess(); | |
| 235 | + | |
| 236 | + // Mock kill to not actually set killed=true for SIGTERM | |
| 237 | + mockProcess.kill.mockImplementation((signal) => { | |
| 238 | + if (signal === "SIGKILL") { | |
| 239 | + (mockProcess as any).killed = true; | |
| 240 | + } | |
| 241 | + return true; | |
| 242 | + }); | |
| 243 | + | |
| 244 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 245 | + | |
| 246 | + const cancelPromise = killTerminalProcess(toolCallId); | |
| 247 | + | |
| 248 | + // Fast-forward time to trigger the timeout | |
| 249 | + jest.advanceTimersByTime(5000); | |
| 250 | + | |
| 251 | + await cancelPromise; | |
| 252 | + | |
| 253 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 254 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL"); | |
| 255 | + }); | |
| 256 | + | |
| 257 | + test("should not send SIGKILL if process was already killed", async () => { | |
| 258 | + const toolCallId = "test-123"; | |
| 259 | + const mockProcess = createMockProcess(); | |
| 260 | + | |
| 261 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 262 | + | |
| 263 | + const cancelPromise = killTerminalProcess(toolCallId); | |
| 264 | + | |
| 265 | + // Fast-forward time to trigger the timeout | |
| 266 | + jest.advanceTimersByTime(5000); | |
| 267 | + | |
| 268 | + await cancelPromise; | |
| 269 | + | |
| 270 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 271 | + expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + describe("utility functions", () => { | |
| 276 | + test("should get all running process IDs", () => { | |
| 277 | + const toolCallId1 = "test-123"; | |
| 278 | + const toolCallId2 = "test-456"; | |
| 279 | + const mockProcess1 = createMockProcess(123); | |
| 280 | + const mockProcess2 = createMockProcess(456); | |
| 281 | + | |
| 282 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 283 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 284 | + | |
| 285 | + const runningIds = getAllRunningProcessIds(); | |
| 286 | + expect(runningIds).toContain(toolCallId1); | |
| 287 | + expect(runningIds).toContain(toolCallId2); | |
| 288 | + expect(runningIds).toHaveLength(2); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + test("should get all backgrounded process IDs", () => { | |
| 292 | + const toolCallId1 = "test-123"; | |
| 293 | + const toolCallId2 = "test-456"; | |
| 294 | + | |
| 295 | + markProcessAsBackgrounded(toolCallId1); | |
| 296 | + markProcessAsBackgrounded(toolCallId2); | |
| 297 | + | |
| 298 | + const backgroundedIds = getAllBackgroundedProcessIds(); | |
| 299 | + expect(backgroundedIds).toContain(toolCallId1); | |
| 300 | + expect(backgroundedIds).toContain(toolCallId2); | |
| 301 | + expect(backgroundedIds).toHaveLength(2); | |
| 302 | + }); | |
| 303 | + | |
| 304 | + test("should return empty arrays when no processes", () => { | |
| 305 | + expect(getAllRunningProcessIds()).toEqual([]); | |
| 306 | + expect(getAllBackgroundedProcessIds()).toEqual([]); | |
| 307 | + }); | |
| 308 | + | |
| 309 | + test("should cancel multiple terminal commands", async () => { | |
| 310 | + const toolCallId1 = "test-123"; | |
| 311 | + const toolCallId2 = "test-456"; | |
| 312 | + const mockProcess1 = createMockProcess(123); | |
| 313 | + const mockProcess2 = createMockProcess(456); | |
| 314 | + | |
| 315 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 316 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 317 | + | |
| 318 | + await killMultipleTerminalProcesses([toolCallId1, toolCallId2]); | |
| 319 | + | |
| 320 | + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 321 | + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 322 | + expect(isProcessRunning(toolCallId1)).toBe(false); | |
| 323 | + expect(isProcessRunning(toolCallId2)).toBe(false); | |
| 324 | + }); | |
| 325 | + | |
| 326 | + test("should cancel all running terminal commands", async () => { | |
| 327 | + const toolCallId1 = "test-123"; | |
| 328 | + const toolCallId2 = "test-456"; | |
| 329 | + const mockProcess1 = createMockProcess(123); | |
| 330 | + const mockProcess2 = createMockProcess(456); | |
| 331 | + | |
| 332 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 333 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 334 | + | |
| 335 | + const cancelledIds = await killAllRunningTerminalProcesses(); | |
| 336 | + | |
| 337 | + expect(cancelledIds).toContain(toolCallId1); | |
| 338 | + expect(cancelledIds).toContain(toolCallId2); | |
| 339 | + expect(cancelledIds).toHaveLength(2); | |
| 340 | + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 341 | + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 342 | + expect(isProcessRunning(toolCallId1)).toBe(false); | |
| 343 | + expect(isProcessRunning(toolCallId2)).toBe(false); | |
| 344 | + }); | |
| 345 | + | |
| 346 | + test("should return empty array when no running commands to cancel", async () => { | |
| 347 | + const cancelledIds = await killAllRunningTerminalProcesses(); | |
| 348 | + expect(cancelledIds).toEqual([]); | |
| 349 | + }); | |
| 350 | + | |
| 351 | + test("should clear all background processes", () => { | |
| 352 | + const toolCallId1 = "test-123"; | |
| 353 | + const toolCallId2 = "test-456"; | |
| 354 | + | |
| 355 | + markProcessAsBackgrounded(toolCallId1); | |
| 356 | + markProcessAsBackgrounded(toolCallId2); | |
| 357 | + | |
| 358 | + expect(getAllBackgroundedProcessIds()).toHaveLength(2); | |
| 359 | + | |
| 360 | + clearAllBackgroundProcesses(); | |
| 361 | + | |
| 362 | + expect(getAllBackgroundedProcessIds()).toEqual([]); | |
| 363 | + expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 364 | + expect(isProcessBackgrounded(toolCallId2)).toBe(false); | |
| 365 | + }); | |
| 366 | + }); | |
| 367 | +}); |
added core/util/processTerminalStates.ts +119 −0
| @@ -0,0 +1,119 @@ | ||
| 1 | +import { ChildProcess } from "child_process"; | |
| 2 | + | |
| 3 | +// Track which processes have been backgrounded | |
| 4 | +const processTerminalBackgroundStates = new Map<string, boolean>(); | |
| 5 | + | |
| 6 | +// Track which foreground processes are currently running | |
| 7 | +interface RunningProcessInfo { | |
| 8 | + process: ChildProcess; | |
| 9 | + onPartialOutput?: (params: { | |
| 10 | + toolCallId: string; | |
| 11 | + contextItems: any[]; | |
| 12 | + }) => void; | |
| 13 | + currentOutput: string; | |
| 14 | +} | |
| 15 | + | |
| 16 | +const processTerminalForegroundStates = new Map<string, RunningProcessInfo>(); | |
| 17 | + | |
| 18 | +// Background process functions (existing) | |
| 19 | +export function markProcessAsBackgrounded(toolCallId: string): void { | |
| 20 | + processTerminalBackgroundStates.set(toolCallId, true); | |
| 21 | +} | |
| 22 | + | |
| 23 | +export function isProcessBackgrounded(toolCallId: string): boolean { | |
| 24 | + return processTerminalBackgroundStates.has(toolCallId); | |
| 25 | +} | |
| 26 | + | |
| 27 | +export function removeBackgroundedProcess(toolCallId: string): void { | |
| 28 | + processTerminalBackgroundStates.delete(toolCallId); | |
| 29 | +} | |
| 30 | + | |
| 31 | +// Foreground process functions (new) | |
| 32 | +export function markProcessAsRunning( | |
| 33 | + toolCallId: string, | |
| 34 | + process: ChildProcess, | |
| 35 | + onPartialOutput?: (params: { | |
| 36 | + toolCallId: string; | |
| 37 | + contextItems: any[]; | |
| 38 | + }) => void, | |
| 39 | + currentOutput: string = "", | |
| 40 | +): void { | |
| 41 | + processTerminalForegroundStates.set(toolCallId, { | |
| 42 | + process, | |
| 43 | + onPartialOutput, | |
| 44 | + currentOutput, | |
| 45 | + }); | |
| 46 | +} | |
| 47 | + | |
| 48 | +export function isProcessRunning(toolCallId: string): boolean { | |
| 49 | + return processTerminalForegroundStates.has(toolCallId); | |
| 50 | +} | |
| 51 | + | |
| 52 | +export function getRunningProcess( | |
| 53 | + toolCallId: string, | |
| 54 | +): ChildProcess | undefined { | |
| 55 | + const info = processTerminalForegroundStates.get(toolCallId); | |
| 56 | + return info?.process; | |
| 57 | +} | |
| 58 | + | |
| 59 | +export function updateProcessOutput(toolCallId: string, output: string): void { | |
| 60 | + const info = processTerminalForegroundStates.get(toolCallId); | |
| 61 | + if (info) { | |
| 62 | + info.currentOutput = output; | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +export function removeRunningProcess(toolCallId: string): void { | |
| 67 | + processTerminalForegroundStates.delete(toolCallId); | |
| 68 | +} | |
| 69 | + | |
| 70 | +export async function killTerminalProcess(toolCallId: string): Promise<void> { | |
| 71 | + const processInfo = processTerminalForegroundStates.get(toolCallId); | |
| 72 | + if (processInfo && !processInfo.process.killed) { | |
| 73 | + const { process } = processInfo; | |
| 74 | + | |
| 75 | + process.kill("SIGTERM"); | |
| 76 | + | |
| 77 | + // Force kill after 5 seconds if still running | |
| 78 | + setTimeout(() => { | |
| 79 | + if (!process.killed) { | |
| 80 | + process.kill("SIGKILL"); | |
| 81 | + } | |
| 82 | + }, 5000); | |
| 83 | + | |
| 84 | + processTerminalForegroundStates.delete(toolCallId); | |
| 85 | + } | |
| 86 | +} | |
| 87 | + | |
| 88 | +// Function to cancel multiple terminal commands at once | |
| 89 | +export async function killMultipleTerminalProcesses( | |
| 90 | + toolCallIds: string[], | |
| 91 | +): Promise<void> { | |
| 92 | + const cancelPromises = toolCallIds.map((toolCallId) => | |
| 93 | + killTerminalProcess(toolCallId), | |
| 94 | + ); | |
| 95 | + await Promise.all(cancelPromises); | |
| 96 | +} | |
| 97 | + | |
| 98 | +// Function to cancel ALL currently running terminal commands | |
| 99 | +export async function killAllRunningTerminalProcesses(): Promise<string[]> { | |
| 100 | + const runningIds = getAllRunningProcessIds(); | |
| 101 | + if (runningIds.length > 0) { | |
| 102 | + await killMultipleTerminalProcesses(runningIds); | |
| 103 | + } | |
| 104 | + return runningIds; // Return the IDs that were cancelled | |
| 105 | +} | |
| 106 | + | |
| 107 | +// Utility functions | |
| 108 | +export function getAllRunningProcessIds(): string[] { | |
| 109 | + return Array.from(processTerminalForegroundStates.keys()); | |
| 110 | +} | |
| 111 | + | |
| 112 | +export function getAllBackgroundedProcessIds(): string[] { | |
| 113 | + return Array.from(processTerminalBackgroundStates.keys()); | |
| 114 | +} | |
| 115 | + | |
| 116 | +// Utility function for testing - clears all background process states | |
| 117 | +export function clearAllBackgroundProcesses(): void { | |
| 118 | + processTerminalBackgroundStates.clear(); | |
| 119 | +} |
added core/util/regexValidator.ts +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +/** | |
| 2 | + * Validates and sanitizes regex patterns for use with ripgrep | |
| 3 | + */ | |
| 4 | + | |
| 5 | +export interface RegexValidationResult { | |
| 6 | + isValid: boolean; | |
| 7 | + sanitizedQuery?: string; | |
| 8 | + error?: string; | |
| 9 | + warning?: string; | |
| 10 | +} | |
| 11 | + | |
| 12 | +/** | |
| 13 | + * Validates a regex pattern and attempts to sanitize common issues | |
| 14 | + * @param query The regex pattern to validate | |
| 15 | + * @returns Validation result with sanitized query if possible | |
| 16 | + */ | |
| 17 | +export function validateAndSanitizeRegex(query: string): RegexValidationResult { | |
| 18 | + // Check for common problematic patterns that often fail with ripgrep | |
| 19 | + const problematicPatterns = [ | |
| 20 | + { | |
| 21 | + // Triple-escaped quotes | |
| 22 | + pattern: /\\\\\\/g, | |
| 23 | + issue: "Triple backslash sequences may cause parsing errors", | |
| 24 | + fix: (s: string) => s.replace(/\\\\\\/g, "\\\\"), | |
| 25 | + }, | |
| 26 | + { | |
| 27 | + // Unescaped brackets/parentheses that are NOT part of valid regex constructs | |
| 28 | + pattern: /(?<!\\)[\[\]()]/g, // Removed {} from here since they're valid quantifiers | |
| 29 | + issue: "Unescaped brackets or parentheses", | |
| 30 | + fix: null, // Just warn, don't auto-fix as it might be intentional | |
| 31 | + }, | |
| 32 | + { | |
| 33 | + // Unescaped braces that are NOT quantifiers (quantifiers are handled separately) | |
| 34 | + pattern: /(?<!\\)\{(?![0-9,}]*\})/g, | |
| 35 | + issue: "Unescaped braces that don't appear to be quantifiers", | |
| 36 | + fix: null, | |
| 37 | + }, | |
| 38 | + { | |
| 39 | + // Raw tab/newline characters (not escaped) | |
| 40 | + pattern: /[\t\n\r]/g, | |
| 41 | + issue: "Raw whitespace characters should be escaped", | |
| 42 | + fix: (s: string) => | |
| 43 | + s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r"), | |
| 44 | + }, | |
| 45 | + ]; | |
| 46 | + | |
| 47 | + let sanitizedQuery = query; | |
| 48 | + let warnings: string[] = []; | |
| 49 | + | |
| 50 | + // Apply fixes for known issues | |
| 51 | + for (const check of problematicPatterns) { | |
| 52 | + if (check.pattern.test(query)) { | |
| 53 | + if (check.fix) { | |
| 54 | + sanitizedQuery = check.fix(sanitizedQuery); | |
| 55 | + warnings.push(`Fixed: ${check.issue}`); | |
| 56 | + } else { | |
| 57 | + warnings.push(`Warning: ${check.issue}`); | |
| 58 | + } | |
| 59 | + } | |
| 60 | + } | |
| 61 | + | |
| 62 | + // Try to compile as a JavaScript regex to catch basic syntax errors | |
| 63 | + try { | |
| 64 | + new RegExp(sanitizedQuery); | |
| 65 | + } catch (e) { | |
| 66 | + let errorMessage = e instanceof Error ? e.message : "Unknown error"; | |
| 67 | + // If it fails as a JS regex, it might still be valid for ripgrep | |
| 68 | + // (ripgrep supports some patterns JS doesn't), but warn the user | |
| 69 | + warnings.push(`Pattern may have syntax issues: ${errorMessage}`); | |
| 70 | + } | |
| 71 | + | |
| 72 | + // Check for patterns that are valid regex but might not work as expected with ripgrep | |
| 73 | + const ripgrepSpecificIssues = [ | |
| 74 | + { | |
| 75 | + pattern: /\\[0-7]{3}/g, | |
| 76 | + warning: "Octal escape sequences may not work as expected in ripgrep", | |
| 77 | + }, | |
| 78 | + { | |
| 79 | + pattern: /\(\?[<!=]/, | |
| 80 | + warning: | |
| 81 | + "Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2", | |
| 82 | + }, | |
| 83 | + ]; | |
| 84 | + | |
| 85 | + for (const issue of ripgrepSpecificIssues) { | |
| 86 | + if (issue.pattern.test(sanitizedQuery)) { | |
| 87 | + warnings.push(issue.warning); | |
| 88 | + } | |
| 89 | + } | |
| 90 | + | |
| 91 | + return { | |
| 92 | + isValid: true, | |
| 93 | + sanitizedQuery, | |
| 94 | + warning: warnings.length > 0 ? warnings.join("; ") : undefined, | |
| 95 | + }; | |
| 96 | +} | |
| 97 | + | |
| 98 | +/** | |
| 99 | + * Escapes a literal string to be used as a regex pattern | |
| 100 | + * @param literal The literal string to escape | |
| 101 | + * @returns Escaped string safe for regex use | |
| 102 | + */ | |
| 103 | +export function escapeLiteralForRegex(literal: string): string { | |
| 104 | + // Escape all regex metacharacters | |
| 105 | + return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); | |
| 106 | +} | |
| 107 | + | |
| 108 | +/** | |
| 109 | + * Detects if a query looks like it's meant to be a literal search | |
| 110 | + * rather than a regex pattern | |
| 111 | + * @param query The search query | |
| 112 | + * @returns true if it appears to be a literal search | |
| 113 | + */ | |
| 114 | +export function looksLikeLiteralSearch(query: string): boolean { | |
| 115 | + // If it contains regex metacharacters but they're not escaped, | |
| 116 | + // and it doesn't look like an intentional regex pattern | |
| 117 | + const hasUnescapedMetachars = /[.*+?^${}()|[\]]/g.test(query); | |
| 118 | + const hasEscapedMetachars = /\\[.*+?^${}()|[\]\\]/g.test(query); | |
| 119 | + | |
| 120 | + // Check for regex constructs, but be more specific about what we consider regex | |
| 121 | + const hasEscapeSequences = /\\[dws]/g.test(query); // \d, \w, \s | |
| 122 | + const hasQuantifiers = /\{[0-9,]+\}/g.test(query); // {2,4}, {3} | |
| 123 | + | |
| 124 | + // Check for bracket patterns and distinguish between character classes and array access | |
| 125 | + const bracketPattern = /\[[^\]]*\]/g; | |
| 126 | + const brackets = query.match(bracketPattern); | |
| 127 | + let hasCharacterClasses = false; | |
| 128 | + | |
| 129 | + if (brackets) { | |
| 130 | + hasCharacterClasses = brackets.some((bracket) => { | |
| 131 | + const inside = bracket.slice(1, -1); // Remove [ ] | |
| 132 | + // Character class indicators: ranges (a-z), multiple chars, negation (^) | |
| 133 | + return /-/.test(inside) || inside.length > 1 || inside.startsWith("^"); | |
| 134 | + }); | |
| 135 | + } | |
| 136 | + | |
| 137 | + const hasRegexConstructs = | |
| 138 | + hasEscapeSequences || hasQuantifiers || hasCharacterClasses; | |
| 139 | + | |
| 140 | + // Likely a literal search if it has unescaped metachars but no regex constructs | |
| 141 | + return hasUnescapedMetachars && !hasEscapedMetachars && !hasRegexConstructs; | |
| 142 | +} | |
| 143 | + | |
| 144 | +/** | |
| 145 | + * Prepares a query for ripgrep by sanitizing problematic patterns | |
| 146 | + * @param query The search query | |
| 147 | + * @returns Object with sanitized query and any warnings | |
| 148 | + */ | |
| 149 | +export function prepareQueryForRipgrep(query: string): { | |
| 150 | + query: string; | |
| 151 | + warning?: string; | |
| 152 | +} { | |
| 153 | + // Check if it looks like a literal search that should be escaped | |
| 154 | + if (looksLikeLiteralSearch(query)) { | |
| 155 | + return { | |
| 156 | + query: escapeLiteralForRegex(query), | |
| 157 | + warning: | |
| 158 | + "Query contained special regex characters and was escaped for literal text search", | |
| 159 | + }; | |
| 160 | + } | |
| 161 | + | |
| 162 | + // Otherwise validate and sanitize as regex | |
| 163 | + const validation = validateAndSanitizeRegex(query); | |
| 164 | + | |
| 165 | + return { | |
| 166 | + query: validation.sanitizedQuery || query, | |
| 167 | + warning: validation.warning, | |
| 168 | + }; | |
| 169 | +} |
added core/util/regexValidator.vitest.ts +310 −0
| @@ -0,0 +1,310 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + escapeLiteralForRegex, | |
| 4 | + looksLikeLiteralSearch, | |
| 5 | + prepareQueryForRipgrep, | |
| 6 | + validateAndSanitizeRegex, | |
| 7 | +} from "./regexValidator"; | |
| 8 | + | |
| 9 | +describe("validateAndSanitizeRegex", () => { | |
| 10 | + it("should accept valid basic regex patterns", () => { | |
| 11 | + const result = validateAndSanitizeRegex("function\\s+\\w+"); | |
| 12 | + expect(result.isValid).toBe(true); | |
| 13 | + expect(result.sanitizedQuery).toBe("function\\s+\\w+"); | |
| 14 | + expect(result.error).toBeUndefined(); | |
| 15 | + expect(result.warning).toBeUndefined(); | |
| 16 | + }); | |
| 17 | + | |
| 18 | + it("should fix triple-escaped sequences", () => { | |
| 19 | + const result = validateAndSanitizeRegex("\\\\\\"); | |
| 20 | + expect(result.isValid).toBe(true); | |
| 21 | + expect(result.sanitizedQuery).toBe("\\\\"); | |
| 22 | + expect(result.warning).toContain("Fixed: Triple backslash sequences"); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + it("should fix raw tab characters", () => { | |
| 26 | + const result = validateAndSanitizeRegex("hello\tworld"); | |
| 27 | + expect(result.isValid).toBe(true); | |
| 28 | + expect(result.sanitizedQuery).toBe("hello\\tworld"); | |
| 29 | + expect(result.warning).toContain("Fixed: Raw whitespace characters"); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + it("should fix raw newline characters", () => { | |
| 33 | + const result = validateAndSanitizeRegex("line1\nline2"); | |
| 34 | + expect(result.isValid).toBe(true); | |
| 35 | + expect(result.sanitizedQuery).toBe("line1\\nline2"); | |
| 36 | + expect(result.warning).toContain("Fixed: Raw whitespace characters"); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should warn about unescaped brackets without fixing", () => { | |
| 40 | + const result = validateAndSanitizeRegex("hello[world]"); | |
| 41 | + expect(result.isValid).toBe(true); | |
| 42 | + expect(result.sanitizedQuery).toBe("hello[world]"); | |
| 43 | + expect(result.warning).toContain( | |
| 44 | + "Warning: Unescaped brackets or parentheses", | |
| 45 | + ); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("should handle multiple issues", () => { | |
| 49 | + const result = validateAndSanitizeRegex("function()\t\\\\\\"); | |
| 50 | + expect(result.isValid).toBe(true); | |
| 51 | + expect(result.sanitizedQuery).toBe("function()\\t\\\\"); | |
| 52 | + expect(result.warning).toContain("Fixed: Raw whitespace characters"); | |
| 53 | + expect(result.warning).toContain("Fixed: Triple backslash sequences"); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + it("should warn about lookbehind assertions", () => { | |
| 57 | + const result = validateAndSanitizeRegex("(?<=foo)bar"); | |
| 58 | + expect(result.isValid).toBe(true); | |
| 59 | + expect(result.warning).toContain( | |
| 60 | + "Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2", | |
| 61 | + ); | |
| 62 | + }); | |
| 63 | +}); | |
| 64 | + | |
| 65 | +describe("escapeLiteralForRegex", () => { | |
| 66 | + it("should escape basic regex metacharacters", () => { | |
| 67 | + expect(escapeLiteralForRegex("hello.world")).toBe("hello\\.world"); | |
| 68 | + expect(escapeLiteralForRegex("test*")).toBe("test\\*"); | |
| 69 | + expect(escapeLiteralForRegex("file+")).toBe("file\\+"); | |
| 70 | + expect(escapeLiteralForRegex("query?")).toBe("query\\?"); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + it("should escape brackets and braces", () => { | |
| 74 | + expect(escapeLiteralForRegex("array[0]")).toBe("array\\[0\\]"); | |
| 75 | + expect(escapeLiteralForRegex("{key}")).toBe("\\{key\\}"); | |
| 76 | + expect(escapeLiteralForRegex("func()")).toBe("func\\(\\)"); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + it("should handle multiple metacharacters", () => { | |
| 80 | + expect(escapeLiteralForRegex("$regex.test(input)")).toBe( | |
| 81 | + "\\$regex\\.test\\(input\\)", | |
| 82 | + ); | |
| 83 | + }); | |
| 84 | + | |
| 85 | + it("should not escape normal characters", () => { | |
| 86 | + expect(escapeLiteralForRegex("hello world")).toBe("hello world"); | |
| 87 | + }); | |
| 88 | +}); | |
| 89 | + | |
| 90 | +describe("looksLikeLiteralSearch", () => { | |
| 91 | + it("should identify literal searches with unescaped metacharacters", () => { | |
| 92 | + expect(looksLikeLiteralSearch("hello.world")).toBe(true); | |
| 93 | + expect(looksLikeLiteralSearch("test*")).toBe(true); | |
| 94 | + expect(looksLikeLiteralSearch("func()")).toBe(true); | |
| 95 | + expect(looksLikeLiteralSearch("array[0]")).toBe(true); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should not identify regex patterns as literal", () => { | |
| 99 | + expect(looksLikeLiteralSearch("hello\\.world")).toBe(false); | |
| 100 | + expect(looksLikeLiteralSearch("\\d+")).toBe(false); | |
| 101 | + expect(looksLikeLiteralSearch("[a-z]+")).toBe(false); | |
| 102 | + expect(looksLikeLiteralSearch("a{2,4}")).toBe(false); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + it("should handle plain text", () => { | |
| 106 | + expect(looksLikeLiteralSearch("hello world")).toBe(false); | |
| 107 | + expect(looksLikeLiteralSearch("simple text")).toBe(false); | |
| 108 | + }); | |
| 109 | +}); | |
| 110 | + | |
| 111 | +describe("prepareQueryForRipgrep", () => { | |
| 112 | + it("should escape literal-looking queries", () => { | |
| 113 | + const result = prepareQueryForRipgrep("hello.world"); | |
| 114 | + expect(result.query).toBe("hello\\.world"); | |
| 115 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 116 | + }); | |
| 117 | + | |
| 118 | + it("should sanitize regex patterns", () => { | |
| 119 | + const result = prepareQueryForRipgrep("function\t\\\\\\"); | |
| 120 | + expect(result.query).toBe("function\\t\\\\"); | |
| 121 | + expect(result.warning).toContain("Fixed:"); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + it("should handle plain text without changes", () => { | |
| 125 | + const result = prepareQueryForRipgrep("hello world"); | |
| 126 | + expect(result.query).toBe("hello world"); | |
| 127 | + expect(result.warning).toBeUndefined(); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + describe("real-world examples", () => { | |
| 131 | + it("should escape file patterns", () => { | |
| 132 | + const result = prepareQueryForRipgrep("*.js"); | |
| 133 | + expect(result.query).toBe("\\*\\.js"); | |
| 134 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 135 | + }); | |
| 136 | + | |
| 137 | + it("should escape function calls", () => { | |
| 138 | + const result = prepareQueryForRipgrep("console.log()"); | |
| 139 | + expect(result.query).toBe("console\\.log\\(\\)"); | |
| 140 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + it("should not escape proper regex patterns", () => { | |
| 144 | + const result = prepareQueryForRipgrep("function\\s+\\w+"); | |
| 145 | + expect(result.query).toBe("function\\s+\\w+"); | |
| 146 | + expect(result.warning).toBeUndefined(); | |
| 147 | + }); | |
| 148 | + }); | |
| 149 | +}); | |
| 150 | + | |
| 151 | +describe("problematic patterns that originally failed", () => { | |
| 152 | + it("should handle triple-escaped quotes", () => { | |
| 153 | + const result = prepareQueryForRipgrep('\\\\\\"'); | |
| 154 | + expect(result.query).toBe('\\\\"'); // Triple backslash -> double backslash, quote stays | |
| 155 | + expect(result.warning).toContain("Fixed:"); | |
| 156 | + }); | |
| 157 | + | |
| 158 | + it("should handle newline-tab sequences", () => { | |
| 159 | + const result = prepareQueryForRipgrep("\n\t"); | |
| 160 | + expect(result.query).toBe("\\n\\t"); | |
| 161 | + expect(result.warning).toContain("Fixed:"); | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("should handle dollar signs in shell patterns", () => { | |
| 165 | + const result = prepareQueryForRipgrep("$(command)"); | |
| 166 | + expect(result.query).toBe("\\$\\(command\\)"); | |
| 167 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 168 | + }); | |
| 169 | + | |
| 170 | + it("should handle escaped dollar signs", () => { | |
| 171 | + const result = prepareQueryForRipgrep("\\$\\("); | |
| 172 | + expect(result.query).toBe("\\$\\("); | |
| 173 | + expect(result.warning).toBeUndefined(); | |
| 174 | + }); | |
| 175 | +}); | |
| 176 | + | |
| 177 | +describe("patterns that should NOT be over-sanitized", () => { | |
| 178 | + describe("valid regex patterns that contain suspicious sequences", () => { | |
| 179 | + it("should not escape properly formed character classes", () => { | |
| 180 | + const result = prepareQueryForRipgrep("[a-zA-Z0-9_-]+"); | |
| 181 | + expect(result.query).toBe("[a-zA-Z0-9_-]+"); | |
| 182 | + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but don't break | |
| 183 | + }); | |
| 184 | + | |
| 185 | + it("should not escape quantifiers in regex patterns", () => { | |
| 186 | + const result = prepareQueryForRipgrep("\\w{2,5}"); | |
| 187 | + expect(result.query).toBe("\\w{2,5}"); | |
| 188 | + expect(result.warning).toBeUndefined(); | |
| 189 | + }); | |
| 190 | + | |
| 191 | + it("should not escape properly formed lookarounds", () => { | |
| 192 | + const result = prepareQueryForRipgrep("(?<!\\w)test(?!\\w)"); | |
| 193 | + expect(result.query).toBe("(?<!\\w)test(?!\\w)"); | |
| 194 | + expect(result.warning).toContain("Lookahead/lookbehind assertions"); // Warn about compatibility | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should not break escaped metacharacters in regex", () => { | |
| 198 | + const result = prepareQueryForRipgrep("console\\.log\\(\\)"); | |
| 199 | + expect(result.query).toBe("console\\.log\\(\\)"); | |
| 200 | + expect(result.warning).toBeUndefined(); | |
| 201 | + }); | |
| 202 | + }); | |
| 203 | + | |
| 204 | + describe("patterns that look problematic but are intentional", () => { | |
| 205 | + it("should not over-escape already escaped sequences", () => { | |
| 206 | + const result = prepareQueryForRipgrep("\\\\t"); // Already escaped tab | |
| 207 | + expect(result.query).toBe("\\\\t"); | |
| 208 | + expect(result.warning).toBeUndefined(); | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should not double-escape backslashes in Windows paths", () => { | |
| 212 | + const result = prepareQueryForRipgrep("C:\\\\Users\\\\file"); | |
| 213 | + expect(result.query).toBe("C:\\\\Users\\\\file"); | |
| 214 | + expect(result.warning).toBeUndefined(); | |
| 215 | + }); | |
| 216 | + | |
| 217 | + it("should not break raw strings that contain regex-like patterns", () => { | |
| 218 | + const result = prepareQueryForRipgrep('"\\d+\\s+\\w+"'); | |
| 219 | + expect(result.query).toBe('"\\d+\\s+\\w+"'); // Escaped sequences in quotes should stay | |
| 220 | + expect(result.warning).toBeUndefined(); | |
| 221 | + }); | |
| 222 | + | |
| 223 | + it("should not break JSON with escaped quotes", () => { | |
| 224 | + const result = prepareQueryForRipgrep('"key": "value"'); | |
| 225 | + expect(result.query).toBe('"key": "value"'); | |
| 226 | + expect(result.warning).toBeUndefined(); | |
| 227 | + }); | |
| 228 | + }); | |
| 229 | + | |
| 230 | + describe("complex patterns that mix literal and regex", () => { | |
| 231 | + it("should not break URLs with query parameters", () => { | |
| 232 | + const result = prepareQueryForRipgrep( | |
| 233 | + "https://api\\.example\\.com\\?param=\\w+", | |
| 234 | + ); | |
| 235 | + expect(result.query).toBe("https://api\\.example\\.com\\?param=\\w+"); | |
| 236 | + expect(result.warning).toBeUndefined(); | |
| 237 | + }); | |
| 238 | + | |
| 239 | + it("should not break file paths with regex metacharacters", () => { | |
| 240 | + const result = prepareQueryForRipgrep("/path/to/file\\.[jt]sx?"); | |
| 241 | + expect(result.query).toBe("/path/to/file\\.[jt]sx?"); | |
| 242 | + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve | |
| 243 | + }); | |
| 244 | + | |
| 245 | + it("should handle mixed escaped and unescaped patterns correctly", () => { | |
| 246 | + // This is a regex that matches function calls with optional whitespace | |
| 247 | + const result = prepareQueryForRipgrep("\\w+\\s*\\("); | |
| 248 | + expect(result.query).toBe("\\w+\\s*\\("); | |
| 249 | + expect(result.warning).toBeUndefined(); | |
| 250 | + }); | |
| 251 | + }); | |
| 252 | + | |
| 253 | + describe("edge cases that could trigger false positives", () => { | |
| 254 | + it("should not treat mathematical expressions as problematic", () => { | |
| 255 | + const result = prepareQueryForRipgrep("a + b * c"); | |
| 256 | + expect(result.query).toBe("a \\+ b \\* c"); // Should be escaped as literal | |
| 257 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 258 | + }); | |
| 259 | + | |
| 260 | + it("should not break regex that uses word boundaries", () => { | |
| 261 | + const result = prepareQueryForRipgrep("\\bclass\\b"); | |
| 262 | + expect(result.query).toBe("\\bclass\\b"); | |
| 263 | + expect(result.warning).toBeUndefined(); | |
| 264 | + }); | |
| 265 | + | |
| 266 | + it("should not break negated character classes", () => { | |
| 267 | + const result = prepareQueryForRipgrep("[^a-z]+"); | |
| 268 | + expect(result.query).toBe("[^a-z]+"); | |
| 269 | + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve | |
| 270 | + }); | |
| 271 | + | |
| 272 | + it("should not treat IPv4 addresses as problematic regex", () => { | |
| 273 | + const result = prepareQueryForRipgrep("192.168.1.1"); | |
| 274 | + expect(result.query).toBe("192\\.168\\.1\\.1"); // Should be escaped as literal | |
| 275 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 276 | + }); | |
| 277 | + | |
| 278 | + it("should not break hex color codes", () => { | |
| 279 | + const result = prepareQueryForRipgrep("#[0-9a-fA-F]{6}"); | |
| 280 | + expect(result.query).toBe("#[0-9a-fA-F]{6}"); | |
| 281 | + expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve regex | |
| 282 | + }); | |
| 283 | + }); | |
| 284 | + | |
| 285 | + describe("patterns that should preserve user intent", () => { | |
| 286 | + it("should not sanitize intentional regex alternation", () => { | |
| 287 | + const result = prepareQueryForRipgrep("(foo|bar)"); | |
| 288 | + expect(result.query).toBe("\\(foo\\|bar\\)"); // Should be escaped as literal since unescaped | |
| 289 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 290 | + }); | |
| 291 | + | |
| 292 | + it("should preserve escaped alternation in regex", () => { | |
| 293 | + const result = prepareQueryForRipgrep("\\(foo\\|bar\\)"); | |
| 294 | + expect(result.query).toBe("\\(foo\\|bar\\)"); | |
| 295 | + expect(result.warning).toBeUndefined(); | |
| 296 | + }); | |
| 297 | + | |
| 298 | + it("should not break SQL LIKE patterns when used as literal search", () => { | |
| 299 | + const result = prepareQueryForRipgrep("name LIKE '%john%'"); | |
| 300 | + expect(result.query).toBe("name LIKE '%john%'"); // No regex metacharacters here | |
| 301 | + expect(result.warning).toBeUndefined(); | |
| 302 | + }); | |
| 303 | + | |
| 304 | + it("should not break CSS selectors when used as literal search", () => { | |
| 305 | + const result = prepareQueryForRipgrep(".class-name > div:nth-child(2)"); | |
| 306 | + expect(result.query).toBe("\\.class-name > div:nth-child\\(2\\)"); | |
| 307 | + expect(result.warning).toContain("escaped for literal text search"); | |
| 308 | + }); | |
| 309 | + }); | |
| 310 | +}); |
modified core/util/sentry/SentryLogger.ts +4 −4
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { Extras } from "@sentry/core"; | |
| 1 | +import { Extras, type Integration, type Event } from "@sentry/core"; | |
| 2 | 2 | import * as Sentry from "@sentry/node"; |
| 3 | 3 | import os from "node:os"; |
| 4 | 4 | import { IdeInfo } from "../../index.js"; |
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | |
| 26 | 26 | // Filter integrations that use the global variable |
| 27 | 27 | const integrations = Sentry.getDefaultIntegrations({}).filter( |
| 28 | - (defaultIntegration) => { | |
| 28 | + (defaultIntegration: Integration) => { | |
| 29 | 29 | // Remove integrations that might interfere with shared environments |
| 30 | 30 | return  | |
| 16 | + | |
| 17 | 17 | |
| 18 | -## Learn More About MCP Blocks | |
| 18 | +## Learn More About MCP servers | |
| 19 | 19 | |
| 20 | 20 | Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details. |
modified docs/customization/models.mdx +116 −6
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "Model Blocks" | |
| 3 | -description: "These blocks form the foundation of the entire assistant experience, offering different specialized capabilities:" | |
| 2 | +title: "Models" | |
| 3 | +description: "Models form the foundation of the entire agent experience, offering different specialized capabilities:" | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | +import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx"; | |
| 7 | + | |
| 6 | 8 | - **[Chat](/customize/model-roles/chat)**: Power conversational interactions about code and provide detailed guidance |
| 7 | 9 | - **[Edit](/customize/model-roles/edit)**: Handle complex code transformations and refactoring tasks |
| 8 | 10 | - **[Apply](/customize/model-roles/apply)**: Execute targeted code modifications with high accuracy |
| @@ -10,10 +12,118 @@ | ||
| 10 | 12 | - **[Embedding](/customize/model-roles/embeddings)**: Transform code into vector representations for semantic search |
| 11 | 13 | - **[Reranker](/customize/model-roles/reranking)**: Improve search relevance by ordering results based on semantic meaning |
| 12 | 14 | |
| 13 | - | |
| 15 | + | |
| 16 | + | |
| 17 | +## Recommended Models | |
| 18 | + | |
| 19 | +### Best Models by Role | |
| 20 | + | |
| 21 | +<ModelRecommendations role="all" /> | |
| 22 | + | |
| 23 | +## Learn More About Models | |
| 24 | + | |
| 25 | +Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. | |
| 26 | + | |
| 27 | +Read more about [model roles](/customize/model-roles), [model capabilities](/customize/deep-dives/model-capabilities) and view [`models`](/reference#models) in the YAML Reference. | |
| 28 | + | |
| 29 | +### Example Model Setup Instructions | |
| 30 | + | |
| 31 | +# Frontier Models | |
| 32 | + | |
| 33 | +[Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic | |
| 34 | + | |
| 35 | +1. Get your API key from [Anthropic](https://console.anthropic.com/) | |
| 36 | +2. Add [Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) to an agent on Continue Hub | |
| 37 | +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) | |
| 38 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 39 | + | |
| 40 | +[Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) from Qwen | |
| 41 | + | |
| 42 | +1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) | |
| 43 | +2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) to an agent on Continue Hub | |
| 44 | +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) | |
| 45 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 46 | + | |
| 47 | +[GPT-5](https://hub.continue.dev/openai/gpt-5) from OpenAI | |
| 48 | + | |
| 49 | +1. Get your API key from [OpenAI](https://platform.openai.com) | |
| 50 | +2. Add [GPT-5](https://hub.continue.dev/openai/gpt-5) to an agent on Continue Hub | |
| 51 | +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) | |
| 52 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 53 | + | |
| 54 | +[Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) from Moonshot AI | |
| 55 | + | |
| 56 | +1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) | |
| 57 | +2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) to an agent on Continue Hub | |
| 58 | +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) | |
| 59 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 60 | + | |
| 61 | +[Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google | |
| 62 | + | |
| 63 | +1. Get your API key from [Google AI Studio](https://aistudio.google.com) | |
| 64 | +2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to an agent on Continue Hub | |
| 65 | +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) | |
| 66 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 67 | + | |
| 68 | +[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI | |
| 69 | + | |
| 70 | +1. Get your API key from [xAI](https://console.x.ai/) | |
| 71 | +2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to an agent on Continue Hub | |
| 72 | +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) | |
| 73 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 74 | + | |
| 75 | +[Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI | |
| 76 | + | |
| 77 | +1. Get your API key from [Mistral AI](https://console.mistral.ai/) | |
| 78 | +2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to an agent on Continue Hub | |
| 79 | +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) | |
| 80 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 81 | + | |
| 82 | +[gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) from OpenAI | |
| 83 | + | |
| 84 | +1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) | |
| 85 | +2. Add [gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) to an agent on Continue Hub | |
| 86 | +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) | |
| 87 | +4. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 88 | + | |
| 89 | +### Local Models | |
| 90 | + | |
| 91 | +These models can be run on your computer if you have enough VRAM. | |
| 92 | + | |
| 93 | +Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode. | |
| 94 | + | |
| 95 | +[Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) | |
| 96 | + | |
| 97 | +1. Add [Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) to an agent on Continue Hub | |
| 98 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 99 | +3. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 100 | + | |
| 101 | +[gpt-oss-20b](https://hub.continue.dev/ollama/gpt-oss-20b) | |
| 102 | + | |
| 103 | +1. Add [gpt-oss-20b](ttps://hub.continue.dev/ollama/gpt-oss-20b) to an agent on Continue Hub | |
| 104 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 105 | +3. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 106 | + | |
| 107 | +[Devstral Small 27B](https://hub.continue.dev/ollama/devstral) | |
| 108 | + | |
| 109 | +1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to an agent on Continue Hub | |
| 110 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 111 | +3. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 112 | + | |
| 113 | +[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen | |
| 114 | + | |
| 115 | +1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to an agent on Continue Hub | |
| 116 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 117 | +3. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 118 | + | |
| 119 | +[Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google | |
| 14 | 120 | |
| 15 | -## Learn More About Model Blocks | |
| 121 | +1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) to an agent on Continue Hub | |
| 122 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 123 | +3. Click `Reload config` in the agent selector in the Continue IDE extension | |
| 16 | 124 | |
| 17 | -Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. | |
| 125 | +[Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) from Qwen | |
| 18 | 126 | |
| 19 | -Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference. | |
| 127 | +1. Add [Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to an agent on Continue Hub | |
| 128 | +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) | |
| 129 | +3. Click `Reload config` in the agent selector in the Continue IDE extension |
modified docs/customization/overview.mdx +8 −12
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Customization Overview" |
| 3 | -description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding assistant" | |
| 3 | +description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding agent" | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | 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. |
| @@ -13,10 +13,6 @@ | ||
| 13 | 13 | |
| 14 | 14 | 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). |
| 15 | 15 | |
| 16 | -## Add a Context Provider | |
| 17 | - | |
| 18 | -Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/custom-providers). | |
| 19 | - | |
| 20 | 16 | ## Create a Slash Command |
| 21 | 17 | |
| 22 | 18 | 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). |
| @@ -25,15 +21,15 @@ | ||
| 25 | 21 | |
| 26 | 22 | Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools) |
| 27 | 23 | |
| 28 | -Whatever you choose, you'll probably start by editing your Assistant. | |
| 24 | +Whatever you choose, you'll probably start by editing your Agent. | |
| 29 | 25 | |
| 30 | -## Edit Your Assistant | |
| 26 | +## Edit Your Agent | |
| 31 | 27 | |
| 32 | -You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. | |
| 28 | +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. | |
| 33 | 29 | |
| 34 | - | |
| 30 | + | |
| 35 | 31 | |
| 36 | -## Manage Your Assistant | |
| 32 | +## Manage Your Agent | |
| 37 | 33 | |
| 38 | -- See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant | |
| 39 | -- See the [Config Deep Dive](/reference) for more details on configuring local assistants. | |
| 34 | +- See [Editing Hub Agents](/hub/agents/edit-an-agent) for more details on managing your hub agent | |
| 35 | +- See the [Config Deep Dive](/reference) for more details on configuring local agents. |
modified docs/customization/prompts.mdx +3 −3
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "Prompt Blocks" | |
| 2 | +title: "Prompts" | |
| 3 | 3 | description: "These are the specialized instructions that shape how models respond:" |
| 4 | 4 | --- |
| 5 | 5 | |
| @@ -9,8 +9,8 @@ | ||
| 9 | 9 | - **Can be shared and reused** across multiple assistants |
| 10 | 10 | - **Act as automated code reviewers** that ensure consistency across teams |
| 11 | 11 | |
| 12 | - | |
| 12 | + | |
| 13 | 13 | |
| 14 | 14 | ## Learn More |
| 15 | 15 | |
| 16 | -Prompt blocks have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts). | |
| 16 | +Prompts have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts). |
modified docs/customization/rules.mdx +6 −6
| @@ -1,18 +1,18 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "Rules Blocks" | |
| 3 | -description: "Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses." | |
| 2 | +title: "Rules" | |
| 3 | +description: "Rules allow you to provide specific instructions that guide how the AI agent behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Think of these as the guardrails for your AI coding assistants: | |
| 6 | +Think of these as the guardrails for your AI coding agents: | |
| 7 | 7 | |
| 8 | 8 | - **Enforce company-specific coding standards** and security practices |
| 9 | 9 | - **Implement quality checks** that match your engineering culture |
| 10 | 10 | - **Create paved paths** for developers to follow organizational best practices |
| 11 | 11 | |
| 12 | -By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints. | |
| 12 | +By implementing rules, you transform the AI from a generic coding agent into a knowledgeable team member that understands your project's unique requirements and constraints. | |
| 13 | 13 | |
| 14 | 14 | ## How Rules Work |
| 15 | 15 | |
| 16 | -Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. | |
| 16 | +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. | |
| 17 | 17 | |
| 18 | -Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. | |
| 18 | +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 the end of the file |
deleted docs/customize/context/_category_.json +0 −4
| @@ -1,4 +0,0 @@ | ||
| 1 | -{ | |
| 2 | - "label": "Context", | |
| 3 | - "position": 2 | |
| 4 | -} |
deleted docs/customize/context/codebase.mdx +0 −104
| @@ -1,104 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Set Up @Codebase Context Provider in Continue" | |
| 3 | -description: Retrieve relevant context and answers from your codebase using embeddings and keyword search. | |
| 4 | -keywords: [talk, embeddings, reranker, codebase, experimental] | |
| 5 | -sidebarTitle: "@Codebase" | |
| 6 | ---- | |
| 7 | - | |
| 8 | -Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`. | |
| 9 | - | |
| 10 | -<Info> | |
| 11 | - **Note:** `transformers.js` cannot be used in JetBrains IDEs. However, you can | |
| 12 | - select a different embeddings model from [the list | |
| 13 | - here](../model-roles/embeddings). | |
| 14 | -</Info> | |
| 15 | - | |
| 16 | -## How to Use @Codebase and @Folder Context Providers | |
| 17 | - | |
| 18 | -Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. | |
| 19 | - | |
| 20 | -### When @Codebase Context Provider Is Useful | |
| 21 | - | |
| 22 | -Here are some common use cases where it can be useful: | |
| 23 | - | |
| 24 | -- **Asking high-level questions about your codebase** | |
| 25 | - - "How do I add a new endpoint to the server?" | |
| 26 | - - "Do we use VS Code's CodeLens feature anywhere?" | |
| 27 | - - "Is there any code written already to convert HTML to markdown?" | |
| 28 | -- **Generate code using existing samples as reference** | |
| 29 | - - "Generate a new React component with a date picker, using the same patterns as existing components" | |
| 30 | - - "Write a draft of a CLI application for this project using Python's argparse" | |
| 31 | - - "Implement the `foo` method in the `bar` class, following the patterns seen in other subclasses of `baz`. | |
| 32 | -- **Use `@Folder` to ask questions about a specific folder, increasing the likelihood of relevant results** | |
| 33 | - - "What is the main purpose of this folder?" | |
| 34 | - - "How do we use VS Code's CodeLens API?" | |
| 35 | - - Or any of the above examples, but with `@Folder` instead of `@Codebase` | |
| 36 | - | |
| 37 | -### When @Codebase Context Provider Is Not Useful | |
| 38 | - | |
| 39 | -Here are use cases where it is not useful: | |
| 40 | - | |
| 41 | -- **When you need the LLM to see _literally every_ file in your codebase** | |
| 42 | - - "Find everywhere where the `foo` function is called" | |
| 43 | - - "Review our codebase and find any spelling mistakes" | |
| 44 | -- **Refactoring tasks** | |
| 45 | - - "Add a new parameter to the `bar` function and update usages" | |
| 46 | - | |
| 47 | -## How to Configure @Codebase Context Provider Settings | |
| 48 | - | |
| 49 | -There are a few options that let you configure the behavior of the `@codebase` context provider, which are the same for the `@folder` context provider: | |
| 50 | - | |
| 51 | -<Tabs> | |
| 52 | - <Tab title="YAML"> | |
| 53 | - ```yaml title="config.yaml" | |
| 54 | - context: | |
| 55 | - - provider: codebase | |
| 56 | - params: | |
| 57 | - nRetrieve: 25 | |
| 58 | - nFinal: 5 | |
| 59 | - useReranking: true | |
| 60 | - ``` | |
| 61 | - </Tab> | |
| 62 | - <Tab title="JSON"> | |
| 63 | - ```json title="config.json" | |
| 64 | - { | |
| 65 | - "contextProviders": [ | |
| 66 | - { | |
| 67 | - "name": "codebase", | |
| 68 | - "params": { | |
| 69 | - "nRetrieve": 25, | |
| 70 | - "nFinal": 5, | |
| 71 | - "useReranking": true | |
| 72 | - } | |
| 73 | - } | |
| 74 | - ] | |
| 75 | - } | |
| 76 | - ``` | |
| 77 | - </Tab> | |
| 78 | -</Tabs> | |
| 79 | - | |
| 80 | -### `nRetrieve` | |
| 81 | - | |
| 82 | -Number of results to initially retrieve from vector database (default: 25) | |
| 83 | - | |
| 84 | -### `nFinal` | |
| 85 | - | |
| 86 | -Final number of results to use after re-ranking (default: 5) | |
| 87 | - | |
| 88 | -### `useReranking` | |
| 89 | - | |
| 90 | -Whether to use re-ranking, which will allow initial selection of `nRetrieve` results, then will use an LLM to select the top `nFinal` results (default: true) | |
| 91 | - | |
| 92 | -## How to Ignore Files During Indexing | |
| 93 | - | |
| 94 | -Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`. | |
| 95 | - | |
| 96 | -Continue also supports a **global** `.continueignore` file that will be respected for all workspaces, which can be created at `~/.continue/.continueignore`. | |
| 97 | - | |
| 98 | -If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. | |
| 99 | - | |
| 100 | -If you need to force a refresh of the index, reload the VS Code window with <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>p</kbd> + "Reload Window". | |
| 101 | - | |
| 102 | -## How Repository Map Enhances Codebase Understanding | |
| 103 | - | |
| 104 | -Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](/customize/context/codebase#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. |
deleted docs/customize/context/documentation.mdx +0 −408
| @@ -1,408 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Set Up @Docs Context Provider in Continue" | |
| 3 | -description: Learn how to access and search your project's documentation directly within Continue | |
| 4 | -keywords: | |
| 5 | - [ | |
| 6 | - documentation, | |
| 7 | - indexing, | |
| 8 | - context provider, | |
| 9 | - embeddings, | |
| 10 | - docs, | |
| 11 | - embedder, | |
| 12 | - embeddings provider, | |
| 13 | - documentation, | |
| 14 | - ] | |
| 15 | -toc_max_heading_level: 5 | |
| 16 | -sidebarTitle: "@Docs" | |
| 17 | ---- | |
| 18 | - | |
| 19 | -The `@Docs` context provider allows you to efficiently reference documentation directly within Continue. | |
| 20 | - | |
| 21 | -## How to Enable the @Docs Context Provider | |
| 22 | - | |
| 23 | -To enable the `@Docs` context provider, add it to the list of context providers in your `config.json` file. | |
| 24 | - | |
| 25 | -<Tabs> | |
| 26 | - <Tab title="YAML"> | |
| 27 | - ```yaml title="config.yaml" | |
| 28 | - context: | |
| 29 | - - provider: docs | |
| 30 | - ``` | |
| 31 | - </Tab> | |
| 32 | - <Tab title="JSON"> | |
| 33 | - ```json title="config.json" | |
| 34 | - { | |
| 35 | - "contextProviders": [ | |
| 36 | - { | |
| 37 | - "name": "docs" | |
| 38 | - } | |
| 39 | - ] | |
| 40 | - } | |
| 41 | - ``` | |
| 42 | - </Tab> | |
| 43 | -</Tabs> | |
| 44 | - | |
| 45 | -## How the @Docs Context Provider Works | |
| 46 | - | |
| 47 | -The `@Docs` context provider works by | |
| 48 | - | |
| 49 | -1. Crawling specified documentation sites | |
| 50 | -2. Generating embeddings for the chunked content | |
| 51 | -3. Storing the embeddings locally on your machine | |
| 52 | -4. Embedding chat input to include similar documentation chunks as context | |
| 53 | - | |
| 54 | -## How to Index Your Own Documentation | |
| 55 | - | |
| 56 | -### Using Hub `docs` Blocks | |
| 57 | - | |
| 58 | -@Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). | |
| 59 | - | |
| 60 | -### How to Add Documentation Through the @Docs Context Provider | |
| 61 | - | |
| 62 | -To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed | |
| 63 | - | |
| 64 | -- from the `@Docs` context provider - type `@Docs` in the chat, hit `Enter`, and search for `Add Docs` | |
| 65 | -- from the `More` page (three dots icon) in the `@docs indexes` section | |
| 66 | - the `@Docs` context provider. | |
| 67 | - | |
| 68 | -In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site. | |
| 69 | - | |
| 70 | -- `Title`: The name of the documentation site, used for identification in the UI. | |
| 71 | -- `Start URL`: The URL where the indexing process should begin. | |
| 72 | - | |
| 73 | -Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page. | |
| 74 | - | |
| 75 | -Documentation sources may be suggested based on package files in your repo. This currently works for Python `requirements.txt` files and Node.js (Javascript/Typescript) `package.json` files. | |
| 76 | - | |
| 77 | -- Packages with a valid documentation URL (with a `+` icon) can be clicked to immediately kick off indexing | |
| 78 | -- Packages with partial information (with a pen icon) can be clicked to fill the form with the available information | |
| 79 | -- Note that you can hover over the information icon to see where the package suggestion was found. | |
| 80 | - | |
| 81 | - | |
| 82 | - | |
| 83 | -### How to Add Documentation in Configuration Files | |
| 84 | - | |
| 85 | -For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows: | |
| 86 | - | |
| 87 | -<Tabs> | |
| 88 | - <Tab title="YAML"> | |
| 89 | - ```yaml title="config.yaml" | |
| 90 | - docs: | |
| 91 | - - title: Nest.js | |
| 92 | - startUrl: https://docs.nestjs.com/ | |
| 93 | - faviconUrl: https://docs.nestjs.com/favicon.ico | |
| 94 | - ``` | |
| 95 | - </Tab> | |
| 96 | - <Tab title="JSON"> | |
| 97 | - ```json title="config.json" | |
| 98 | - { | |
| 99 | - "docs": [ | |
| 100 | - { | |
| 101 | - "title": "Nest.js", | |
| 102 | - "startUrl": "https://docs.nestjs.com/", | |
| 103 | - "faviconUrl": "https://docs.nestjs.com/favicon.ico" | |
| 104 | - } | |
| 105 | - ] | |
| 106 | - } | |
| 107 | - ``` | |
| 108 | - </Tab> | |
| 109 | -</Tabs> | |
| 110 | - | |
| 111 | -See [the config reference](/reference) for all documentation site configuration options. | |
| 112 | - | |
| 113 | -Indexing will re-sync upon saving the configuration file. | |
| 114 | - | |
| 115 | -## How to Configure @Docs Advanced Settings | |
| 116 | - | |
| 117 | -### How to Use Your Custom Embeddings Provider | |
| 118 | - | |
| 119 | -If you have set up an [embeddings provider](../model-roles/embeddings.mdx), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration. | |
| 120 | - | |
| 121 | -### How to Configure Reranking for Better Results | |
| 122 | - | |
| 123 | -As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`. | |
| 124 | - | |
| 125 | -<Tabs> | |
| 126 | - <Tab title="YAML"> | |
| 127 | - ```yaml title="config.yaml" | |
| 128 | - context: | |
| 129 | - - provider: docs | |
| 130 | - params: | |
| 131 | - nRetrieve: 25 # The number of docs to retrieve from the embeddings query | |
| 132 | - nFinal: 5 # The number of docs chunks to return IF reranking | |
| 133 | - useReranking: true # use reranking if a reranker is configured (defaults to true) | |
| 134 | - ``` | |
| 135 | - </Tab> | |
| 136 | - <Tab title="JSON"> | |
| 137 | - ```json title="config.json" | |
| 138 | - { | |
| 139 | - "contextProviders": [ | |
| 140 | - { | |
| 141 | - "name": "docs", | |
| 142 | - "params": { | |
| 143 | - "nRetrieve": 25, // The number of docs to retrieve from the embeddings query | |
| 144 | - "nFinal": 5, // The number of docs chunks to return IF reranking | |
| 145 | - "useReranking": true // use reranking if a reranker is configured (defaults to true) | |
| 146 | - } | |
| 147 | - } | |
| 148 | - ] | |
| 149 | - } | |
| 150 | - ``` | |
| 151 | - </Tab> | |
| 152 | -</Tabs> | |
| 153 | - | |
| 154 | -### How to Set Up GitHub Token for GitHub Documentation | |
| 155 | - | |
| 156 | -The GitHub API rate limits public requests to 60 per hour. If you want to reliably index GitHub repos, you can add a github token to your config file: | |
| 157 | - | |
| 158 | -<Tabs> | |
| 159 | - <Tab title="YAML"> | |
| 160 | - ```yaml title="config.yaml" | |
| 161 | - context: | |
| 162 | - - provider: docs | |
| 163 | - params: | |
| 164 | - githubToken: <GITHUB_TOKEN> | |
| 165 | - ``` | |
| 166 | - </Tab> | |
| 167 | - <Tab title="JSON"> | |
| 168 | - ```json title="config.json" | |
| 169 | - { | |
| 170 | - "contextProviders": [ | |
| 171 | - { | |
| 172 | - "name": "docs", | |
| 173 | - "params": { | |
| 174 | - "githubToken": "github_..." | |
| 175 | - } | |
| 176 | - } | |
| 177 | - ] | |
| 178 | - } | |
| 179 | - ``` | |
| 180 | - </Tab> | |
| 181 | -</Tabs> | |
| 182 | - | |
| 183 | -### How to Enable Local Crawling for Private Documentation | |
| 184 | - | |
| 185 | -By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites. | |
| 186 | - | |
| 187 | -If your documentation is private, you can skip the default crawler and use a local crawler instead by setting `useLocalCrawling` to `true`. | |
| 188 | - | |
| 189 | -<Tabs> | |
| 190 | - <Tab title="YAML"> | |
| 191 | - ```yaml title="config.yaml" | |
| 192 | - docs: | |
| 193 | - - title: My Private Docs | |
| 194 | - startUrl: http://10.2.1.2/docs | |
| 195 | - faviconUrl: http://10.2.1.2/docs/assets/favicon.ico, | |
| 196 | - useLocalCrawling: true | |
| 197 | - ``` | |
| 198 | - </Tab> | |
| 199 | - <Tab title="JSON"> | |
| 200 | - ```json title="config.json" | |
| 201 | - { | |
| 202 | - "docs": [ | |
| 203 | - { | |
| 204 | - "title": "My Private Docs", | |
| 205 | - "startUrl": "http://10.2.1.2/docs", | |
| 206 | - "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", | |
| 207 | - "useLocalCrawling": true | |
| 208 | - } | |
| 209 | - ] | |
| 210 | - } | |
| 211 | - ``` | |
| 212 | - </Tab> | |
| 213 | -</Tabs> | |
| 214 | - | |
| 215 | -<Info> | |
| 216 | - The default local crawler is a lightweight tool that cannot render sites that | |
| 217 | - are dynamically generated using JavaScript. If your sites need to be rendered, | |
| 218 | - you can enable the experimental `Use Chromium for Docs Crawling` feature from | |
| 219 | - your [User Settings Page](../settings) This will download and install Chromium | |
| 220 | - to `~/.continue/.utils`, and use it as the local crawler. **Note:** Chromium | |
| 221 | - crawling support is being deprecated and may be removed in future versions. | |
| 222 | -</Info> | |
| 223 | - | |
| 224 | -Further notes: | |
| 225 | - | |
| 226 | -- If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential. | |
| 227 | -- For GitHub Repos this has no effect because only the GitHub Crawler will be used, and if the repo is private it can only be accessed with a priveleged GitHub token anyways. | |
| 228 | - | |
| 229 | -## How to Manage Your Documentation Indexes | |
| 230 | - | |
| 231 | -You can view indexing statuses and manage your documentation sites from the `@docs indexes` section of the `More` page (three dots) | |
| 232 | - | |
| 233 | -- Continue does not automatically re-index your docs. Use `Click to re-index` to trigger a reindex for a specific source | |
| 234 | -- While a site is indexing, click `Cancel indexing` to cancel the process | |
| 235 | -- Failed indexing attempts will show an error status bar and icon | |
| 236 | -- Delete a documentation site from your configuration using the trash icon | |
| 237 | - | |
| 238 | - | |
| 239 | - | |
| 240 | -You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page | |
| 241 | - | |
| 242 | - | |
| 243 | - | |
| 244 | -You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`. | |
| 245 | - | |
| 246 | -## Configuration Examples for Different Setups | |
| 247 | - | |
| 248 | -### How to Set Up @Docs in VS Code (Minimal Configuration) | |
| 249 | - | |
| 250 | -The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. | |
| 251 | - | |
| 252 | -<Tabs> | |
| 253 | - <Tab title="YAML"> | |
| 254 | - ```yaml title="config.yaml" | |
| 255 | - context: | |
| 256 | - - provider: docs | |
| 257 | - | |
| 258 | - docs: | |
| 259 | - - title: Nest.js | |
| 260 | - startUrl: https://docs.nestjs.com/ | |
| 261 | - ``` | |
| 262 | - </Tab> | |
| 263 | - <Tab title="JSON"> | |
| 264 | - ```json title="config.json" | |
| 265 | - { | |
| 266 | - "contextProviders": [ | |
| 267 | - { | |
| 268 | - "name": "docs", | |
| 269 | - } | |
| 270 | - ], | |
| 271 | - "docs": [ | |
| 272 | - { | |
| 273 | - "title": "Nest.js", | |
| 274 | - "startUrl": "https://docs.nestjs.com/", | |
| 275 | - }, | |
| 276 | - ] | |
| 277 | - } | |
| 278 | - ``` | |
| 279 | - </Tab> | |
| 280 | -</Tabs> | |
| 281 | - | |
| 282 | -### How to Set Up @Docs in JetBrains IDEs (Minimal Configuration) | |
| 283 | - | |
| 284 | -Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). | |
| 285 | - | |
| 286 | -<Tabs> | |
| 287 | - <Tab title="YAML"> | |
| 288 | - ```yaml title="config.yaml" | |
| 289 | - models: | |
| 290 | - - name: LMStudio embedder | |
| 291 | - provider: lmstudio | |
| 292 | - model: nomic-ai/nomic-embed-text-v1.5-GGUF | |
| 293 | - roles: | |
| 294 | - - embed | |
| 295 | - context: | |
| 296 | - - provider: docs | |
| 297 | - docs: | |
| 298 | - - title: Nest.js | |
| 299 | - startUrl: https://docs.nestjs.com/ | |
| 300 | - ``` | |
| 301 | - </Tab> | |
| 302 | - <Tab title="JSON"> | |
| 303 | - ```json title="config.json" | |
| 304 | - { | |
| 305 | - "contextProviders": [ | |
| 306 | - { | |
| 307 | - "name": "docs", | |
| 308 | - } | |
| 309 | - ], | |
| 310 | - "docs": [ | |
| 311 | - { | |
| 312 | - "title": "Nest.js", | |
| 313 | - "startUrl": "https://docs.nestjs.com/", | |
| 314 | - }, | |
| 315 | - ], | |
| 316 | - "embeddingsProvider": { | |
| 317 | - "provider": "lmstudio", | |
| 318 | - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" | |
| 319 | - } | |
| 320 | - } | |
| 321 | - ``` | |
| 322 | - </Tab> | |
| 323 | -</Tabs> | |
| 324 | - | |
| 325 | -### How to Set Up @Docs with Advanced Features (VS Code or JetBrains) | |
| 326 | - | |
| 327 | -The following configuration example includes: | |
| 328 | - | |
| 329 | -- Examples of both public and private documentation sources | |
| 330 | -- A custom embeddings provider | |
| 331 | -- A reranker model available, with reranking parameters customized | |
| 332 | -- A GitHub token to enable GitHub crawling | |
| 333 | - | |
| 334 | -<Tabs> | |
| 335 | - <Tab title="YAML"> | |
| 336 | - ```yaml title="config.yaml" | |
| 337 | - models: | |
| 338 | - - name: LMStudio Nomic Text | |
| 339 | - provider: lmstudio | |
| 340 | - model: nomic-ai/nomic-embed-text-v1.5-GGUF | |
| 341 | - roles: | |
| 342 | - - embed | |
| 343 | - - name: Voyage Rerank-2 | |
| 344 | - provider: voyage | |
| 345 | - apiKey: <VOYAGE_API_KEY> | |
| 346 | - model: rerank-2 | |
| 347 | - roles: | |
| 348 | - - rerank | |
| 349 | - context: | |
| 350 | - - provider: docs | |
| 351 | - params: | |
| 352 | - githubToken: <GITHUB_TOKEN> | |
| 353 | - nRetrieve: 25 | |
| 354 | - nFinal: 5 | |
| 355 | - useReranking: true | |
| 356 | - docs: | |
| 357 | - - title: Nest.js | |
| 358 | - startUrl: https://docs.nestjs.com/ | |
| 359 | - - title: My Private Docs | |
| 360 | - startUrl: http://10.2.1.2/docs | |
| 361 | - faviconUrl: http://10.2.1.2/docs/assets/favicon.ico | |
| 362 | - useLocalCrawling: true | |
| 363 | - ``` | |
| 364 | - </Tab> | |
| 365 | - <Tab title="JSON"> | |
| 366 | - ```json title="config.json" | |
| 367 | - { | |
| 368 | - "contextProviders": [ | |
| 369 | - { | |
| 370 | - "name": "docs", | |
| 371 | - "params": { | |
| 372 | - "githubToken": "github_...", | |
| 373 | - "nRetrieve": 25, | |
| 374 | - "nFinal": 5, | |
| 375 | - "useReranking": true | |
| 376 | - } | |
| 377 | - } | |
| 378 | - ], | |
| 379 | - "docs": [ | |
| 380 | - { | |
| 381 | - "title": "Nest.js", | |
| 382 | - "startUrl": "https://docs.nestjs.com/" | |
| 383 | - }, | |
| 384 | - { | |
| 385 | - "title": "My Private Docs", | |
| 386 | - "startUrl": "http://10.2.1.2/docs", | |
| 387 | - "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", | |
| 388 | - "maxDepth": 4, | |
| 389 | - "useLocalCrawling": true | |
| 390 | - } | |
| 391 | - ], | |
| 392 | - "reranker": { | |
| 393 | - "name": "voyage", | |
| 394 | - "params": { | |
| 395 | - "model": "rerank-2", | |
| 396 | - "apiKey": "<YOUR_VOYAGE_API_KEY>" | |
| 397 | - } | |
| 398 | - }, | |
| 399 | - "embeddingsProvider": { | |
| 400 | - "provider": "lmstudio", | |
| 401 | - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" | |
| 402 | - } | |
| 403 | - } | |
| 404 | - ``` | |
| 405 | - </Tab> | |
| 406 | -</Tabs> | |
| 407 | - | |
| 408 | -This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../settings). |
modified docs/customize/custom-providers.mdx +0 −426
| @@ -437,432 +437,6 @@ | ||
| 437 | 437 | |
| 438 | 438 | You'll then be able to type "@" and see "MCP" in the context providers dropdown. |
| 439 | 439 | |
| 440 | -### @Issue Context Provider – Reference GitHub Issue Conversations | |
| 441 | - | |
| 442 | -Reference the conversation in a GitHub issue. | |
| 443 | - | |
| 444 | -- YAML | |
| 445 | -- JSON | |
| 446 | - | |
| 447 | -config.yaml | |
| 448 | - | |
| 449 | -``` | |
| 450 | -context: | |
| 451 | - - provider: issue | |
| 452 | - params: | |
| 453 | - repos: | |
| 454 | - - owner: continuedev | |
| 455 | - repo: continue | |
| 456 | - githubToken: ghp_xxx | |
| 457 | -``` | |
| 458 | - | |
| 459 | -config.json | |
| 460 | - | |
| 461 | -```json | |
| 462 | -{ | |
| 463 | - "contextProviders": [ | |
| 464 | - { | |
| 465 | - "name": "issue", | |
| 466 | - "params": { | |
| 467 | - "repos": [{ "owner": "continuedev", "repo": "continue" }], | |
| 468 | - "githubToken": "ghp_xxx" | |
| 469 | - } | |
| 470 | - } | |
| 471 | - ] | |
| 472 | -} | |
| 473 | -``` | |
| 474 | - | |
| 475 | -Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited. | |
| 476 | - | |
| 477 | -### @Database Context Provider – Reference Database Table Schemas | |
| 478 | - | |
| 479 | -Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. | |
| 480 | - | |
| 481 | -- YAML | |
| 482 | -- JSON | |
| 483 | - | |
| 484 | -config.yaml | |
| 485 | - | |
| 486 | -``` | |
| 487 | -context: | |
| 488 | - - provider: database | |
| 489 | - params: | |
| 490 | - connections: | |
| 491 | - - name: examplePostgres | |
| 492 | - connection_type: postgres | |
| 493 | - connection: | |
| 494 | - user: username | |
| 495 | - host: localhost | |
| 496 | - database: exampleDB | |
| 497 | - password: yourPassword | |
| 498 | - port: 5432 | |
| 499 | - - name: exampleMssql | |
| 500 | - connection_type: mssql | |
| 501 | - connection: | |
| 502 | - user: username | |
| 503 | - server: localhost | |
| 504 | - database: exampleDB | |
| 505 | - password: yourPassword | |
| 506 | - - name: exampleSqlite | |
| 507 | - connection_type: sqlite | |
| 508 | - connection: | |
| 509 | - filename: /path/to/your/sqlite/database.db | |
| 510 | -``` | |
| 511 | - | |
| 512 | -config.json | |
| 513 | - | |
| 514 | -```json | |
| 515 | -{ | |
| 516 | - "contextProviders": [ | |
| 517 | - { | |
| 518 | - "name": "database", | |
| 519 | - "params": { | |
| 520 | - "connections": [ | |
| 521 | - { | |
| 522 | - "name": "examplePostgres", | |
| 523 | - "connection_type": "postgres", | |
| 524 | - "connection": { | |
| 525 | - "user": "username", | |
| 526 | - "host": "localhost", | |
| 527 | - "database": "exampleDB", | |
| 528 | - "password": "yourPassword", | |
| 529 | - "port": 5432 | |
| 530 | - } | |
| 531 | - }, | |
| 532 | - { | |
| 533 | - "name": "exampleMssql", | |
| 534 | - "connection_type": "mssql", | |
| 535 | - "connection": { | |
| 536 | - "user": "username", | |
| 537 | - "server": "localhost", | |
| 538 | - "database": "exampleDB", | |
| 539 | - "password": "yourPassword" | |
| 540 | - } | |
| 541 | - }, | |
| 542 | - { | |
| 543 | - "name": "exampleSqlite", | |
| 544 | - "connection_type": "sqlite", | |
| 545 | - "connection": { "filename": "/path/to/your/sqlite/database.db" } | |
| 546 | - } | |
| 547 | - ] | |
| 548 | - } | |
| 549 | - } | |
| 550 | - ] | |
| 551 | -} | |
| 552 | -``` | |
| 553 | - | |
| 554 | -Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. | |
| 555 | - | |
| 556 | -Available connection types: | |
| 557 | - | |
| 558 | -- `postgres` | |
| 559 | -- `mysql` | |
| 560 | -- `sqlite` | |
| 561 | - | |
| 562 | -### @Google Context Provider – Reference Google Search Results | |
| 563 | - | |
| 564 | -Reference the results of a Google search. | |
| 565 | - | |
| 566 | -- YAML | |
| 567 | -- JSON | |
| 568 | - | |
| 569 | -config.yaml | |
| 570 | - | |
| 571 | -``` | |
| 572 | -context: | |
| 573 | - - provider: google | |
| 574 | - params: | |
| 575 | - serperApiKey: <YOUR_SERPER.DEV_API_KEY> | |
| 576 | -``` | |
| 577 | - | |
| 578 | -config.json | |
| 579 | - | |
| 580 | -```json | |
| 581 | -{ | |
| 582 | - "contextProviders": [ | |
| 583 | - { | |
| 584 | - "name": "google", | |
| 585 | - "params": { "serperApiKey": "<YOUR_SERPER.DEV_API_KEY>" } | |
| 586 | - } | |
| 587 | - ] | |
| 588 | -} | |
| 589 | -``` | |
| 590 | - | |
| 591 | -For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. | |
| 592 | - | |
| 593 | -Note: You can get an API key for free at [serper.dev](https://serper.dev). | |
| 594 | - | |
| 595 | -### @Gitlab Merge Request Context Provider – Reference GitLab Merge Requests | |
| 596 | - | |
| 597 | -Reference an open MR for this branch on GitLab. | |
| 598 | - | |
| 599 | -- YAML | |
| 600 | -- JSON | |
| 601 | - | |
| 602 | -config.yaml | |
| 603 | - | |
| 604 | -``` | |
| 605 | -context: | |
| 606 | - - provider: gitlab-mr | |
| 607 | - params: | |
| 608 | - token: "..." | |
| 609 | -``` | |
| 610 | - | |
| 611 | -config.json | |
| 612 | - | |
| 613 | -```json | |
| 614 | -{ "contextProviders": [{ "name": "gitlab-mr", "params": { "token": "..." } }] } | |
| 615 | -``` | |
| 616 | - | |
| 617 | -You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. | |
| 618 | - | |
| 619 | -#### How to Use Self-Hosted GitLab | |
| 620 | - | |
| 621 | -You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`. | |
| 622 | - | |
| 623 | -- YAML | |
| 624 | -- JSON | |
| 625 | - | |
| 626 | -config.yaml | |
| 627 | - | |
| 628 | -``` | |
| 629 | -context: | |
| 630 | - - provider: gitlab-mr | |
| 631 | - params: | |
| 632 | - token: "..." | |
| 633 | - domain: "gitlab.example.com" | |
| 634 | -``` | |
| 635 | - | |
| 636 | -config.json | |
| 637 | - | |
| 638 | -```json | |
| 639 | -{ | |
| 640 | - "contextProviders": [ | |
| 641 | - { | |
| 642 | - "name": "gitlab-mr", | |
| 643 | - "params": { "token": "...", "domain": "gitlab.example.com" } | |
| 644 | - } | |
| 645 | - ] | |
| 646 | -} | |
| 647 | -``` | |
| 648 | - | |
| 649 | -#### How to Provide Context by Filtering Comments | |
| 650 | - | |
| 651 | -If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`. | |
| 652 | - | |
| 653 | -### @Jira Context Provider – Reference Jira Issues | |
| 654 | - | |
| 655 | -Reference the conversation in a Jira issue. | |
| 656 | - | |
| 657 | -- YAML | |
| 658 | -- JSON | |
| 659 | - | |
| 660 | -config.yaml | |
| 661 | - | |
| 662 | -``` | |
| 663 | -context: | |
| 664 | - - provider: jira | |
| 665 | - params: | |
| 666 | - domain: company.atlassian.net | |
| 667 | - token: ATATT... | |
| 668 | -``` | |
| 669 | - | |
| 670 | -config.json | |
| 671 | - | |
| 672 | -```json | |
| 673 | -{ | |
| 674 | - "contextProviders": [ | |
| 675 | - { | |
| 676 | - "name": "jira", | |
| 677 | - "params": { "domain": "company.atlassian.net", "token": "ATATT..." } | |
| 678 | - } | |
| 679 | - ] | |
| 680 | -} | |
| 681 | -``` | |
| 682 | - | |
| 683 | -Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email. | |
| 684 | - | |
| 685 | -#### Jira Datacenter Support | |
| 686 | - | |
| 687 | -This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property. | |
| 688 | - | |
| 689 | -- YAML | |
| 690 | -- JSON | |
| 691 | - | |
| 692 | -config.yaml | |
| 693 | - | |
| 694 | -``` | |
| 695 | -context: | |
| 696 | - - provider: jira | |
| 697 | - params: | |
| 698 | - apiVersion: "2" | |
| 699 | -``` | |
| 700 | - | |
| 701 | -config.json | |
| 702 | - | |
| 703 | -```json | |
| 704 | -{ "contextProviders": [{ "name": "jira", "params": { "apiVersion": "2" } }] } | |
| 705 | -``` | |
| 706 | - | |
| 707 | -#### Issue Query | |
| 708 | - | |
| 709 | -By default, the following query will be used to find issues: | |
| 710 | - | |
| 711 | -``` | |
| 712 | -assignee = currentUser() AND resolution = Unresolved order by updated DESC | |
| 713 | -``` | |
| 714 | - | |
| 715 | -You can override this query by setting the `issueQuery` parameter. | |
| 716 | - | |
| 717 | -#### Max results | |
| 718 | - | |
| 719 | -You can set the `maxResults` parameter to limit the number of results returned. The default is `50`. | |
| 720 | - | |
| 721 | -### @Discord Context Provider – Reference Messages in Discord Channels | |
| 722 | - | |
| 723 | -Reference the messages in a Discord channel. | |
| 724 | - | |
| 725 | -- YAML | |
| 726 | -- JSON | |
| 727 | - | |
| 728 | -config.yaml | |
| 729 | - | |
| 730 | -``` | |
| 731 | -context: | |
| 732 | - - provider: discord | |
| 733 | - params: | |
| 734 | - discordKey: "bot token" | |
| 735 | - guildId: "1234567890" | |
| 736 | - channels: | |
| 737 | - - id: "123456" | |
| 738 | - name: "example-channel" | |
| 739 | - - id: "678901" | |
| 740 | - name: "example-channel-2" | |
| 741 | -``` | |
| 742 | - | |
| 743 | -config.json | |
| 744 | - | |
| 745 | -```json | |
| 746 | -{ | |
| 747 | - "contextProviders": [ | |
| 748 | - { | |
| 749 | - "name": "discord", | |
| 750 | - "params": { | |
| 751 | - "discordKey": "bot token", | |
| 752 | - "guildId": "1234567890", | |
| 753 | - "channels": [ | |
| 754 | - { "id": "123456", "name": "example-channel" }, | |
| 755 | - { "id": "678901", "name": "example-channel-2" } | |
| 756 | - ] | |
| 757 | - } | |
| 758 | - } | |
| 759 | - ] | |
| 760 | -} | |
| 761 | -``` | |
| 762 | - | |
| 763 | -Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels. | |
| 764 | - | |
| 765 | -### @HTTP Context Provider – Reference Data from an HTTP Request | |
| 766 | - | |
| 767 | -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. | |
| 768 | - | |
| 769 | -- YAML | |
| 770 | -- JSON | |
| 771 | - | |
| 772 | -config.yaml | |
| 773 | - | |
| 774 | -``` | |
| 775 | -context: | |
| 776 | - - provider: http | |
| 777 | - params: | |
| 778 | - url: "https://api.example.com/v1/users" | |
| 779 | -``` | |
| 780 | - | |
| 781 | -config.json | |
| 782 | - | |
| 783 | -```json | |
| 784 | -{ | |
| 785 | - "contextProviders": [ | |
| 786 | - { "name": "http", "params": { "url": "https://api.example.com/v1/users" } } | |
| 787 | - ] | |
| 788 | -} | |
| 789 | -``` | |
| 790 | - | |
| 791 | -The receiving URL should expect to receive the following parameters: | |
| 792 | - | |
| 793 | -POST parameters | |
| 794 | - | |
| 795 | -```json | |
| 796 | -{ query: string, fullInput: string} | |
| 797 | -``` | |
| 798 | - | |
| 799 | -The response 200 OK should be a JSON object with the following structure: | |
| 800 | - | |
| 801 | -Response | |
| 802 | - | |
| 803 | -``` | |
| 804 | -[ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""} | |
| 805 | -``` | |
| 806 | - | |
| 807 | -### @Commits Context Provider – Reference Git Commit Metadata and Diffs | |
| 808 | - | |
| 809 | -Reference specific git commit metadata and diff or all of the recent commits. | |
| 810 | - | |
| 811 | -- YAML | |
| 812 | -- JSON | |
| 813 | - | |
| 814 | -config.yaml | |
| 815 | - | |
| 816 | -``` | |
| 817 | -context: | |
| 818 | - - provider: commit | |
| 819 | - params: | |
| 820 | - Depth: 50 | |
| 821 | - LastXCommitsDepth: 10 | |
| 822 | -``` | |
| 823 | - | |
| 824 | -config.json | |
| 825 | - | |
| 826 | -```json | |
| 827 | -{ | |
| 828 | - "contextProviders": [ | |
| 829 | - { "name": "commit", "params": { "Depth": 50, "LastXCommitsDepth": 10 } } | |
| 830 | - ] | |
| 831 | -} | |
| 832 | -``` | |
| 833 | - | |
| 834 | -The depth is how many commits will be loaded into the submenu, defaults to 50. The LastXCommitsDepth is how many recent commits will be included, defaults to 10. | |
| 835 | - | |
| 836 | -### @Greptile Context Provider – Query Greptile Index of Repo/Branch | |
| 837 | - | |
| 838 | -Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. | |
| 839 | - | |
| 840 | -- YAML | |
| 841 | -- JSON | |
| 842 | - | |
| 843 | -config.yaml | |
| 844 | - | |
| 845 | -``` | |
| 846 | -context: | |
| 847 | - - provider: greptile | |
| 848 | - params: | |
| 849 | - greptileToken: "..." | |
| 850 | - githubToken: "..." | |
| 851 | -``` | |
| 852 | - | |
| 853 | -config.json | |
| 854 | - | |
| 855 | -```json | |
| 856 | -{ | |
| 857 | - "contextProviders": [ | |
| 858 | - { | |
| 859 | - "name": "greptile", | |
| 860 | - "params": { "GreptileToken": "...", "GithubToken": "..." } | |
| 861 | - } | |
| 862 | - ] | |
| 863 | -} | |
| 864 | -``` | |
| 865 | - | |
| 866 | 440 | ### How to Request a New Context Provider in Continue |
| 867 | 441 | |
| 868 | 442 | Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider. |
modified docs/customize/deep-dives/autocomplete.mdx +7 −1
| @@ -5,6 +5,12 @@ | ||
| 5 | 5 | sidebarTitle: Autocomplete |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | +import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx"; | |
| 9 | + | |
| 10 | +## Model Recommendations for Autocomplete | |
| 11 | + | |
| 12 | +<ModelRecommendations role="autocomplete" /> | |
| 13 | + | |
| 8 | 14 | ## How to Set Up Autocomplete in Continue with Codestral (Recommended) |
| 9 | 15 | |
| 10 | 16 | If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your config: |
| @@ -123,7 +129,7 @@ | ||
| 123 | 129 | ### Customize Autocomplete User Settings in the Continue Extension |
| 124 | 130 | |
| 125 | 131 | {/* - `Use autocomplete cache`: If on, caches completions */} |
| 126 | -The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md): | |
| 132 | +The following settings can be configured for autocompletion in the IDE extension User Settings Page: | |
| 127 | 133 | |
| 128 | 134 | - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` |
| 129 | 135 | - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" |
modified docs/customize/deep-dives/configuration.mdx +9 −9
| @@ -1,26 +1,26 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "How to Configure Continue Assistants" | |
| 3 | -description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files | |
| 2 | +title: "How to Configure Continue Agents" | |
| 3 | +description: Learn how to access and manage Continue agent configurations through Hub or local YAML files | |
| 4 | 4 | keywords: [config, settings, customize] |
| 5 | -sidebarTitle: "Assistant Configuration" | |
| 5 | +sidebarTitle: "Agent Configuration" | |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | -You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. | |
| 8 | +You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (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. | |
| 9 | 9 | |
| 10 | - | |
| 10 | + | |
| 11 | 11 | |
| 12 | -## How to Manage Hub Assistants | |
| 12 | +## How to Manage Hub Agents | |
| 13 | 13 | |
| 14 | -Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md) | |
| 14 | +Hub Agents can be managed in [the Hub](https://hub.continue.dev). See [Editing an Agent](../../hub/agents/edit-an-agent.md) | |
| 15 | 15 | |
| 16 | -## How to Configure Local Assistants with YAML | |
| 16 | +## How to Configure Local Agents with YAML | |
| 17 | 17 | |
| 18 | 18 | Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: |
| 19 | 19 | |
| 20 | 20 | - `~/.continue/config.yaml` (MacOS / Linux) |
| 21 | 21 | - `%USERPROFILE%\.continue\config.yaml` (Windows) |
| 22 | 22 | |
| 23 | -To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`. | |
| 23 | +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`. | |
| 24 | 24 | |
| 25 | 25 |  |
| 26 | 26 |
added docs/customize/deep-dives/custom-providers.mdx +433 −0
| @@ -0,0 +1,433 @@ | ||
| 1 | +--- | |
| 2 | +title: "Context Providers" | |
| 3 | +description: "Context Providers allow you to type '@' and see a dropdown of content that can all be provided to the model as context." | |
| 4 | +--- | |
| 5 | + | |
| 6 | +Context Providers allow you to type '@' and see a dropdown of content that can all be provided to the model as context. | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | +## Built-in Context Providers | |
| 11 | + | |
| 12 | +You can add any built-in context-providers in your config file as shown below: | |
| 13 | + | |
| 14 | +### `@File` | |
| 15 | + | |
| 16 | +Reference any file in your current workspace. | |
| 17 | + | |
| 18 | +<Tabs> | |
| 19 | + <Tab title="YAML"> | |
| 20 | + ```yaml config.yaml | |
| 21 | + context: | |
| 22 | + - provider: file | |
| 23 | + ``` | |
| 24 | + </Tab> | |
| 25 | + <Tab title="JSON (Deprecated)"> | |
| 26 | + ```json config.json | |
| 27 | + { | |
| 28 | + "contextProviders": [ | |
| 29 | + { | |
| 30 | + "name": "file" | |
| 31 | + } | |
| 32 | + ] | |
| 33 | + } | |
| 34 | + ``` | |
| 35 | + </Tab> | |
| 36 | +</Tabs> | |
| 37 | + | |
| 38 | +### `@Code` | |
| 39 | + | |
| 40 | +Reference specific functions or classes from throughout your project. | |
| 41 | + | |
| 42 | +<Tabs> | |
| 43 | + <Tab title="YAML"> | |
| 44 | + ```yaml config.yaml | |
| 45 | + context: | |
| 46 | + - provider: code | |
| 47 | + ``` | |
| 48 | + </Tab> | |
| 49 | + <Tab title="JSON (Deprecated)"> | |
| 50 | + ```json config.json | |
| 51 | + { | |
| 52 | + "contextProviders": [ | |
| 53 | + { | |
| 54 | + "name": "code" | |
| 55 | + } | |
| 56 | + ] | |
| 57 | + } | |
| 58 | + ``` | |
| 59 | + </Tab> | |
| 60 | +</Tabs> | |
| 61 | + | |
| 62 | +### `@Git Diff` | |
| 63 | + | |
| 64 | +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. | |
| 65 | + | |
| 66 | +<Tabs> | |
| 67 | + <Tab title="YAML"> | |
| 68 | + ```yaml config.yaml | |
| 69 | + context: | |
| 70 | + - provider: diff | |
| 71 | + ``` | |
| 72 | + </Tab> | |
| 73 | + <Tab title="JSON (Deprecated)"> | |
| 74 | + ```json config.json | |
| 75 | + { | |
| 76 | + "contextProviders": [ | |
| 77 | + { | |
| 78 | + "name": "diff" | |
| 79 | + } | |
| 80 | + ] | |
| 81 | + } | |
| 82 | + ``` | |
| 83 | + </Tab> | |
| 84 | +</Tabs> | |
| 85 | + | |
| 86 | +### `@Current File` | |
| 87 | + | |
| 88 | +Reference the currently open file. | |
| 89 | + | |
| 90 | +<Tabs> | |
| 91 | + <Tab title="YAML"> | |
| 92 | + ```yaml config.yaml | |
| 93 | + context: | |
| 94 | + - provider: currentFile | |
| 95 | + ``` | |
| 96 | + </Tab> | |
| 97 | + <Tab title="JSON (Deprecated)"> | |
| 98 | + ```json config.json | |
| 99 | + { | |
| 100 | + "contextProviders": [ | |
| 101 | + { | |
| 102 | + "name": "currentFile" | |
| 103 | + } | |
| 104 | + ] | |
| 105 | + } | |
| 106 | + ``` | |
| 107 | + </Tab> | |
| 108 | +</Tabs> | |
| 109 | + | |
| 110 | +### `@Terminal` | |
| 111 | + | |
| 112 | +Reference the last command you ran in your IDE's terminal and its output. | |
| 113 | + | |
| 114 | +<Tabs> | |
| 115 | + <Tab title="YAML"> | |
| 116 | + ```yaml config.yaml | |
| 117 | + context: | |
| 118 | + - provider: terminal | |
| 119 | + ``` | |
| 120 | + </Tab> | |
| 121 | + <Tab title="JSON (Deprecated)"> | |
| 122 | + ```json config.json | |
| 123 | + { | |
| 124 | + "contextProviders": [ | |
| 125 | + { | |
| 126 | + "name": "terminal" | |
| 127 | + } | |
| 128 | + ] | |
| 129 | + } | |
| 130 | + ``` | |
| 131 | + </Tab> | |
| 132 | +</Tabs> | |
| 133 | + | |
| 134 | +### `@Open` | |
| 135 | + | |
| 136 | +Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. | |
| 137 | + | |
| 138 | +<Tabs> | |
| 139 | + <Tab title="YAML"> | |
| 140 | + ```yaml config.yaml | |
| 141 | + context: | |
| 142 | + - provider: open | |
| 143 | + params: | |
| 144 | + onlyPinned: true | |
| 145 | + ``` | |
| 146 | + </Tab> | |
| 147 | + <Tab title="JSON (Deprecated)"> | |
| 148 | + ```json config.json | |
| 149 | + { | |
| 150 | + "contextProviders": [ | |
| 151 | + { | |
| 152 | + "name": "open", | |
| 153 | + "params": { | |
| 154 | + "onlyPinned": true | |
| 155 | + } | |
| 156 | + } | |
| 157 | + ] | |
| 158 | + } | |
| 159 | + ``` | |
| 160 | + </Tab> | |
| 161 | +</Tabs> | |
| 162 | + | |
| 163 | +### `@Clipboard` | |
| 164 | + | |
| 165 | +Reference recent clipboard items | |
| 166 | + | |
| 167 | +<Tabs> | |
| 168 | + <Tab title="YAML"> | |
| 169 | + ```yaml config.yaml | |
| 170 | + context: | |
| 171 | + - provider: clipboard | |
| 172 | + ``` | |
| 173 | + </Tab> | |
| 174 | + <Tab title="JSON (Deprecated)"> | |
| 175 | + ```json config.json | |
| 176 | + { | |
| 177 | + "contextProviders": [ | |
| 178 | + { | |
| 179 | + "name": "clipboard" | |
| 180 | + } | |
| 181 | + ] | |
| 182 | + } | |
| 183 | + ``` | |
| 184 | + </Tab> | |
| 185 | +</Tabs> | |
| 186 | + | |
| 187 | +### `@Tree` | |
| 188 | + | |
| 189 | +Reference the structure of your current workspace. | |
| 190 | + | |
| 191 | +<Tabs> | |
| 192 | + <Tab title="YAML"> | |
| 193 | + ```yaml config.yaml | |
| 194 | + context: | |
| 195 | + - provider: tree | |
| 196 | + ``` | |
| 197 | + </Tab> | |
| 198 | + <Tab title="JSON (Deprecated)"> | |
| 199 | + ```json config.json | |
| 200 | + { | |
| 201 | + "contextProviders": [ | |
| 202 | + { | |
| 203 | + "name": "tree" | |
| 204 | + } | |
| 205 | + ] | |
| 206 | + } | |
| 207 | + ``` | |
| 208 | + </Tab> | |
| 209 | +</Tabs> | |
| 210 | + | |
| 211 | +### `@Problems` | |
| 212 | + | |
| 213 | +Get Problems from the current file. | |
| 214 | + | |
| 215 | +<Tabs> | |
| 216 | + <Tab title="YAML"> | |
| 217 | + ```yaml config.yaml | |
| 218 | + context: | |
| 219 | + - provider: problems | |
| 220 | + ``` | |
| 221 | + </Tab> | |
| 222 | + <Tab title="JSON (Deprecated)"> | |
| 223 | + ```json config.json | |
| 224 | + { | |
| 225 | + "contextProviders": [ | |
| 226 | + { | |
| 227 | + "name": "problems" | |
| 228 | + } | |
| 229 | + ] | |
| 230 | + } | |
| 231 | + ``` | |
| 232 | + </Tab> | |
| 233 | +</Tabs> | |
| 234 | + | |
| 235 | +### `@Debugger` | |
| 236 | + | |
| 237 | +Reference the contents of the local variables in the debugger. Currently only available in VS Code. | |
| 238 | + | |
| 239 | +<Tabs> | |
| 240 | + <Tab title="YAML"> | |
| 241 | + ```yaml config.yaml | |
| 242 | + context: | |
| 243 | + - provider: debugger | |
| 244 | + params: | |
| 245 | + stackDepth: 3 | |
| 246 | + ``` | |
| 247 | + </Tab> | |
| 248 | + <Tab title="JSON (Deprecated)"> | |
| 249 | + ```json config.json | |
| 250 | + { | |
| 251 | + "contextProviders": [ | |
| 252 | + { | |
| 253 | + "name": "debugger", | |
| 254 | + "params": { | |
| 255 | + "stackDepth": 3 | |
| 256 | + } | |
| 257 | + } | |
| 258 | + ] | |
| 259 | + } | |
| 260 | + ``` | |
| 261 | + </Tab> | |
| 262 | +</Tabs> | |
| 263 | + | |
| 264 | +Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. | |
| 265 | + | |
| 266 | +### `@Repository Map` | |
| 267 | + | |
| 268 | +Reference the outline of your codebase. By default, signatures are included along with file in the repo map. | |
| 269 | + | |
| 270 | +`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. | |
| 271 | + | |
| 272 | +<Tabs> | |
| 273 | + <Tab title="YAML"> | |
| 274 | + ```yaml config.yaml | |
| 275 | + context: | |
| 276 | + - provider: repo-map | |
| 277 | + params: | |
| 278 | + includeSignatures: false # default true | |
| 279 | + ``` | |
| 280 | + </Tab> | |
| 281 | + <Tab title="JSON (Deprecated)"> | |
| 282 | + ```json config.json | |
| 283 | + { | |
| 284 | + "contextProviders": [ | |
| 285 | + { | |
| 286 | + "name": "repo-map", | |
| 287 | + "params": { | |
| 288 | + "includeSignatures": false // default true | |
| 289 | + } | |
| 290 | + } | |
| 291 | + ] | |
| 292 | + } | |
| 293 | + ``` | |
| 294 | + </Tab> | |
| 295 | +</Tabs> | |
| 296 | + | |
| 297 | +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. | |
| 298 | + | |
| 299 | +In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. | |
| 300 | + | |
| 301 | +This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). | |
| 302 | + | |
| 303 | +### `@Operating System` | |
| 304 | + | |
| 305 | +Reference the architecture and platform of your current operating system. | |
| 306 | + | |
| 307 | +<Tabs> | |
| 308 | + <Tab title="YAML"> | |
| 309 | + ```yaml config.yaml | |
| 310 | + context: | |
| 311 | + - provider: os | |
| 312 | + ``` | |
| 313 | + </Tab> | |
| 314 | + <Tab title="JSON (Deprecated)"> | |
| 315 | + ```json config.json | |
| 316 | + { | |
| 317 | + "contextProviders": [ | |
| 318 | + { | |
| 319 | + "name": "os" | |
| 320 | + } | |
| 321 | + ] | |
| 322 | + } | |
| 323 | + ``` | |
| 324 | + </Tab> | |
| 325 | +</Tabs> | |
| 326 | + | |
| 327 | +### `@HTTP` | |
| 328 | + | |
| 329 | +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. | |
| 330 | + | |
| 331 | +<Tabs> | |
| 332 | + <Tab title="YAML"> | |
| 333 | + ```yaml config.yaml | |
| 334 | + context: | |
| 335 | + - provider: http | |
| 336 | + params: | |
| 337 | + url: "https://api.example.com/v1/users" | |
| 338 | + headers: | |
| 339 | + - Authorization: "Bearer <token>" | |
| 340 | + ``` | |
| 341 | + </Tab> | |
| 342 | + <Tab title="JSON (Deprecated)"> | |
| 343 | + ```json config.json | |
| 344 | + { | |
| 345 | + "contextProviders": [ | |
| 346 | + { | |
| 347 | + "name": "http", | |
| 348 | + "params": { | |
| 349 | + "url": "https://api.example.com/v1/users" | |
| 350 | + } | |
| 351 | + } | |
| 352 | + ] | |
| 353 | + } | |
| 354 | + ``` | |
| 355 | + </Tab> | |
| 356 | +</Tabs> | |
| 357 | + | |
| 358 | +The receiving URL should expect to receive the following parameters: | |
| 359 | + | |
| 360 | +POST parameters | |
| 361 | + | |
| 362 | +```json | |
| 363 | +{ query: string, fullInput: string} | |
| 364 | +``` | |
| 365 | + | |
| 366 | +The response 200 OK should be a JSON object with the following structure: | |
| 367 | + | |
| 368 | +Response | |
| 369 | + | |
| 370 | +``` | |
| 371 | +[ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""} | |
| 372 | +``` | |
| 373 | + | |
| 374 | +### Model Context Protocol | |
| 375 | + | |
| 376 | +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: | |
| 377 | + | |
| 378 | +<Tabs> | |
| 379 | + <Tab title="YAML"> | |
| 380 | + ```yaml config.yaml | |
| 381 | + mcpServers: | |
| 382 | + - name: My MCP Server | |
| 383 | + command: uvx | |
| 384 | + args: | |
| 385 | + - mcp-server-sqlite | |
| 386 | + - --db-path | |
| 387 | + - /Users/NAME/test.db | |
| 388 | + ``` | |
| 389 | + </Tab> | |
| 390 | + <Tab title="JSON (Deprecated)"> | |
| 391 | + ```json config.json | |
| 392 | + { | |
| 393 | + "experimental": { | |
| 394 | + "modelContextProtocolServers": [ | |
| 395 | + { | |
| 396 | + "transport": { | |
| 397 | + "type": "stdio", | |
| 398 | + "command": "uvx", | |
| 399 | + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] | |
| 400 | + } | |
| 401 | + } | |
| 402 | + ] | |
| 403 | + } | |
| 404 | + } | |
| 405 | + ``` | |
| 406 | + </Tab> | |
| 407 | +</Tabs> | |
| 408 | + | |
| 409 | +You'll then be able to type "@" and see "MCP" in the context providers dropdown. | |
| 410 | + | |
| 411 | +## Deprecated Context Providers | |
| 412 | + | |
| 413 | +<Note> | |
| 414 | + To provide conext beyond the built-in context providers, we now recommend | |
| 415 | + using [MCP Servers](/customization/mcp-tools) | |
| 416 | +</Note> | |
| 417 | + | |
| 418 | +View the [deprecated context providers](/reference/deprecated-context-providers) for documentation on: | |
| 419 | + | |
| 420 | +- [`@Codebase`](/reference/deprecated-codebase) - Use the [codebase awareness guide](/guides/codebase-documentation-awareness) instead | |
| 421 | +- [`@Folder`](/reference/deprecated-codebase) - Use the [codebase awareness guide](/guides/codebase-documentation-awareness) instead | |
| 422 | +- [`@Docs`](/reference/deprecated-docs) - Use the [documentation awareness guide](/guides/codebase-documentation-awareness) instead | |
| 423 | +- `@Greptile` - Query Greptile index | |
| 424 | +- `@Commits` - Reference git commits | |
| 425 | +- `@Discord` - Reference Discord messages | |
| 426 | +- `@Jira` - Reference Jira issues | |
| 427 | +- `@Gitlab Merge Request` - Reference GitLab MRs | |
| 428 | +- `@Google` - Google search results | |
| 429 | +- `@Database` - Database schemas | |
| 430 | +- `@Issue` - GitHub issues | |
| 431 | +- `@Url` - URL content | |
| 432 | +- `@Search` - Codebase search | |
| 433 | +- `@Web` - Web search results |
modified docs/customize/deep-dives/development-data.mdx +1 −3
| @@ -13,8 +13,6 @@ | ||
| 13 | 13 | |
| 14 | 14 | You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories. |
| 15 | 15 | |
| 16 | -For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). | |
| 17 | - | |
| 18 | -See more details about adding `data` blocks to your configuration files in the [YAML specification](/reference#data) | |
| 16 | +Data destinations should be configured directly in the `data` section of your `config.yaml` file. See more details about adding `data` configuration in the [YAML specification](/reference#data). | |
| 19 | 17 | |
| 20 | 18 | When sending development data to your own HTTP endpoint, it will receive an event JSON blob at the given `schema` version. You can view event names, schema versions, and fields [here in the source code](https://github.com/continuedev/continue/tree/main/packages/config-yaml/src/schemas/data). |
modified docs/customize/deep-dives/mcp.mdx +2 −2
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | Currently custom tools can be configured using the Model Context |
| 20 | 20 | Protocol standard to unify prompts, context, and tool use. |
| 21 | 21 | |
| 22 | -MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can | |
| 22 | +MCP Servers can be added to hub Agents using `mcpServers` blocks. You can | |
| 23 | 23 | explore available MCP server blocks |
| 24 | 24 | [here](https://hub.continue.dev/explore/mcp). |
| 25 | 25 | |
| @@ -27,7 +27,7 @@ | ||
| 27 | 27 | |
| 28 | 28 | ## Quick Start: How to Set Up Your First MCP Server |
| 29 | 29 | |
| 30 | -Below is a quick example of setting up a new MCP server for use in your assistant: | |
| 30 | +Below is a quick example of setting up a new MCP server for use in your agent: | |
| 31 | 31 | |
| 32 | 32 | 1. Create a folder called `.continue/mcpServers` at the top level of your workspace |
| 33 | 33 | 2. Add a file called `playwright-mcp.yaml` to this folder. |
modified docs/customize/deep-dives/model-capabilities.mdx +2 −1
| @@ -231,12 +231,13 @@ | ||
| 231 | 231 | | Model | Tool Use | Image Input | Context Window | |
| 232 | 232 | | :------------- | -------- | ----------- | -------------- | |
| 233 | 233 | | Qwen 3 Coder | Yes | No | 32k | |
| 234 | +| Qwen 2.5 VL | No | Yes | 128k | | |
| 234 | 235 | | Devstral Small | Yes | No | 32k | |
| 235 | 236 | | Llama 3.1 | Yes | No | 128k | |
| 236 | 237 | | Llama 3 | Yes | No | 8k | |
| 237 | 238 | | Mistral | Yes | No | 32k | |
| 238 | 239 | | Codestral | Yes | No | 32k | |
| 239 | -| Gemma 3 4B | Yes | No | 8k | | |
| 240 | +| Gemma 3 4B | Yes | Yes | 128k | | |
| 240 | 241 | |
| 241 | 242 | ### Notes |
| 242 | 243 |
modified docs/customize/deep-dives/rules.mdx +2 −2
| @@ -42,7 +42,7 @@ | ||
| 42 | 42 | |
| 43 | 43 | ## How to Create Rules Blocks |
| 44 | 44 | |
| 45 | -Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules. | |
| 45 | +Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. | |
| 46 | 46 | |
| 47 | 47 |  |
| 48 | 48 | |
| @@ -53,7 +53,7 @@ | ||
| 53 | 53 | |
| 54 | 54 | </Info> |
| 55 | 55 | |
| 56 | -Rules can also be added to an Assistant on the Continue Hub. | |
| 56 | +Rules can also be added to an Agent on the Continue Hub. | |
| 57 | 57 | |
| 58 | 58 | Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. |
| 59 | 59 |
modified docs/customize/deep-dives/rules.mdx.backup +3 −3
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | |
| 40 | 40 | ## Creating `rules` blocks |
| 41 | 41 | |
| 42 | -Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules. | |
| 42 | +Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. | |
| 43 | 43 | |
| 44 | 44 |  |
| 45 | 45 | |
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | 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. |
| 50 | 50 | </Info> |
| 51 | 51 | |
| 52 | -Rules can also be added to an Assistant on the Continue Hub. | |
| 52 | +Rules can also be added to an Agent on the Continue Hub. | |
| 53 | 53 | |
| 54 | 54 | Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. |
| 55 | 55 | |
| @@ -133,7 +133,7 @@ | ||
| 133 | 133 | Always give concise responses |
| 134 | 134 | ``` |
| 135 | 135 | |
| 136 | -This is also done when selecting "Add Rule" in the Assistant settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`. | |
| 136 | +This is also done when selecting "Add Rule" in the Agent settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`. | |
| 137 | 137 | |
| 138 | 138 | ### Examples |
| 139 | 139 |
modified docs/customize/deep-dives/slash-commands.mdx +3 −3
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown. |
| 11 | 11 |  |
| 12 | 12 | |
| 13 | -Slash commands can be combined with additional instructions, including [context providers](../custom-providers) or highlighted code. | |
| 13 | +Slash commands can be combined with additional instructions, including highlighted code. | |
| 14 | 14 | |
| 15 | 15 | <Note> |
| 16 | 16 | **Recommended approach**: Use prompt files to create slash commands instead of |
| @@ -21,9 +21,9 @@ | ||
| 21 | 21 | |
| 22 | 22 | ## Ways to Create Slash Commands in Continue |
| 23 | 23 | |
| 24 | -### Assistant Prompt Blocks | |
| 24 | +### Agent Prompt Blocks | |
| 25 | 25 | |
| 26 | -The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works). | |
| 26 | +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). | |
| 27 | 27 | |
| 28 | 28 | ### Prompt Files |
| 29 | 29 |
deleted docs/customize/deep-dives/vscode-actions.mdx +0 −44
| @@ -1,44 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Use Continue's VS Code Actions and Quick Features" | |
| 3 | -keywords: [vscode, quick actions, quick, actions] | |
| 4 | -description: "Learn about Continue's VS Code-specific actions including quick actions buttons, right-click context menu options, debug shortcuts, and quick fixes for errors in your code" | |
| 5 | -sidebarTitle: "VS Code Actions" | |
| 6 | ---- | |
| 7 | - | |
| 8 | -<Info>Currently all of these are only available in VS Code</Info> | |
| 9 | - | |
| 10 | -To make common use cases even more accessible, we provide a handful of other ways to invoke actions in VS Code. | |
| 11 | - | |
| 12 | -## How to Use Quick Actions | |
| 13 | - | |
| 14 | -Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions. | |
| 15 | - | |
| 16 | - | |
| 17 | - | |
| 18 | -By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings. | |
| 19 | - | |
| 20 | -## How to Use Right Click Actions | |
| 21 | - | |
| 22 | -Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu. | |
| 23 | - | |
| 24 | -The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit. | |
| 25 | - | |
| 26 | -Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../features/edit/how-it-works). | |
| 27 | - | |
| 28 | - | |
| 29 | - | |
| 30 | -## How to Use the Debug Action Shortcut | |
| 31 | - | |
| 32 | -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>R</kbd> to instantly copy the contents of the most recent terminal output into the chat sidebar and get debugging advice. There is no additional, non-visible information sent to the language model. | |
| 33 | - | |
| 34 | -``` | |
| 35 | -I got the following error, can you please help explain how to fix it? | |
| 36 | - | |
| 37 | -[ERROR_MESSAGE] | |
| 38 | -``` | |
| 39 | - | |
| 40 | -## How to Use Quick Fixes for Code Errors | |
| 41 | - | |
| 42 | -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> again and Continue will attempt to help solve the problem. | |
| 43 | - | |
| 44 | -Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”. |
added docs/customize/model-providers/assets/tetrate-get-api-key.png +0 −0
Binary content is not shown. View the file.
added docs/customize/model-providers/assets/tetrate-remix.png +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
added docs/customize/model-providers/assets/tetrate-sign-in.png +0 −0
Binary content is not shown. View the file.
modified docs/customize/model-providers/more/deepinfra.mdx +19 −9
| @@ -3,27 +3,35 @@ | ||
| 3 | 3 | description: "Configure DeepInfra with Continue to access low-cost inference for open-source models like Mixtral-8x7B-Instruct, including API setup instructions" |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -[DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here: | |
| 6 | +<Tip> | |
| 7 | + **Discover Deep Infra models [here](https://hub.continue.dev/deepinfra)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + Get an API key from the [Deep Infra](https://deepinfra.com/) | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Configuration | |
| 7 | 15 | |
| 8 | 16 | <Tabs> |
| 9 | 17 | <Tab title="YAML"> |
| 10 | 18 | ```yaml title="config.yaml" |
| 11 | 19 | models: |
| 12 | - - name: DeepInfra | |
| 20 | + - name: <MODEL_NAME> | |
| 13 | 21 | provider: deepinfra |
| 14 | - model: mistralai/Mixtral-8x7B-Instruct-v0.1 | |
| 15 | - apiKey: <YOUR_DEEP_INFRA_API_KEY> | |
| 22 | + model: <MODEL_ID> | |
| 23 | + apiKey: <YOUR_DEEPINFRA_API_KEY> | |
| 16 | 24 | ``` |
| 17 | 25 | </Tab> |
| 18 | - <Tab title="JSON"> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 19 | 27 | ```json title="config.json" |
| 20 | 28 | { |
| 21 | 29 | "models": [ |
| 22 | 30 | { |
| 31 | + "title": "<MODEL_NAME>", | |
| 23 | 32 | "provider": "deepinfra", |
| 24 | - "title": "DeepInfra", | |
| 25 | - "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", | |
| 26 | - "apiKey": "<YOUR_DEEP_INFRA_API_KEY>" | |
| 33 | + "model": "<MODEL_ID>", | |
| 34 | + "apiKey": "<YOUR_DEEPINFRA_API_KEY>" | |
| 27 | 35 | } |
| 28 | 36 | ] |
| 29 | 37 | } |
| @@ -31,4 +39,6 @@ | ||
| 31 | 39 | </Tab> |
| 32 | 40 | </Tabs> |
| 33 | 41 | |
| 34 | -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts) | |
| 42 | +<Info> | |
| 43 | + **Check out a more advanced configuration [here](https://hub.continue.dev/deepinfra/qwen-qwen2.5-coder-32b-instruct?view=config)** | |
| 44 | +</Info> | |
| No newline at the end of the file |
added docs/customize/model-providers/more/deepseek.mdx +40 −0
| @@ -0,0 +1,40 @@ | ||
| 1 | +--- | |
| 2 | +title: DeepSeek | |
| 3 | +slug: ../deepseek | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Tip> | |
| 7 | + **Discover DeepSeek models [here](https://hub.continue.dev/?q=DeepSeek)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + You can get an API key from the [DeepSeek Console](https://www.deepseek.com/). | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Confiugration | |
| 15 | + | |
| 16 | +<Tabs> | |
| 17 | + <Tab title="YAML"> | |
| 18 | + ```yaml title="config.yaml" | |
| 19 | + models: | |
| 20 | + - name: <MODEL_NAME> | |
| 21 | + provider: deepseek | |
| 22 | + model: <MODEL_ID> | |
| 23 | + apiKey: <YOUR_DEEPSEEK_API_KEY> | |
| 24 | + ``` | |
| 25 | + </Tab> | |
| 26 | + <Tab title="JSON"> | |
| 27 | + ```json title="config.json" | |
| 28 | + { | |
| 29 | + "models": [ | |
| 30 | + { | |
| 31 | + "title": "<MODEL_NAME>", | |
| 32 | + "provider": "deepseek", | |
| 33 | + "model": "<MODEL_ID>", | |
| 34 | + "apiKey": "<YOUR_DEEPSEEK_API_KEY>" | |
| 35 | + } | |
| 36 | + ] | |
| 37 | + } | |
| 38 | + ``` | |
| 39 | + </Tab> | |
| 40 | +</Tabs> | |
| No newline at the end of the file |
modified docs/customize/model-providers/more/groq.mdx +10 −18
| @@ -1,44 +1,36 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Groq with Continue" |
| 3 | -description: "Configure Groq with Continue to access their ultra-fast inference platform for open-source language models, including the entire Llama 3.1 and 3.3 family with industry-leading speeds" | |
| 4 | 3 | sidebarTitle: "Groq" |
| 5 | 4 | --- |
| 6 | 5 | |
| 7 | 6 | <Info> |
| 8 | - Check if your chosen model is still supported by referring to the [model | |
| 9 | - documentation](https://console.groq.com/docs/models). If a model has been | |
| 10 | - deprecated, you may encounter a 404 error when attempting to use it. | |
| 7 | + Get your API key from the [Groq Console](https://console.groq.com/docs/models) | |
| 11 | 8 | </Info> |
| 12 | 9 | |
| 13 | -Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. | |
| 14 | - | |
| 15 | -1. Obtain an API key [here](https://console.groq.com/keys) | |
| 16 | -2. Update your Continue config file like this: | |
| 10 | +## Configuration | |
| 17 | 11 | |
| 18 | 12 | <Tabs> |
| 19 | 13 | <Tab title="YAML"> |
| 20 | 14 | ```yaml title="config.yaml" |
| 21 | 15 | models: |
| 22 | - - name: Llama 3.3 70b Versatile | |
| 16 | + - name: <MODEL_NAME> | |
| 23 | 17 | provider: groq |
| 24 | - model: llama-3.3-70b-versatile | |
| 25 | - apiKey: <YOUR_GROQ_API_KEY> | |
| 26 | - roles: | |
| 27 | - - chat | |
| 18 | + model: <MODEL_ID> | |
| 19 | + apiKey: <YOUR_GROQ_API_KEY>" | |
| 28 | 20 | ``` |
| 29 | 21 | </Tab> |
| 30 | - <Tab title="JSON"> | |
| 22 | + <Tab title="JSON (Deprecated)"> | |
| 31 | 23 | ```json title="config.json" |
| 32 | 24 | { |
| 33 | 25 | "models": [ |
| 34 | 26 | { |
| 35 | - "title": "Llama 3.3 70b Versatile", | |
| 27 | + "title": "<MODEL_NAME>", | |
| 36 | 28 | "provider": "groq", |
| 37 | - "model": "llama-3.3-70b-versatile", | |
| 38 | - "apiKey": "<YOUR_GROQ_API_KEY>" | |
| 29 | + "model": "<MODEL_ID>", | |
| 30 | + "apiKey": "<YOUR_GROQ_API_KEY>"", | |
| 39 | 31 | } |
| 40 | 32 | ] |
| 41 | 33 | } |
| 42 | 34 | ``` |
| 43 | 35 | </Tab> |
| 44 | -</Tabs> | |
| 36 | +</Tabs> | |
| No newline at the end of the file |
modified docs/customize/model-providers/more/huggingfaceinferenceapi.mdx +32 −31
| @@ -1,36 +1,37 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "HuggingFace Inference Endpoints" | |
| 3 | -description: "Configure HuggingFace Inference Endpoints with Continue to deploy and access open-source language models on any cloud, including setup instructions for models like WizardCoder" | |
| 2 | +title: "Hugging Face" | |
| 4 | 3 | --- |
| 5 | 4 | |
| 6 | -Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this: | |
| 5 | +<Info> | |
| 6 | + Get started with [Hugging Face Inference Endpoints](https://endpoints.huggingface.co/) | |
| 7 | +</Info> | |
| 7 | 8 | |
| 8 | -<Tabs> | |
| 9 | - <Tab title="YAML"> | |
| 10 | - ```yaml title="config.yaml" | |
| 11 | - models: | |
| 12 | - - name: Hugging Face Inference API | |
| 13 | - provider: huggingface-inference-api | |
| 14 | - model: MODEL_NAME | |
| 15 | - apiKey: <YOUR_HF_TOKEN> | |
| 16 | - apiBase: <YOUR_HF_INFERENCE_API_ENDPOINT_URL> | |
| 17 | - ``` | |
| 18 | - </Tab> | |
| 19 | - <Tab title="JSON"> | |
| 20 | - ```json title="config.json" | |
| 21 | - { | |
| 22 | - "models": [ | |
| 23 | - { | |
| 24 | - "title": "Hugging Face Inference API", | |
| 25 | - "provider": "huggingface-inference-api", | |
| 26 | - "model": "MODEL_NAME", | |
| 27 | - "apiKey": "<YOUR_HF_TOKEN>", | |
| 28 | - "apiBase": "<YOUR_HF_INFERENCE_API_ENDPOINT_URL>" | |
| 29 | - } | |
| 30 | - ] | |
| 31 | - } | |
| 32 | - ``` | |
| 33 | - </Tab> | |
| 34 | -</Tabs> | |
| 9 | +## Configuration | |
| 35 | 10 | |
| 36 | -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/HuggingFaceInferenceAPI.ts) | |
| 11 | +<Tabs> | |
| 12 | + <Tab title="YAML"> | |
| 13 | + ```yaml title="config.yaml" | |
| 14 | + models: | |
| 15 | + - name: <MODEL_NAME> | |
| 16 | + provider: huggingface-inference-api | |
| 17 | + model: <MODEL_ID> | |
| 18 | + apiKey: <YOUR_HF_TOKEN> | |
| 19 | + apiBase: <YOUR_HF_INFERENCE_API_ENDPOINT_URL> | |
| 20 | + ``` | |
| 21 | + </Tab> | |
| 22 | + <Tab title="JSON (Deprecated)"> | |
| 23 | + ```json title="config.json" | |
| 24 | + { | |
| 25 | + "models": [ | |
| 26 | + { | |
| 27 | + "title": "<MODEL_NAME>", | |
| 28 | + "provider": "huggingface-inference-api", | |
| 29 | + "model": "<MODEL_ID>", | |
| 30 | + "apiKey": "<YOUR_HF_TOKEN>", | |
| 31 | + "apiBase": "<YOUR_HF_INFERENCE_API_ENDPOINT_URL>" | |
| 32 | + } | |
| 33 | + ] | |
| 34 | + } | |
| 35 | + ``` | |
| 36 | + </Tab> | |
| 37 | +</Tabs> | |
| No newline at the end of the file |
added docs/customize/model-providers/more/lemonade.mdx +81 −0
| @@ -0,0 +1,81 @@ | ||
| 1 | +--- | |
| 2 | +title: "Lemonade Server" | |
| 3 | +description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Info> | |
| 7 | + Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration | |
| 8 | +</Info> | |
| 9 | + | |
| 10 | +## Overview | |
| 11 | + | |
| 12 | +Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms. | |
| 13 | + | |
| 14 | +## Installation | |
| 15 | + | |
| 16 | +Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/). | |
| 17 | + | |
| 18 | +## Configuration | |
| 19 | + | |
| 20 | +Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration. | |
| 21 | + | |
| 22 | +### Option 1: Using the Continue UI (Recommended) | |
| 23 | + | |
| 24 | +1. Click on the model selector dropdown in Continue | |
| 25 | +2. Select "Add Model" | |
| 26 | +3. Choose "Lemonade Server" from the provider list | |
| 27 | +4. Continue will automatically configure the connection | |
| 28 | + | |
| 29 | +### Option 2: Manual Configuration | |
| 30 | + | |
| 31 | +If you need custom settings, you can manually configure Lemonade: | |
| 32 | + | |
| 33 | +<Tabs> | |
| 34 | + <Tab title="YAML"> | |
| 35 | + ```yaml title="config.yaml" | |
| 36 | + models: | |
| 37 | + - name: Lemonade | |
| 38 | + provider: lemonade | |
| 39 | + model: <MODEL_NAME> | |
| 40 | + apiBase: http://localhost:8000/api/v1/ | |
| 41 | + ``` | |
| 42 | + </Tab> | |
| 43 | + <Tab title="JSON (Deprecated)"> | |
| 44 | + ```json title="config.json" | |
| 45 | + { | |
| 46 | + "models": [ | |
| 47 | + { | |
| 48 | + "title": "Lemonade", | |
| 49 | + "provider": "lemonade", | |
| 50 | + "model": "<MODEL_NAME>", | |
| 51 | + "apiBase": "http://localhost:8000/api/v1/" | |
| 52 | + } | |
| 53 | + ] | |
| 54 | + } | |
| 55 | + ``` | |
| 56 | + </Tab> | |
| 57 | +</Tabs> | |
| 58 | + | |
| 59 | +## Getting Started | |
| 60 | + | |
| 61 | +1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/) | |
| 62 | +2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default) | |
| 63 | +3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue | |
| 64 | +4. **Load a model**: Choose your preferred model through the interface | |
| 65 | + | |
| 66 | +## Hardware Support | |
| 67 | + | |
| 68 | +Lemonade Server automatically detects and optimizes for available hardware: | |
| 69 | +- **NPU**: Neural Processing Unit acceleration for efficient inference | |
| 70 | +- **GPU**: Full GPU acceleration support | |
| 71 | +- **CPU**: Optimized CPU fallback when accelerators are unavailable | |
| 72 | + | |
| 73 | +## Key Features | |
| 74 | + | |
| 75 | +- OpenAI-compatible API for seamless integration | |
| 76 | +- Support for popular model formats | |
| 77 | +- Automatic hardware detection and optimization | |
| 78 | +- Integration with Continue, Open WebUI, Gaia, and AnythingLLM | |
| 79 | +- Active open-source community | |
| 80 | + | |
| 81 | +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts) | |
| No newline at the end of the file |
modified docs/customize/model-providers/more/llamacpp.mdx +28 −33
| @@ -1,40 +1,35 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Llama.cpp" |
| 3 | -description: "Configure Llama.cpp with Continue to run local language models using high-performance C++ inference, including setup instructions for the server and client configuration" | |
| 4 | 3 | --- |
| 5 | 4 | |
| 6 | -Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0: | |
| 5 | +<Info> | |
| 6 | + Get started with [Llama.cpp](https://github.com/ggml-org/llama.cpp?tab=readme-ov-file#quick-start) | |
| 7 | +</Info> | |
| 7 | 8 | |
| 8 | -```bash | |
| 9 | -.\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\meta\llama\codellama-7b-instruct.Q8_0.gguf | |
| 10 | -``` | |
| 11 | - | |
| 12 | -After it's up and running, change `~/.continue/config.json` to look like this: | |
| 9 | +## Configuration | |
| 13 | 10 | |
| 14 | 11 | <Tabs> |
| 15 | - <Tab title="YAML"> | |
| 16 | - ```yaml title="config.yaml" | |
| 17 | - models: | |
| 18 | - - name: Llama CPP | |
| 19 | - provider: llama.cpp | |
| 20 | - model: MODEL_NAME | |
| 21 | - apiBase: http://localhost:8080 | |
| 22 | - ``` | |
| 23 | - </Tab> | |
| 24 | - <Tab title="JSON"> | |
| 25 | - ```json title="config.json" | |
| 26 | - { | |
| 27 | - "models": [ | |
| 28 | - { | |
| 29 | - "title": "Llama CPP", | |
| 30 | - "provider": "llama.cpp", | |
| 31 | - "model": "MODEL_NAME", | |
| 32 | - "apiBase": "http://localhost:8080" | |
| 33 | - } | |
| 34 | - ] | |
| 35 | - } | |
| 36 | - ``` | |
| 37 | - </Tab> | |
| 38 | -</Tabs> | |
| 39 | - | |
| 40 | -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LlamaCpp.ts) | |
| 12 | + <Tab title="YAML"> | |
| 13 | + ```yaml title="config.yaml" | |
| 14 | + models: | |
| 15 | + - name: <MODEL_NAME> | |
| 16 | + provider: llama.cpp | |
| 17 | + model: <MODEL_ID> | |
| 18 | + apiBase: http://localhost:8080 | |
| 19 | + ``` | |
| 20 | + </Tab> | |
| 21 | + <Tab title="JSON (Deprecated)"> | |
| 22 | + ```json title="config.json" | |
| 23 | + { | |
| 24 | + "models": [ | |
| 25 | + { | |
| 26 | + "title": "<MODEL_NAME>", | |
| 27 | + "provider": "llama.cpp", | |
| 28 | + "model": "<MODEL_ID>" | |
| 29 | + "apiBase": "http://localhost:8080" | |
| 30 | + } | |
| 31 | + ] | |
| 32 | + } | |
| 33 | + ``` | |
| 34 | + </Tab> | |
| 35 | +</Tabs> | |
| No newline at the end of the file |
modified docs/customize/model-providers/more/llamastack.mdx +26 −106
| @@ -1,114 +1,34 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Llama Stack" |
| 3 | -description: "Configure Llama Stack with Continue" | |
| 4 | 3 | keywords: [llama, stack, local, api, inference] |
| 5 | 4 | --- |
| 6 | 5 | |
| 7 | -[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides | |
| 8 | - | |
| 9 | -- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry. | |
| 10 | -- **Plugin architecture** to support the rich ecosystem of different API implementations in various environments, including local development, on-premises, cloud, and mobile. | |
| 11 | -- **Prepackaged verified distributions** which offer a one-stop solution for developers to get started quickly and reliably in any environment. | |
| 12 | -- **Multiple developer interfaces** like CLI and SDKs for Python, Typescript, iOS, and Android. | |
| 13 | -- **Standalone applications** as examples for how to build production-grade AI applications with Llama Stack. | |
| 14 | - | |
| 15 | -To try Llama Stack locally, run: | |
| 16 | - | |
| 17 | -```shell | |
| 18 | -curl -LsSf https://github.com/meta-llama/llama-stack/raw/main/install.sh | bash | |
| 19 | -``` | |
| 20 | - | |
| 21 | -Learn more about how to get started with llama stack in this [guide](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html) | |
| 22 | - | |
| 23 | -## Chat model | |
| 24 | - | |
| 25 | -We recommend configuring **Llama 4 Maverick** as your chat model. | |
| 26 | - | |
| 27 | -<Tabs> | |
| 28 | - <Tab title="YAML"> | |
| 29 | - ```yaml title="config.yaml" | |
| 30 | - models: | |
| 31 | - - name: Llama4 Maverick | |
| 32 | - provider: llamastack | |
| 33 | - model: meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8 | |
| 34 | - apiBase: http://<llama stack endpoint>/v1/openai/v1/ | |
| 35 | - ``` | |
| 36 | - </Tab> | |
| 37 | - <Tab title="JSON"> | |
| 38 | - ```json title="config.json" | |
| 39 | - { | |
| 40 | - "models": [ | |
| 41 | - { | |
| 42 | - "title": "Llama4 Maverick", | |
| 43 | - "provider": "llamastack", | |
| 44 | - "model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", | |
| 45 | - "apiBase": "http://<llama stack endpoint>/v1/openai/v1/" | |
| 46 | - } | |
| 47 | - ] | |
| 48 | - } | |
| 49 | - ``` | |
| 50 | - </Tab> | |
| 51 | -</Tabs> | |
| 52 | - | |
| 53 | -## Autocomplete model | |
| 54 | - | |
| 55 | -We recommend configuring **CodeLlama 7B** as your autocomplete model. | |
| 6 | +<Info> | |
| 7 | + Get started with [Lllama Stack](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html) | |
| 8 | +</Info> | |
| 56 | 9 | |
| 57 | 10 | <Tabs> |
| 58 | - <Tab title="YAML"> | |
| 59 | - ```yaml title="config.yaml" | |
| 60 | - models: | |
| 61 | - - name: CodeLlama 7B | |
| 62 | - provider: llamastack | |
| 63 | - model: codellama:7b | |
| 64 | - apiBase: http://<llama stack endpoint>/v1/openai/v1/ | |
| 65 | - roles: | |
| 66 | - - autocomplete | |
| 67 | - ``` | |
| 68 | - </Tab> | |
| 69 | - <Tab title="JSON"> | |
| 70 | - ```json title="config.json" | |
| 71 | - { | |
| 72 | - "tabAutocompleteModel": { | |
| 73 | - "title": "CodeLlama 7B", | |
| 11 | + <Tab title="YAML"> | |
| 12 | + ```yaml title="config.yaml" | |
| 13 | + models: | |
| 14 | + - name: <MODEL_NAME> | |
| 15 | + provider: llamastack | |
| 16 | + model: <MODEL_ID> | |
| 17 | + apiBase: http://<LLAMA_STACK_ENDPOINT>/v1/openai/v1/ | |
| 18 | + ``` | |
| 19 | + </Tab> | |
| 20 | + <Tab title="JSON (Deprecated)"> | |
| 21 | + ```json title="config.json" | |
| 22 | + { | |
| 23 | + "models": [ | |
| 24 | + { | |
| 25 | + "title": "<MODEL_NAME>", | |
| 74 | 26 | "provider": "llamastack", |
| 75 | - "model": "codellama:7b", | |
| 76 | - "apiBase": "http://<llama stack endpoint>/v1/openai/v1/" | |
| 77 | - } | |
| 78 | - } | |
| 79 | - ``` | |
| 80 | - </Tab> | |
| 81 | -</Tabs> | |
| 82 | - | |
| 83 | -## Embeddings model | |
| 84 | - | |
| 85 | -By default, Llama Stack uses **all-MiniLM-L6-v2** as the embeddings model. | |
| 86 | - | |
| 87 | -<Tabs> | |
| 88 | - <Tab title="YAML"> | |
| 89 | - ```yaml title="config.yaml" | |
| 90 | - models: | |
| 91 | - - name: all-MiniLM-L6-v2 | |
| 92 | - provider: llamastack | |
| 93 | - model: all-MiniLM-L6-v2 | |
| 94 | - apiBase: http://<llama stack endpoint>/v1/openai/v1/ | |
| 95 | - roles: | |
| 96 | - - embed | |
| 97 | - ``` | |
| 98 | - </Tab> | |
| 99 | - <Tab title="JSON"> | |
| 100 | - ```json title="config.json" | |
| 101 | - { | |
| 102 | - "embeddingsProvider": { | |
| 103 | - "provider": "llamastack", | |
| 104 | - "model": "all-MiniLM-L6-v2", | |
| 105 | - "apiBase": "http://<llama stack endpoint>/v1/openai/v1/" | |
| 106 | - } | |
| 107 | - } | |
| 108 | - ``` | |
| 109 | - </Tab> | |
| 110 | -</Tabs> | |
| 111 | - | |
| 112 | -## Reranking model | |
| 113 | - | |
| 114 | -Llama Stack currently did not support Reranking API yet. | |
| 27 | + "model": "<MODEL_ID>", | |
| 28 | + "apiBase": "http://<LLAMA_STACK_ENDPOINT>/v1/openai/v1/" | |
| 29 | + } | |
| 30 | + ] | |
| 31 | + } | |
| 32 | + ``` | |
| 33 | + </Tab> | |
| 34 | +</Tabs> | |
| No newline at the end of the file |
deleted docs/customize/model-providers/more/lmstudio.mdx +0 −95
| @@ -1,95 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "LM Studio" | |
| 3 | -description: "Configure LM Studio with Continue to run open-source models locally, including setup for Llama3.1 8B for chat, embedding models, and instructions for connecting to remote instances" | |
| 4 | ---- | |
| 5 | - | |
| 6 | -[LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class: | |
| 7 | - | |
| 8 | -## Chat model | |
| 9 | - | |
| 10 | -We recommend configuring **Llama3.1 8B** as your chat model. | |
| 11 | - | |
| 12 | -<Tabs> | |
| 13 | - <Tab title="YAML"> | |
| 14 | - ```yaml title="config.yaml" | |
| 15 | - models: | |
| 16 | - - name: Llama3.1 8B Instruct | |
| 17 | - provider: lmstudio | |
| 18 | - model: meta-llama-3.1-8b-instruct | |
| 19 | - ``` | |
| 20 | - </Tab> | |
| 21 | - <Tab title="JSON"> | |
| 22 | - ```json title="config.json" | |
| 23 | - { | |
| 24 | - "models": [ | |
| 25 | - { | |
| 26 | - "title": "Llama3.1 8B Instruct", | |
| 27 | - "provider": "lmstudio", | |
| 28 | - "model": "meta-llama-3.1-8b-instruct" | |
| 29 | - } | |
| 30 | - ] | |
| 31 | - } | |
| 32 | - ``` | |
| 33 | - </Tab> | |
| 34 | -</Tabs> | |
| 35 | - | |
| 36 | -## Embeddings model | |
| 37 | - | |
| 38 | -LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) | |
| 39 | - | |
| 40 | -<Tabs> | |
| 41 | - <Tab title="YAML"> | |
| 42 | - ```yaml title="config.yaml" | |
| 43 | - models: | |
| 44 | - - name: Nomic Embed Text | |
| 45 | - provider: lmstudio | |
| 46 | - model: nomic-ai/nomic-embed-text-v1.5-GGUF | |
| 47 | - roles: | |
| 48 | - - embed | |
| 49 | - ``` | |
| 50 | - </Tab> | |
| 51 | - <Tab title="JSON"> | |
| 52 | - ```json title="config.json" | |
| 53 | - { | |
| 54 | - "embeddingsProvider": { | |
| 55 | - "provider": "lmstudio", | |
| 56 | - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" | |
| 57 | - } | |
| 58 | - } | |
| 59 | - ``` | |
| 60 | - </Tab> | |
| 61 | -</Tabs> | |
| 62 | - | |
| 63 | -## Setting up a remote instance | |
| 64 | - | |
| 65 | -To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: | |
| 66 | - | |
| 67 | -<Tabs> | |
| 68 | - <Tab title="YAML"> | |
| 69 | - ```yaml title="config.yaml" | |
| 70 | - models: | |
| 71 | - - name: Llama3.1 8B Instruct | |
| 72 | - provider: lmstudio | |
| 73 | - model: meta-llama-3.1-8b-instruct | |
| 74 | - apiBase: http://<MY ENDPOINT>/v1 | |
| 75 | - ``` | |
| 76 | - </Tab> | |
| 77 | - <Tab title="JSON"> | |
| 78 | - ```json title="config.json" | |
| 79 | - { | |
| 80 | - "models": [ | |
| 81 | - { | |
| 82 | - "title": "Llama3.1 8B Instruct", | |
| 83 | - "provider": "lmstudio", | |
| 84 | - "model": "meta-llama-3.1-8b-instruct", | |
| 85 | - "apiBase": "http://<MY ENDPOINT>/v1" | |
| 86 | - } | |
| 87 | - ] | |
| 88 | - } | |
| 89 | - ``` | |
| 90 | - </Tab> | |
| 91 | -</Tabs> | |
| 92 | - | |
| 93 | -This `apiBase` will now be used instead of the default `http://localhost:1234/v1`. | |
| 94 | - | |
| 95 | -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LMStudio.ts) |
added docs/customize/model-providers/more/mistral.mdx +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +--- | |
| 2 | +title: Mistral | |
| 3 | +slug: ../mistral | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Tip> | |
| 7 | + **Discover Mistral models [here](https://hub.continue.dev/mistral)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + Get an API key from the [Mistral Dashboard](https://console.mistral.ai) | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Configuration | |
| 15 | + | |
| 16 | +<Tabs> | |
| 17 | + <Tab title="YAML"> | |
| 18 | + ```yaml title="config.yaml" | |
| 19 | + models: | |
| 20 | + - name: <MODEL_NAME> | |
| 21 | + provider: mistral | |
| 22 | + model: <MODEL_ID> | |
| 23 | + apiKey: <YOUR_MISTRAL_API_KEY> | |
| 24 | + ``` | |
| 25 | + </Tab> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 27 | + ```json title="config.json" | |
| 28 | + { | |
| 29 | + "models": [ | |
| 30 | + { | |
| 31 | + "title": "<MODEL_NAME>", | |
| 32 | + "provider": "mistral", | |
| 33 | + "model": "<MODEL_ID>", | |
| 34 | + "apiKey": "<YOUR_MISTRAL_API_KEY>" | |
| 35 | + } | |
| 36 | + ] | |
| 37 | + } | |
| 38 | + ``` | |
| 39 | + </Tab> | |
| 40 | +</Tabs> | |
| 41 | + | |
| 42 | +<Info> | |
| 43 | + **Check out a more advanced configuration [here](https://hub.continue.dev/mistral/codestral?view=config)** | |
| 44 | +</Info> | |
| 45 | + | |
| 46 | +<Note> | |
| 47 | + The API key for `codestral.mistral.ai` is different from `api.mistral.ai`. | |
| 48 | + If you are using a Codestral API key, you should set the `apiBase` to `https://codestral.mistral.ai/v1`. | |
| 49 | + Otherwise, we will default to using `https://api.mistral.ai/v1`. | |
| 50 | +</Note> | |
| No newline at the end of the file |
modified docs/customize/model-providers/more/nvidia.mdx +7 −53
| @@ -1,36 +1,31 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "NVIDIA" |
| 3 | -description: "Configure NVIDIA AI models with Continue, including setup for Nemotron-4-340B-Instruct for chat and NVIDIA Retrieval QA Mistral 7B for embeddings" | |
| 4 | 3 | --- |
| 5 | 4 | |
| 6 | 5 | <Info> |
| 7 | - [View the | |
| 8 | - docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) | |
| 9 | - to learn how to get an API key. | |
| 6 | + Get an API key from the [NVIDIA](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) | |
| 10 | 7 | </Info> |
| 11 | 8 | |
| 12 | -## Chat model | |
| 13 | - | |
| 14 | -We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. | |
| 9 | +## Configuration | |
| 15 | 10 | |
| 16 | 11 | <Tabs> |
| 17 | 12 | <Tab title="YAML"> |
| 18 | 13 | ```yaml title="config.yaml" |
| 19 | 14 | models: |
| 20 | - - name: Nemotron-4-340B-Instruct | |
| 15 | + - name: <MODEL_NAME> | |
| 21 | 16 | provider: nvidia |
| 22 | - model: nvidia-nemotron-4-340b-instruct | |
| 17 | + model: <MODEL_ID> | |
| 23 | 18 | apiKey: <YOUR_NVIDIA_API_KEY> |
| 24 | 19 | ``` |
| 25 | 20 | </Tab> |
| 26 | - <Tab title="JSON"> | |
| 21 | + <Tab title="JSON (Deprecated)"> | |
| 27 | 22 | ```json title="config.json" |
| 28 | 23 | { |
| 29 | 24 | "models": [ |
| 30 | 25 | { |
| 31 | - "title": "Nemotron-4-340B-Instruct", | |
| 26 | + "title": "<MODEL_NAME>", | |
| 32 | 27 | "provider": "nvidia", |
| 33 | - "model": "nvidia-nemotron-4-340b-instruct", | |
| 28 | + "model": "<MODEL_ID>", | |
| 34 | 29 | "apiKey": "<YOUR_NVIDIA_API_KEY>" |
| 35 | 30 | } |
| 36 | 31 | ] |
| @@ -38,44 +33,3 @@ | ||
| 38 | 33 | ``` |
| 39 | 34 | </Tab> |
| 40 | 35 | </Tabs> |
| 41 | - | |
| 42 | -## Autocomplete model | |
| 43 | - | |
| 44 | -NVIDIA currently does not offer any autocomplete models. | |
| 45 | - | |
| 46 | -[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers. | |
| 47 | - | |
| 48 | -## Embeddings model | |
| 49 | - | |
| 50 | -We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. | |
| 51 | - | |
| 52 | -<Tabs> | |
| 53 | - <Tab title="YAML"> | |
| 54 | - ```yaml title="config.yaml" | |
| 55 | - models: | |
| 56 | - - name: Nvidia Embedder | |
| 57 | - provider: nvidia | |
| 58 | - model: nvidia/nv-embedqa-mistral-7b-v2 | |
| 59 | - apiKey: <YOUR_NVIDIA_API_KEY> | |
| 60 | - roles: | |
| 61 | - - embed | |
| 62 | - ``` | |
| 63 | - </Tab> | |
| 64 | - <Tab title="JSON"> | |
| 65 | - ```json title="config.json" | |
| 66 | - { | |
| 67 | - "embeddingsProvider": { | |
| 68 | - "provider": "nvidia", | |
| 69 | - "model": "nvidia/nv-embedqa-mistral-7b-v2", | |
| 70 | - "apiKey": "<YOUR_NVIDIA_API_KEY>" | |
| 71 | - } | |
| 72 | - } | |
| 73 | - ``` | |
| 74 | - </Tab> | |
| 75 | -</Tabs> | |
| 76 | - | |
| 77 | -## Reranking model | |
| 78 | - | |
| 79 | -NVIDIA currently does not offer any reranking models. | |
| 80 | - | |
| 81 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. |
deleted docs/customize/model-providers/more/openrouter.mdx +0 −125
| @@ -1,125 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Configure OpenRouter with Continue" | |
| 3 | -sidebarTitle: "OpenRouter" | |
| 4 | -description: "Configure OpenRouter with Continue to access various commercial and open-source models through a unified interface, including model capability configuration and advanced request options" | |
| 5 | ---- | |
| 6 | - | |
| 7 | -OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). | |
| 8 | - | |
| 9 | -Change `~/.continue/config.json` to look like the following. | |
| 10 | - | |
| 11 | -<Tabs> | |
| 12 | - <Tab title="YAML"> | |
| 13 | - ```yaml title="config.yaml" | |
| 14 | - models: | |
| 15 | - - name: OpenRouter LLaMA 70 8B | |
| 16 | - provider: openrouter | |
| 17 | - model: meta-llama/llama-3-70b-instruct | |
| 18 | - apiBase: https://openrouter.ai/api/v1 | |
| 19 | - apiKey: <YOUR_OPEN_ROUTER_API_KEY> | |
| 20 | - ``` | |
| 21 | - </Tab> | |
| 22 | - <Tab title="JSON"> | |
| 23 | - ```json title="config.json" | |
| 24 | - { | |
| 25 | - "models": [ | |
| 26 | - { | |
| 27 | - "title": "OpenRouter LLaMA 70 8B", | |
| 28 | - "provider": "openrouter", | |
| 29 | - "model": "meta-llama/llama-3-70b-instruct", | |
| 30 | - "apiBase": "https://openrouter.ai/api/v1", | |
| 31 | - "apiKey": "<YOUR_OPEN_ROUTER_API_KEY>" | |
| 32 | - } | |
| 33 | - ] | |
| 34 | - } | |
| 35 | - ``` | |
| 36 | - </Tab> | |
| 37 | -</Tabs> | |
| 38 | - | |
| 39 | -To utilize features such as provider preferences or model routing configuration, include these parameters inside the `models[].requestsOptions.extraBodyProperties` field of your plugin config. | |
| 40 | - | |
| 41 | -For example, to prevent extra long prompts from being compressed, you can explicitly turn off the feature like so: | |
| 42 | - | |
| 43 | -<Tabs> | |
| 44 | - <Tab title="YAML"> | |
| 45 | - ```yaml title="config.yaml" | |
| 46 | - models: | |
| 47 | - - name: Example Model | |
| 48 | - provider: exampleProvider | |
| 49 | - model: example-model | |
| 50 | - requestOptions: | |
| 51 | - extraBodyProperties: | |
| 52 | - transforms: [] | |
| 53 | - ``` | |
| 54 | - </Tab> | |
| 55 | - <Tab title="JSON"> | |
| 56 | - ```json title="config.json" | |
| 57 | - { | |
| 58 | - "models": [ | |
| 59 | - { | |
| 60 | - "title": "Example Model", | |
| 61 | - "provider": "exampleProvider", | |
| 62 | - "model": "example-model", | |
| 63 | - "requestOptions": { | |
| 64 | - "extraBodyProperties": { | |
| 65 | - "transforms": [] | |
| 66 | - } | |
| 67 | - } | |
| 68 | - } | |
| 69 | - ] | |
| 70 | - } | |
| 71 | - ``` | |
| 72 | - </Tab> | |
| 73 | -</Tabs> | |
| 74 | - | |
| 75 | -Learn more about available settings [here](https://openrouter.ai/docs). | |
| 76 | - | |
| 77 | -## Model Capabilities | |
| 78 | - | |
| 79 | -OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support. | |
| 80 | - | |
| 81 | -<Info> | |
| 82 | - Continue automatically uses system message tools for models that don't support | |
| 83 | - native function calling, so Agent mode should work even without explicit | |
| 84 | - capability configuration. However, you can still override capabilities if | |
| 85 | - needed. | |
| 86 | -</Info> | |
| 87 | - | |
| 88 | -If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field: | |
| 89 | - | |
| 90 | -<Tabs> | |
| 91 | - <Tab title="YAML"> | |
| 92 | - ```yaml title="config.yaml" | |
| 93 | - models: | |
| 94 | - - name: Claude via OpenRouter | |
| 95 | - provider: openrouter | |
| 96 | - model: anthropic/claude-3.5-sonnet | |
| 97 | - apiBase: https://openrouter.ai/api/v1 | |
| 98 | - apiKey: <YOUR_OPEN_ROUTER_API_KEY> | |
| 99 | - capabilities: | |
| 100 | - - tool_use # Enable function calling for Agent mode | |
| 101 | - - image_input # Enable image upload support | |
| 102 | - ``` | |
| 103 | - </Tab> | |
| 104 | - <Tab title="JSON"> | |
| 105 | - ```json title="config.json" | |
| 106 | - { | |
| 107 | - "models": [ | |
| 108 | - { | |
| 109 | - "title": "Claude via OpenRouter", | |
| 110 | - "provider": "openrouter", | |
| 111 | - "model": "anthropic/claude-3.5-sonnet", | |
| 112 | - "apiBase": "https://openrouter.ai/api/v1", | |
| 113 | - "apiKey": "<YOUR_OPEN_ROUTER_API_KEY>", | |
| 114 | - "capabilities": { | |
| 115 | - "tools": true, | |
| 116 | - "uploadImage": true | |
| 117 | - } | |
| 118 | - } | |
| 119 | - ] | |
| 120 | - } | |
| 121 | - ``` | |
| 122 | - </Tab> | |
| 123 | -</Tabs> | |
| 124 | - | |
| 125 | -Note: Not all models support function calling. Check the [OpenRouter models page](https://openrouter.ai/models) for specific model capabilities. |
modified docs/customize/model-providers/more/together.mdx +36 −27
| @@ -1,35 +1,44 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "How to Configure Together AI with Continue" | |
| 3 | -description: "Configure the Together AI cloud platform for running large language models with Continue, including setup instructions and sample configuration for Qwen2.5 Coder" | |
| 2 | +title: "Together AI" | |
| 4 | 3 | sidebarTitle: "Together AI" |
| 5 | 4 | --- |
| 6 | 5 | |
| 7 | -The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this: | |
| 6 | +<Tip> | |
| 7 | + **Discover Together AI models [here](https://hub.continue.dev/togetherai)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + Get an API key from the [Together AI](https://api.together.ai) | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Configuration | |
| 8 | 15 | |
| 9 | 16 | <Tabs> |
| 10 | - <Tab title="YAML"> | |
| 11 | - ```yaml title="config.yaml" | |
| 12 | - models: | |
| 13 | - - name: Together Qwen2.5 Coder | |
| 14 | - provider: together | |
| 15 | - model: Qwen/Qwen2.5-Coder-32B-Instruct | |
| 16 | - apiKey: <YOUR_TOGETHER_API_KEY> | |
| 17 | - ``` | |
| 18 | - </Tab> | |
| 19 | - <Tab title="JSON"> | |
| 20 | - ```json title="config.json" | |
| 21 | - { | |
| 22 | - "models": [ | |
| 23 | - { | |
| 24 | - "title": "Together Qwen2.5 Coder", | |
| 25 | - "provider": "together", | |
| 26 | - "model": "Qwen/Qwen2.5-Coder-32B-Instruct", | |
| 27 | - "apiKey": "<YOUR_TOGETHER_API_KEY>" | |
| 28 | - } | |
| 29 | - ] | |
| 30 | - } | |
| 31 | - ``` | |
| 32 | - </Tab> | |
| 17 | + <Tab title="YAML"> | |
| 18 | + ```yaml title="config.yaml" | |
| 19 | + models: | |
| 20 | + - name: <MODEL_NAME> | |
| 21 | + provider: together | |
| 22 | + model: <MODEL_ID> | |
| 23 | + apiKey: <YOUR_TOGETHER_API_KEY> | |
| 24 | + ``` | |
| 25 | + </Tab> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 27 | + ```json title="config.json" | |
| 28 | + { | |
| 29 | + "models": [ | |
| 30 | + { | |
| 31 | + "title": "<MODEL_NAME>", | |
| 32 | + "provider": "together", | |
| 33 | + "model": "<MODEL_ID>", | |
| 34 | + "apiKey": "<YOUR_TOGETHER_API_KEY>" | |
| 35 | + } | |
| 36 | + ] | |
| 37 | + } | |
| 38 | + ``` | |
| 39 | + </Tab> | |
| 33 | 40 | </Tabs> |
| 34 | 41 | |
| 35 | -[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Together.ts) | |
| 42 | +<Info> | |
| 43 | + **Check out a more advanced configuration [here](https://hub.continue.dev/togetherai/qwen3-coder-480b-a35b-instruct-fp8?view=config)** | |
| 44 | +</Info> | |
| No newline at the end of the file |
added docs/customize/model-providers/more/xAI.mdx +44 −0
| @@ -0,0 +1,44 @@ | ||
| 1 | +--- | |
| 2 | +title: xAI | |
| 3 | +slug: ../xai | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Tip> | |
| 7 | + **Discover xAI models [here](https://hub.continue.dev/xai)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + Get an API key from the [xAI Console](https://console.x.ai/) | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Configuration | |
| 15 | + | |
| 16 | +<Tabs> | |
| 17 | + <Tab title="YAML"> | |
| 18 | + ```yaml title="config.yaml" | |
| 19 | + models: | |
| 20 | + - name: <MODEL_NAME> | |
| 21 | + provider: xai | |
| 22 | + model: <MODEL_ID> | |
| 23 | + apiKey: <YOUR_XAI_API_KEY> | |
| 24 | + ``` | |
| 25 | + </Tab> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 27 | + ```json title="config.json" | |
| 28 | + { | |
| 29 | + "models": [ | |
| 30 | + { | |
| 31 | + "title": "<MODEL_NAME>", | |
| 32 | + "provider": "anthropic", | |
| 33 | + "model": "<MODEL_ID>", | |
| 34 | + "apiKey": "<YOUR_XAI_API_KEY>" | |
| 35 | + } | |
| 36 | + ] | |
| 37 | + } | |
| 38 | + ``` | |
| 39 | + </Tab> | |
| 40 | +</Tabs> | |
| 41 | + | |
| 42 | +<Info> | |
| 43 | + **Check out a more advanced configuration [here](https://hub.continue.dev/xai/grok-4?view=config)** | |
| 44 | +</Info> | |
| No newline at the end of the file |
modified docs/customize/model-providers/overview.mdx +9 −8
| @@ -15,9 +15,9 @@ | ||
| 15 | 15 | | [Amazon Bedrock](/customize/model-providers/top-level/bedrock) | AWS service offering access to various foundation models | Chat, Edit, Apply, Embeddings | |
| 16 | 16 | | [Ollama](/customize/model-providers/top-level/ollama) | Run open-source models locally with a simple interface | Chat, Edit, Apply, Embeddings, Autocomplete | |
| 17 | 17 | | [Google Gemini](/customize/model-providers/top-level/gemini) | Google's multimodal AI models | Chat, Edit, Apply, Embeddings | |
| 18 | -| [DeepSeek](/customize/model-providers/top-level/deepseek) | Specialized code models with strong performance | Chat, Edit, Apply | | |
| 19 | -| [Mistral](/customize/model-providers/top-level/mistral) | High-performance open models with commercial offerings | Chat, Edit, Apply, Embeddings | | |
| 20 | -| [xAI](/customize/model-providers/top-level/xAI) | Grok models from xAI | Chat, Edit, Apply | | |
| 18 | +| [DeepSeek](/customize/model-providers/more/deepseek) | Specialized code models with strong performance | Chat, Edit, Apply | | |
| 19 | +| [Mistral](/customize/model-providers/more/mistral) | High-performance open models with commercial offerings | Chat, Edit, Apply, Embeddings | | |
| 20 | +| [xAI](/customize/model-providers/more/xAI) | Grok models from xAI | Chat, Edit, Apply | | |
| 21 | 21 | | [Vertex AI](/customize/model-providers/top-level/vertexai) | Google Cloud's machine learning platform | Chat, Edit, Apply, Embeddings | |
| 22 | 22 | | [Inception](/customize/model-providers/top-level/inception) | On-premises open-source model runners | Chat, Edit, Apply | |
| 23 | 23 | |
| @@ -32,7 +32,8 @@ | ||
| 32 | 32 | | [Groq](/customize/model-providers/more/groq) | Ultra-fast inference for various open models | |
| 33 | 33 | | [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models | |
| 34 | 34 | | [DeepInfra](/customize/model-providers/more/deepinfra) | Hosting for various open source models | |
| 35 | -| [OpenRouter](/customize/model-providers/more/openrouter) | Gateway to multiple model providers | | |
| 35 | +| [OpenRouter](/customize/model-providers/top-level/openrouter) | Gateway to multiple model providers | | |
| 36 | +| [Tetrate Agent Router Service](/customize/model-providers/top-level/tetrate_agent_router_service) | Gateway with intelligent routing across multiple model providers | | |
| 36 | 37 | | [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation | |
| 37 | 38 | | [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting | |
| 38 | 39 | | [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services | |
| @@ -42,7 +43,7 @@ | ||
| 42 | 43 | |
| 43 | 44 | | Provider | Description | |
| 44 | 45 | | :------------------------------------------------------- | :-------------------------------------------- | |
| 45 | -| [LM Studio](/customize/model-providers/more/lmstudio) | Desktop app for running models locally | | |
| 46 | +| [LM Studio](/customize/model-providers/top-level/lmstudio) | Desktop app for running models locally | | |
| 46 | 47 | | [llama.cpp](/customize/model-providers/more/llamacpp) | Optimized C++ implementation for running LLMs | |
| 47 | 48 | | [LlamaStack](/customize/model-providers/more/llamastack) | Stack for running Llama models locally | |
| 48 | 49 | | [llamafile](/customize/model-providers/more/llamafile) | Self-contained executable model files | |
| @@ -72,9 +73,9 @@ | ||
| 72 | 73 | |
| 73 | 74 | ```yaml |
| 74 | 75 | models: |
| 75 | - - name: My Model | |
| 76 | - provider: openai # Choose provider from the lists above | |
| 77 | - model: gpt-4o # Specific model name | |
| 76 | + - name: Claude 4 Sonnet | |
| 77 | + provider: anthropic # Choose provider from the lists above | |
| 78 | + model: claude-sonnet-4-20250514 # Specific model name | |
| 78 | 79 | apiKey: ${{ secrets.OPENAI_API_KEY }} |
| 79 | 80 | roles: |
| 80 | 81 | - chat |
modified docs/customize/model-providers/top-level/anthropic.mdx +19 −40
| @@ -1,37 +1,37 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Anthropic Claude Models with Continue" |
| 3 | 3 | slug: ../anthropic |
| 4 | -description: "Configure Anthropic's Claude models with Continue, including Claude 4 Sonnet with prompt caching capabilities to improve performance and reduce costs for chat applications" | |
| 5 | 4 | sidebarTitle: "Anthropic" |
| 6 | 5 | --- |
| 7 | 6 | |
| 7 | +<Tip> | |
| 8 | + **Discover Anthropic models [here](https://hub.continue.dev/anthropic)** | |
| 9 | +</Tip> | |
| 10 | + | |
| 8 | 11 | <Info> |
| 9 | - You can get an API key from the [Anthropic | |
| 10 | - console](https://console.anthropic.com/account/keys). | |
| 12 | + Get an API key from the [Anthropic Console](https://console.anthropic.com/account/keys) | |
| 11 | 13 | </Info> |
| 12 | 14 | |
| 13 | -## How to Set Up Anthropic Chat Models | |
| 14 | - | |
| 15 | -We recommend configuring **Claude 4 Sonnet** as your chat model. | |
| 15 | +## Configuration | |
| 16 | 16 | |
| 17 | 17 | <Tabs> |
| 18 | 18 | <Tab title="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - name: Claude 4 Sonnet | |
| 21 | + - name: <MODEL_NAME> | |
| 22 | 22 | provider: anthropic |
| 23 | - model: claude-sonnet-4-20250514 | |
| 23 | + model: <MODEL_ID> | |
| 24 | 24 | apiKey: <YOUR_ANTHROPIC_API_KEY> |
| 25 | 25 | ``` |
| 26 | 26 | </Tab> |
| 27 | - <Tab title="JSON"> | |
| 27 | + <Tab title="JSON (Deprecated)"> | |
| 28 | 28 | ```json title="config.json" |
| 29 | 29 | { |
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | - "title": "Claude 4 Sonnet", | |
| 32 | + "title": "<MODEL_NAME>", | |
| 33 | 33 | "provider": "anthropic", |
| 34 | - "model": "claude-sonnet-4-latest", | |
| 34 | + "model": "<MODEL_ID>", | |
| 35 | 35 | "apiKey": "<YOUR_ANTHROPIC_API_KEY>" |
| 36 | 36 | } |
| 37 | 37 | ] |
| @@ -40,44 +40,23 @@ | ||
| 40 | 40 | </Tab> |
| 41 | 41 | </Tabs> |
| 42 | 42 | |
| 43 | -## Anthropic Autocomplete Model Availability | |
| 44 | - | |
| 45 | -Anthropic currently does not offer any autocomplete models. | |
| 46 | - | |
| 47 | -[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers. | |
| 48 | - | |
| 49 | -## Anthropic Embeddings Model Availability | |
| 50 | - | |
| 51 | -Anthropic currently does not offer any embeddings models. | |
| 52 | - | |
| 53 | -[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers. | |
| 54 | - | |
| 55 | -## Anthropic Reranking Model Availability | |
| 56 | - | |
| 57 | -Anthropic currently does not offer any reranking models. | |
| 58 | - | |
| 59 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. | |
| 43 | +<Info> | |
| 44 | + **Check out a more advanced configuration [here](https://hub.continue.dev/anthropic/claude-4-sonnet?view=config)** | |
| 45 | +</Info> | |
| 60 | 46 | |
| 61 | 47 | ## How to Enable Prompt Caching with Claude |
| 62 | 48 | |
| 63 | 49 | Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching), which allows Claude models to cache system messages and conversation history between requests to improve performance and reduce costs. |
| 64 | 50 | |
| 65 | -Prompt caching is generally available for: | |
| 66 | - | |
| 67 | -- Claude 4 Sonnet | |
| 68 | -- Claude 3.7 Sonnet | |
| 69 | -- Claude 3.5 Sonnet | |
| 70 | -- Claude 3.5 Haiku | |
| 71 | - | |
| 72 | 51 | To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows: |
| 73 | 52 | |
| 74 | 53 | <Tabs> |
| 75 | 54 | <Tab title="YAML"> |
| 76 | 55 | ```yaml title="config.yaml" |
| 77 | 56 | models: |
| 78 | - - name: Anthropic | |
| 57 | + - name: <MODEL_NAME> | |
| 79 | 58 | provider: anthropic |
| 80 | - model: claude-sonnet-4-20250514 | |
| 59 | + model: <MODEL_ID> | |
| 81 | 60 | apiKey: <YOUR_ANTHROPIC_API_KEY> |
| 82 | 61 | roles: |
| 83 | 62 | - chat |
| @@ -85,7 +64,7 @@ | ||
| 85 | 64 | promptCaching: true |
| 86 | 65 | ``` |
| 87 | 66 | </Tab> |
| 88 | - <Tab title="JSON"> | |
| 67 | + <Tab title="JSON (Deprecated)"> | |
| 89 | 68 | ```json title="config.json" |
| 90 | 69 | { |
| 91 | 70 | "models": [ |
| @@ -94,9 +73,9 @@ | ||
| 94 | 73 | "cacheSystemMessage": true, |
| 95 | 74 | "cacheConversation": true |
| 96 | 75 | }, |
| 97 | - "title": "Anthropic", | |
| 76 | + "title": "<MODEL_NAME>", | |
| 98 | 77 | "provider": "anthropic", |
| 99 | - "model": "claude-sonnet-4-latest", | |
| 78 | + "model": "<MODEL_ID>", | |
| 100 | 79 | "defaultCompletionOptions": { |
| 101 | 80 | "promptCaching": true |
| 102 | 81 | }, |
modified docs/customize/model-providers/top-level/azure.mdx +18 −116
| @@ -1,29 +1,20 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Azure AI Foundry with Continue" |
| 3 | 3 | slug: ../azure |
| 4 | -description: "Configure Azure AI Foundry with Continue to access models from OpenAI and Mistral with Microsoft's enterprise security features, including setup for GPT-4o, Codestral, and embedding models" | |
| 5 | 4 | sidebarTitle: "Azure AI Foundry" |
| 6 | 5 | --- |
| 7 | 6 | |
| 8 | -Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com). | |
| 9 | - | |
| 10 | 7 | <Info> |
| 11 | - | |
| 12 | -For details on OpenAI model setup, see [Azure OpenAI Service configuration](#how-to-configure-azure-openai-service). | |
| 13 | - | |
| 8 | + Create an Azure AI Foundry resource in the [Azure Portal](https://portal.azure.com) | |
| 14 | 9 | </Info> |
| 15 | 10 | |
| 16 | -## How to Set Up Azure AI Foundry Chat Models | |
| 17 | - | |
| 18 | -We recommend configuring **GPT-4o** as your chat model. | |
| 19 | - | |
| 20 | 11 | <Tabs> |
| 21 | 12 | <Tab title="YAML"> |
| 22 | 13 | ```yaml title="config.yaml" |
| 23 | 14 | models: |
| 24 | - - name: GPT-4o | |
| 15 | + - name: <Model_NAME> | |
| 25 | 16 | provider: azure |
| 26 | - model: gpt-4o | |
| 17 | + model: <MODEL_ID> | |
| 27 | 18 | apiBase: <YOUR_DEPLOYMENT_BASE> |
| 28 | 19 | apiKey: <YOUR_AZURE_API_KEY> # If you use subscription key, try using Azure gateway to rename it apiKey |
| 29 | 20 | env: |
| @@ -32,13 +23,13 @@ | ||
| 32 | 23 | apiVersion: 2023-07-01-preview # Azure API version |
| 33 | 24 | ``` |
| 34 | 25 | </Tab> |
| 35 | - <Tab title="JSON"> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 36 | 27 | ```json title="config.json" |
| 37 | 28 | { |
| 38 | 29 | "models": [{ |
| 39 | - "title": "GPT-4o", | |
| 30 | + "title": "<MODEL_NAME>", | |
| 40 | 31 | "provider": "azure", |
| 41 | - "model": "gpt-4o", | |
| 32 | + "model": "<MODEL_ID>", | |
| 42 | 33 | "apiBase": "<YOUR_DEPLOYMENT_BASE>", |
| 43 | 34 | "deployment": "<YOUR_DEPLOYMENT_NAME>", |
| 44 | 35 | "apiKey": "<YOUR_AZURE_API_KEY>", // If you use subscription key, try using Azure gateway to rename it apiKey |
| @@ -49,101 +40,12 @@ | ||
| 49 | 40 | </Tab> |
| 50 | 41 | </Tabs> |
| 51 | 42 | |
| 52 | -## How to Set Up Azure AI Foundry Autocomplete Models | |
| 53 | - | |
| 54 | -We recommend configuring **Codestral** as your autocomplete model. | |
| 55 | - | |
| 56 | -<Info> | |
| 57 | - **Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint | |
| 58 | - required for autocomplete functionality. To use Codestral for autocomplete, | |
| 59 | - deploy it through **Azure Machine Learning Studio** instead, which provides | |
| 60 | - the necessary `/v1/fim/completions` endpoint. | |
| 61 | -</Info> | |
| 62 | - | |
| 63 | -If you use Azure Machine Learning Studio to deploy Codestral: | |
| 64 | - | |
| 65 | -<Tabs> | |
| 66 | - <Tab title="YAML"> | |
| 67 | - ```yaml title="config.yaml" | |
| 68 | - models: | |
| 69 | - - name: Codestral | |
| 70 | - provider: mistral | |
| 71 | - model: codestral-latest | |
| 72 | - apiBase: https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1 | |
| 73 | - apiKey: <YOUR_AZURE_API_KEY> | |
| 74 | - roles: | |
| 75 | - - autocomplete | |
| 76 | - ``` | |
| 77 | - </Tab> | |
| 78 | - <Tab title="JSON"> | |
| 79 | - ```json title="config.json" | |
| 80 | - { | |
| 81 | - "tabAutocompleteModel": { | |
| 82 | - "title": "Codestral", | |
| 83 | - "provider": "mistral", | |
| 84 | - "model": "codestral-latest", | |
| 85 | - "apiBase": "https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1", | |
| 86 | - "apiKey": "<YOUR_AZURE_API_KEY>" | |
| 87 | - } | |
| 88 | - } | |
| 89 | - ``` | |
| 90 | - </Tab> | |
| 91 | -</Tabs> | |
| 92 | - | |
| 93 | -## How to Configure Azure AI Foundry Embeddings Models | |
| 94 | - | |
| 95 | -We recommend configuring **text-embedding-3-large** as your embeddings model. | |
| 96 | - | |
| 97 | -<Tabs> | |
| 98 | - <Tab title="YAML"> | |
| 99 | - ```yaml title="config.yaml" | |
| 100 | - models: | |
| 101 | - - name: Text Embedding-3 Large | |
| 102 | - provider: azure | |
| 103 | - model: text-embedding-3-large | |
| 104 | - apiBase: <YOUR_DEPLOYMENT_BASE> | |
| 105 | - apiKey: <YOUR_AZURE_API_KEY> | |
| 106 | - env: | |
| 107 | - deployment: <YOUR_DEPLOYMENT_NAME> | |
| 108 | - apiType: azure | |
| 109 | - apiVersion: 2023-07-01-preview | |
| 110 | - ``` | |
| 111 | - </Tab> | |
| 112 | - <Tab title="JSON"> | |
| 113 | - ```json title="config.json" | |
| 114 | - { | |
| 115 | - "embeddingsProvider": { | |
| 116 | - "provider": "azure", | |
| 117 | - "model": "text-embedding-3-large", | |
| 118 | - "apiBase": "<YOUR_DEPLOYMENT_BASE>", | |
| 119 | - "deployment": "<YOUR_DEPLOYMENT_NAME>", | |
| 120 | - "apiKey": "<YOUR_AZURE_API_KEY>", | |
| 121 | - "apiType": "azure-foundry" // Or "azure-openai" if using OpenAI models | |
| 122 | - } | |
| 123 | - } | |
| 124 | - ``` | |
| 125 | - </Tab> | |
| 126 | -</Tabs> | |
| 127 | - | |
| 128 | -## Reranking model | |
| 129 | - | |
| 130 | -Azure OpenAI currently does not offer any reranking models. | |
| 131 | - | |
| 132 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking models. | |
| 133 | - | |
| 134 | -## Privacy | |
| 135 | - | |
| 136 | -If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant. | |
| 43 | +## Azure OpenAI Service (Alternative) | |
| 137 | 44 | |
| 138 | 45 | <Info> |
| 139 | - **Getting access:** [Click | |
| 140 | - here](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | |
| 141 | - to apply for access to the Azure OpenAI service. Response times are typically | |
| 142 | - within a few days. | |
| 46 | + Get access to the Azure OpenAI service [here](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | |
| 143 | 47 | </Info> |
| 144 | 48 | |
| 145 | -## Azure OpenAI Service configuration | |
| 146 | - | |
| 147 | 49 | Azure OpenAI Service requires a handful of additional parameters to be configured, such as a deployment name and API base URL. |
| 148 | 50 | |
| 149 | 51 | To find this information in _Azure AI Foundry_, first select the model that you would like to connect. Then visit _Endpoint_ > _Target URI_. |
| @@ -154,29 +56,29 @@ | ||
| 154 | 56 | <Tab title="YAML"> |
| 155 | 57 | ```yaml title="config.yaml" |
| 156 | 58 | models: |
| 157 | - - name: GPT-4o Azure | |
| 158 | - model: gpt-4o | |
| 59 | + - name: <MODEL_NAME> | |
| 60 | + model: <MODEL_ID> | |
| 159 | 61 | provider: azure |
| 160 | 62 | apiBase: https://just-an-example.openai.azure.com |
| 161 | 63 | apiKey: <YOUR_AZURE_API_KEY> |
| 162 | 64 | env: |
| 163 | - apiVersion: 2023-03-15-preview | |
| 164 | - deployment: gpt-4o-july | |
| 65 | + apiVersion: <API_VERSION> | |
| 66 | + deployment: <MODEL_DEPLOYMENT> | |
| 165 | 67 | apiType: azure-openai |
| 166 | 68 | ``` |
| 167 | 69 | </Tab> |
| 168 | - <Tab title="JSON"> | |
| 70 | + <Tab title="JSON (Deprecated)"> | |
| 169 | 71 | ```json title="config.json" |
| 170 | 72 | { |
| 171 | - "title": "GPT-4o Azure", | |
| 172 | - "model": "gpt-4o", | |
| 73 | + "title": "<MODEL_NAME>", | |
| 74 | + "model": "<MODEL_ID>", | |
| 173 | 75 | "provider": "azure", |
| 174 | 76 | "apiBase": "https://just-an-example.openai.azure.com", |
| 175 | - "deployment": "gpt-4o-july", | |
| 176 | - "apiVersion": "2023-03-15-preview", | |
| 77 | + "deployment": "<MODEL_DEPLOYMENT>", | |
| 78 | + "apiVersion": "<API_VERSION>", | |
| 177 | 79 | "apiKey": "<YOUR_AZURE_API_KEY>", |
| 178 | 80 | "apiType": "azure-openai" |
| 179 | 81 | } |
| 180 | 82 | ``` |
| 181 | 83 | </Tab> |
| 182 | -</Tabs> | |
| 84 | +</Tabs> | |
| No newline at the end of the file |
modified docs/customize/model-providers/top-level/bedrock.mdx +29 −138
| @@ -1,23 +1,26 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Amazon Bedrock with Continue" |
| 3 | 3 | slug: ../bedrock |
| 4 | -description: "Configure Amazon Bedrock with Continue to access foundation models like Claude 3.7 Sonnet for chat, Titan for embeddings, and Cohere for reranking, with AWS credential authentication" | |
| 5 | 4 | sidebarTitle: "Amazon Bedrock" |
| 6 | 5 | --- |
| 7 | 6 | |
| 8 | -Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API. | |
| 7 | +<Tip> | |
| 8 | + **Discover Amazon Bedrock models [here](https://hub.continue.dev/amazon)** | |
| 9 | +</Tip> | |
| 9 | 10 | |
| 10 | -## How to Set Up Amazon Bedrock Chat Models | |
| 11 | +<Info> | |
| 12 | + Get started with [Amazon Bedrock](https://aws.amazon.com/bedrock/) | |
| 13 | +</Info> | |
| 11 | 14 | |
| 12 | -We recommend configuring **Claude 3.7 Sonnet** as your chat model. | |
| 15 | +## Configuration | |
| 13 | 16 | |
| 14 | 17 | <Tabs> |
| 15 | 18 | <Tab title="YAML"> |
| 16 | 19 | ```yaml title="config.yaml" |
| 17 | 20 | models: |
| 18 | - - name: Claude 3.7 Sonnet | |
| 21 | + - name: <MODEL_NAME> | |
| 19 | 22 | provider: bedrock |
| 20 | - model: us.anthropic.claude-3-7-sonnet-20250219-v1:0 | |
| 23 | + model: <MODEL_ID> | |
| 21 | 24 | env: |
| 22 | 25 | region: us-east-1 |
| 23 | 26 | profile: bedrock |
| @@ -25,14 +28,14 @@ | ||
| 25 | 28 | - chat |
| 26 | 29 | ``` |
| 27 | 30 | </Tab> |
| 28 | - <Tab title="JSON"> | |
| 31 | + <Tab title="JSON (Deprecated)"> | |
| 29 | 32 | ```json title="config.json" |
| 30 | 33 | { |
| 31 | 34 | "models": [ |
| 32 | 35 | { |
| 33 | - "title": "Claude 3.7 Sonnet", | |
| 36 | + "title": "<MODEL_NAME>", | |
| 34 | 37 | "provider": "bedrock", |
| 35 | - "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0", | |
| 38 | + "model": "<MODEL_ID>", | |
| 36 | 39 | "region": "us-east-1", |
| 37 | 40 | "profile": "bedrock" |
| 38 | 41 | } |
| @@ -42,109 +45,9 @@ | ||
| 42 | 45 | </Tab> |
| 43 | 46 | </Tabs> |
| 44 | 47 | |
| 45 | -> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn't supported. Retry your request with the ID or ARN of an inference profile that contains this model.` | |
| 46 | - | |
| 47 | -> You can fix this using the following config: | |
| 48 | - | |
| 49 | -<Tabs> | |
| 50 | - <Tab title="YAML"> | |
| 51 | - ```yaml title="config.yaml" | |
| 52 | - models: | |
| 53 | - - name: Claude 3.5 Sonnet | |
| 54 | - provider: bedrock | |
| 55 | - model: us.anthropic.claude-3-5-sonnet-20241022-v2:0 | |
| 56 | - env: | |
| 57 | - region: us-east-1 | |
| 58 | - profile: bedrock | |
| 59 | - roles: | |
| 60 | - - chat | |
| 61 | - ``` | |
| 62 | - </Tab> | |
| 63 | - <Tab title="JSON"> | |
| 64 | - ```json title="config.json" | |
| 65 | - { | |
| 66 | - "models": [ | |
| 67 | - { | |
| 68 | - "title": "Claude 3.5 Sonnet", | |
| 69 | - "provider": "bedrock", | |
| 70 | - "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0", | |
| 71 | - "region": "us-east-1", | |
| 72 | - "profile": "bedrock" | |
| 73 | - } | |
| 74 | - ] | |
| 75 | - } | |
| 76 | - ``` | |
| 77 | - </Tab> | |
| 78 | -</Tabs> | |
| 79 | - | |
| 80 | -## How to Set Up Amazon Bedrock Autocomplete Models | |
| 81 | - | |
| 82 | -Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. | |
| 83 | - | |
| 84 | -In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete). | |
| 85 | - | |
| 86 | -## How to Configure Amazon Bedrock Embeddings Models | |
| 87 | - | |
| 88 | -We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) as your embeddings model. | |
| 89 | - | |
| 90 | -<Tabs> | |
| 91 | - <Tab title="YAML"> | |
| 92 | - ```yaml title="config.yaml" | |
| 93 | - models: | |
| 94 | - - name: Embeddings Model | |
| 95 | - provider: bedrock | |
| 96 | - model: amazon.titan-embed-text-v2:0 | |
| 97 | - env: | |
| 98 | - region: us-west-2 | |
| 99 | - roles: | |
| 100 | - - embed | |
| 101 | - ``` | |
| 102 | - </Tab> | |
| 103 | - <Tab title="JSON"> | |
| 104 | - ```json title="config.json" | |
| 105 | - { | |
| 106 | - "embeddingsProvider": { | |
| 107 | - "title": "Embeddings Model", | |
| 108 | - "provider": "bedrock", | |
| 109 | - "model": "amazon.titan-embed-text-v2:0", | |
| 110 | - "region": "us-west-2" | |
| 111 | - } | |
| 112 | - } | |
| 113 | - ``` | |
| 114 | - </Tab> | |
| 115 | -</Tabs> | |
| 116 | - | |
| 117 | -## How to Configure Amazon Bedrock Reranking Models | |
| 118 | - | |
| 119 | -We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. | |
| 120 | - | |
| 121 | -<Tabs> | |
| 122 | - <Tab title="YAML"> | |
| 123 | - ```yaml title="config.yaml" | |
| 124 | - models: | |
| 125 | - - name: Bedrock Reranker | |
| 126 | - provider: bedrock | |
| 127 | - model: cohere.rerank-v3-5:0 | |
| 128 | - env: | |
| 129 | - region: us-west-2 | |
| 130 | - roles: | |
| 131 | - - rerank | |
| 132 | - ``` | |
| 133 | - </Tab> | |
| 134 | - <Tab title="JSON"> | |
| 135 | - ```json title="config.json" | |
| 136 | - { | |
| 137 | - "reranker": { | |
| 138 | - "name": "bedrock", | |
| 139 | - "params": { | |
| 140 | - "model": "cohere.rerank-v3-5:0", | |
| 141 | - "region": "us-west-2" | |
| 142 | - } | |
| 143 | - } | |
| 144 | - } | |
| 145 | - ``` | |
| 146 | - </Tab> | |
| 147 | -</Tabs> | |
| 48 | +<Info> | |
| 49 | + **Check out a more advanced configuration [here](https://hub.continue.dev/amazon/us-anthropic-claude-sonnet-4-20250514-v1?view=config)** | |
| 50 | +</Info> | |
| 148 | 51 | |
| 149 | 52 | ## How to Enable Prompt Caching with Amazon Bedrock |
| 150 | 53 | |
| @@ -153,23 +56,11 @@ | ||
| 153 | 56 | `promptCaching: true` under `defaultCompletionOptions` in your model |
| 154 | 57 | configuration. |
| 155 | 58 | |
| 156 | -Prompt caching is generally available for: | |
| 157 | - | |
| 158 | -- Claude 3.7 Sonnet | |
| 159 | -- Claude 3.5 Haiku | |
| 160 | -- Amazon Nova Micro | |
| 161 | -- Amazon Nova Lite | |
| 162 | -- Amazon Nova Pro | |
| 163 | - | |
| 164 | -Customers who were granted access to Claude 3.5 Sonnet v2 during the prompt | |
| 165 | -caching preview will retain that access, but it cannot be enabled for new users | |
| 166 | -on that model. | |
| 167 | - | |
| 168 | 59 | ```yaml title="config.yaml" |
| 169 | 60 | models: |
| 170 | - - name: Claude 3.7 Sonnet | |
| 61 | + - name: <MODEL_NAME> | |
| 171 | 62 | provider: bedrock |
| 172 | - model: us.anthropic.claude-3-7-sonnet-20250219-v1:0 | |
| 63 | + model: <MODEL_ID> | |
| 173 | 64 | defaultCompletionOptions: |
| 174 | 65 | promptCaching: true |
| 175 | 66 | ``` |
| @@ -194,9 +85,9 @@ | ||
| 194 | 85 | <Tab title="YAML"> |
| 195 | 86 | ```yaml title="config.yaml" |
| 196 | 87 | models: |
| 197 | - - name: Claude 3.7 Sonnet | |
| 88 | + - name: <MODEL_NAME> | |
| 198 | 89 | provider: bedrock |
| 199 | - model: us.anthropic.claude-3-7-sonnet-20250219-v1:0 | |
| 90 | + model: <MODEL_ID> | |
| 200 | 91 | env: |
| 201 | 92 | region: us-east-1 |
| 202 | 93 | accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants |
| @@ -205,17 +96,17 @@ | ||
| 205 | 96 | - chat |
| 206 | 97 | ``` |
| 207 | 98 | </Tab> |
| 208 | - <Tab title="JSON"> | |
| 99 | + <Tab title="JSON (Deprecated)"> | |
| 209 | 100 | ```json title="config.json" |
| 210 | 101 | { |
| 211 | 102 | "models": [ |
| 212 | 103 | { |
| 213 | - "title": "Claude 3.7 Sonnet", | |
| 104 | + "title": "<MODEL_NAME>", | |
| 214 | 105 | "provider": "bedrock", |
| 215 | - "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0", | |
| 106 | + "model": "<MODEL_ID>", | |
| 216 | 107 | "region": "us-east-1", |
| 217 | - "accessKeyId": "[YOUR_ACCESS_KEY_ID]", | |
| 218 | - "secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]" | |
| 108 | + "accessKeyId": "<YOUR_ACCESS_KEY_ID>", | |
| 109 | + "secretAccessKey": "<YOUR_SECRET_ACCESS_KEY>" | |
| 219 | 110 | } |
| 220 | 111 | ] |
| 221 | 112 | } |
| @@ -231,23 +122,23 @@ | ||
| 231 | 122 | <Tab title="YAML"> |
| 232 | 123 | ```yaml title="config.yaml" |
| 233 | 124 | models: |
| 234 | - - name: AWS Bedrock deepseek-coder-6.7b-instruct | |
| 125 | + - name: <MODEL_NAME> | |
| 235 | 126 | provider: bedrockimport |
| 236 | - model: deepseek-coder-6.7b-instruct | |
| 127 | + model: <MODEL_ID> | |
| 237 | 128 | env: |
| 238 | 129 | region: us-west-2 |
| 239 | 130 | profile: bedrock |
| 240 | 131 | modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX |
| 241 | 132 | ``` |
| 242 | 133 | </Tab> |
| 243 | - <Tab title="JSON"> | |
| 134 | + <Tab title="JSON (Deprecated)"> | |
| 244 | 135 | ```json title="config.json" |
| 245 | 136 | { |
| 246 | 137 | "models": [ |
| 247 | 138 | { |
| 248 | - "title": "AWS Bedrock deepseek-coder-6.7b-instruct", | |
| 139 | + "title": "<MODEL_NAME>", | |
| 249 | 140 | "provider": "bedrockimport", |
| 250 | - "model": "deepseek-coder-6.7b-instruct", | |
| 141 | + "model": "<MODEL_ID>", | |
| 251 | 142 | "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", |
| 252 | 143 | "region": "us-west-2", |
| 253 | 144 | "profile": "bedrock" |
deleted docs/customize/model-providers/top-level/deepseek.mdx +0 −82
| @@ -1,82 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Configure DeepSeek with Continue" | |
| 3 | -slug: ../deepseek | |
| 4 | -description: "Configure DeepSeek models with Continue, including DeepSeek Chat for general conversations and DeepSeek Coder specifically optimized for code autocomplete and programming tasks" | |
| 5 | -sidebarTitle: "DeepSeek" | |
| 6 | ---- | |
| 7 | - | |
| 8 | -<Info> | |
| 9 | - You can get an API key from the [DeepSeek console](https://www.deepseek.com/). | |
| 10 | -</Info> | |
| 11 | - | |
| 12 | -## How to Set Up DeepSeek Chat Models | |
| 13 | - | |
| 14 | -We recommend configuring **DeepSeek Chat** as your chat model. | |
| 15 | - | |
| 16 | -<Tabs> | |
| 17 | - <Tab title="YAML"> | |
| 18 | - ```yaml title="config.yaml" | |
| 19 | - models: | |
| 20 | - - name: DeepSeek Chat | |
| 21 | - provider: deepseek | |
| 22 | - model: deepseek-chat | |
| 23 | - apiKey: <YOUR_DEEPSEEK_API_KEY> | |
| 24 | - ``` | |
| 25 | - </Tab> | |
| 26 | - <Tab title="JSON"> | |
| 27 | - ```json title="config.json" | |
| 28 | - { | |
| 29 | - "models": [ | |
| 30 | - { | |
| 31 | - "title": "DeepSeek Chat", | |
| 32 | - "provider": "deepseek", | |
| 33 | - "model": "deepseek-chat", | |
| 34 | - "apiKey": "<YOUR_DEEPSEEK_API_KEY>" | |
| 35 | - } | |
| 36 | - ] | |
| 37 | - } | |
| 38 | - ``` | |
| 39 | - </Tab> | |
| 40 | -</Tabs> | |
| 41 | - | |
| 42 | -## How to Set Up DeepSeek Autocomplete Models | |
| 43 | - | |
| 44 | -We recommend configuring **DeepSeek Coder** as your autocomplete model. | |
| 45 | - | |
| 46 | -<Tabs> | |
| 47 | - <Tab title="YAML"> | |
| 48 | - ```yaml title="config.yaml" | |
| 49 | - models: | |
| 50 | - - name: DeepSeek Coder | |
| 51 | - provider: deepseek | |
| 52 | - model: deepseek-coder | |
| 53 | - apiKey: <YOUR_DEEPSEEK_API_KEY> | |
| 54 | - roles: | |
| 55 | - - autocomplete | |
| 56 | - ``` | |
| 57 | - </Tab> | |
| 58 | - <Tab title="JSON"> | |
| 59 | - ```json title="config.json" | |
| 60 | - { | |
| 61 | - "tabAutocompleteModel": { | |
| 62 | - "title": "DeepSeek Coder", | |
| 63 | - "provider": "deepseek", | |
| 64 | - "model": "deepseek-coder", | |
| 65 | - "apiKey": "<YOUR_DEEPSEEK_API_KEY>" | |
| 66 | - } | |
| 67 | - } | |
| 68 | - ``` | |
| 69 | - </Tab> | |
| 70 | -</Tabs> | |
| 71 | - | |
| 72 | -## How to Configure DeepSeek Embeddings Models | |
| 73 | - | |
| 74 | -DeepSeek currently does not offer any embeddings models. | |
| 75 | - | |
| 76 | -[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers. | |
| 77 | - | |
| 78 | -## How to Configure DeepSeek Reranking Models | |
| 79 | - | |
| 80 | -DeepSeek currently does not offer any reranking models. | |
| 81 | - | |
| 82 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. |
modified docs/customize/model-providers/top-level/gemini.mdx +14 −51
| @@ -1,37 +1,37 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Gemini with Continue" |
| 3 | 3 | slug: ../gemini |
| 4 | -description: "Configure Google's Gemini models with Continue to access Gemini 2.0 Flash for chat and text-embedding-004 for embeddings with simple API key authentication" | |
| 5 | 4 | sidebarTitle: "Gemini" |
| 6 | 5 | --- |
| 7 | 6 | |
| 7 | +<Tip> | |
| 8 | + **Discover Google models [here](https://hub.continue.dev/?q=Gemini)** | |
| 9 | +</Tip> | |
| 10 | + | |
| 8 | 11 | <Info> |
| 9 | - You can get an API key from the [Google AI | |
| 10 | - Studio](https://aistudio.google.com/). | |
| 12 | + Get an API key from [Google AI Studio](https://aistudio.google.com/) | |
| 11 | 13 | </Info> |
| 12 | 14 | |
| 13 | -## How to Set Up Gemini Chat Models | |
| 14 | - | |
| 15 | -We recommend configuring **Gemini 2.0 Flash** as your chat model. | |
| 15 | +## Configuration | |
| 16 | 16 | |
| 17 | 17 | <Tabs> |
| 18 | 18 | <Tab title="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - name: Gemini 2.0 Flash | |
| 21 | + - name: <MODEL_NAME> | |
| 22 | 22 | provider: gemini |
| 23 | - model: gemini-2.0-flash | |
| 23 | + model: <MODEL_ID> | |
| 24 | 24 | apiKey: <YOUR_GEMINI_API_KEY> |
| 25 | 25 | ``` |
| 26 | 26 | </Tab> |
| 27 | - <Tab title="JSON"> | |
| 27 | + <Tab title="JSON (Deprecated)"> | |
| 28 | 28 | ```json title="config.json" |
| 29 | 29 | { |
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | - "title": "Gemini 2.0 Flash", | |
| 32 | + "title": "<MODEL_NAME>", | |
| 33 | 33 | "provider": "gemini", |
| 34 | - "model": "gemini-2.0-flash", | |
| 34 | + "model": "<MODEL_ID>", | |
| 35 | 35 | "apiKey": "<YOUR_GEMINI_API_KEY>" |
| 36 | 36 | } |
| 37 | 37 | ] |
| @@ -40,43 +40,6 @@ | ||
| 40 | 40 | </Tab> |
| 41 | 41 | </Tabs> |
| 42 | 42 | |
| 43 | -## How to Set Up Gemini Autocomplete Models | |
| 44 | - | |
| 45 | -Gemini currently does not offer any autocomplete models. | |
| 46 | - | |
| 47 | -[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers. | |
| 48 | - | |
| 49 | -## How to Configure Gemini Embeddings Models | |
| 50 | - | |
| 51 | -We recommend configuring **text-embedding-004** as your embeddings model. | |
| 52 | - | |
| 53 | -<Tabs> | |
| 54 | - <Tab title="YAML"> | |
| 55 | - ```yaml title="config.yaml" | |
| 56 | - models: | |
| 57 | - - name: Gemini Embeddings | |
| 58 | - provider: gemini | |
| 59 | - model: models/text-embedding-004 | |
| 60 | - apiKey: <YOUR_GEMINI_API_KEY> | |
| 61 | - roles: | |
| 62 | - - embed | |
| 63 | - ``` | |
| 64 | - </Tab> | |
| 65 | - <Tab title="JSON"> | |
| 66 | - ```json title="config.json" | |
| 67 | - { | |
| 68 | - "embeddingsProvider": { | |
| 69 | - "provider": "gemini", | |
| 70 | - "model": "models/text-embedding-004", | |
| 71 | - "apiKey": "<YOUR_GEMINI_API_KEY>" | |
| 72 | - } | |
| 73 | - } | |
| 74 | - ``` | |
| 75 | - </Tab> | |
| 76 | -</Tabs> | |
| 77 | - | |
| 78 | -## How to Configure Gemini Reranking Models | |
| 79 | - | |
| 80 | -Gemini currently does not offer any reranking models. | |
| 81 | - | |
| 82 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. | |
| 43 | +<Info> | |
| 44 | + **Check out a more advanced configuration [here](https://hub.continue.dev/google/gemini-2.5-pro?view=config)** | |
| 45 | +</Info> | |
| No newline at the end of the file |
modified docs/customize/model-providers/top-level/inception.mdx +16 −52
| @@ -1,65 +1,37 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Inception with Continue" |
| 3 | 3 | slug: ../inception |
| 4 | -description: "Configure Inception Labs models with Continue, featuring Mercury Coder Small for both chat and autocomplete functions, optimized for programming and code generation tasks" | |
| 5 | 4 | sidebarTitle: "Inception" |
| 6 | 5 | --- |
| 7 | 6 | |
| 7 | +<Tip> | |
| 8 | + **Discover Inception models [here](https://hub.continue.dev/inceptionlabs)** | |
| 9 | +</Tip> | |
| 10 | + | |
| 8 | 11 | <Info> |
| 9 | - You can get an API key from the [Inception | |
| 10 | - Dashboard](https://platform.inceptionlabs.ai/dashboard/api-keys). | |
| 12 | + Get an API key from [Inception Platform](https://platform.inceptionlabs.ai/dashboard/api-keys) | |
| 11 | 13 | </Info> |
| 12 | 14 | |
| 13 | -## How to Set Up Inception Chat Models | |
| 14 | - | |
| 15 | -We recommend configuring **Mercury Coder Small** as your chat model. | |
| 15 | +## Configuration | |
| 16 | 16 | |
| 17 | 17 | <Tabs> |
| 18 | 18 | <Tab title="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - uses: inceptionlabs/mercury-coder-small | |
| 22 | - with: | |
| 23 | - INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 21 | + - name: <MODEL_NAME> | |
| 22 | + provider: inception | |
| 23 | + model: <MODEL_ID> | |
| 24 | + apiKey: <INCEPTION_API_KEY> | |
| 24 | 25 | ``` |
| 25 | 26 | </Tab> |
| 26 | - <Tab title="JSON"> | |
| 27 | + <Tab title="JSON (Deprecated)"> | |
| 27 | 28 | ```json title="config.json" |
| 28 | 29 | { |
| 29 | 30 | "models": [ |
| 30 | 31 | { |
| 31 | - "title": "Mercury Coder Small", | |
| 32 | - "provider": "inception", | |
| 33 | - "model": "mercury-coder-small", | |
| 34 | - "apiKey": "<INCEPTION_API_KEY>" | |
| 35 | - } | |
| 36 | - ] | |
| 37 | - } | |
| 38 | - ``` | |
| 39 | - </Tab> | |
| 40 | -</Tabs> | |
| 41 | - | |
| 42 | -## How to Set Up Inception Autocomplete Models | |
| 43 | - | |
| 44 | -We also recommend configuring **Mercury Coder Small** as your autocomplete model. | |
| 45 | - | |
| 46 | -<Tabs> | |
| 47 | - <Tab title="YAML"> | |
| 48 | - ```yaml title="config.yaml" | |
| 49 | - models: | |
| 50 | - - uses: inceptionlabs/mercury-coder-small | |
| 51 | - with: | |
| 52 | - INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 53 | - ``` | |
| 54 | - </Tab> | |
| 55 | - <Tab title="JSON"> | |
| 56 | - ```json title="config.json" | |
| 57 | - { | |
| 58 | - "tabAutocompleteModel": [ | |
| 59 | - { | |
| 60 | - "title": "Mercury Coder Small", | |
| 32 | + "title": "<MODEL_NAME>", | |
| 61 | 33 | "provider": "inception", |
| 62 | - "model": "mercury-coder-small", | |
| 34 | + "model": "<MODEL_ID>", | |
| 63 | 35 | "apiKey": "<INCEPTION_API_KEY>" |
| 64 | 36 | } |
| 65 | 37 | ] |
| @@ -68,14 +40,6 @@ | ||
| 68 | 40 | </Tab> |
| 69 | 41 | </Tabs> |
| 70 | 42 | |
| 71 | -## How to Configure Inception Embeddings Models | |
| 72 | - | |
| 73 | -Inception currently does not offer any embeddings models. | |
| 74 | - | |
| 75 | -[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers. | |
| 76 | - | |
| 77 | -## How to Configure Inception Reranking Models | |
| 78 | - | |
| 79 | -Inception currently does not offer any reranking models. | |
| 80 | - | |
| 81 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. | |
| 43 | +<Info> | |
| 44 | + **Check out a more advanced configuration [here](https://hub.continue.dev/inceptionlabs/mercury-coder?view=config)** | |
| 45 | +</Info> |
added docs/customize/model-providers/top-level/lmstudio.mdx +47 −0
| @@ -0,0 +1,47 @@ | ||
| 1 | +--- | |
| 2 | +title: "LM Studio" | |
| 3 | +--- | |
| 4 | + | |
| 5 | +<Tip> | |
| 6 | + **Discover LM Studio models [here](https://hub.continue.dev/lmstudio)** | |
| 7 | +</Tip> | |
| 8 | + | |
| 9 | +<Info> | |
| 10 | + Get started with [LM Studio](https://lmstudio.ai/download) | |
| 11 | +</Info> | |
| 12 | + | |
| 13 | +## Configuration | |
| 14 | + | |
| 15 | +<Tabs> | |
| 16 | + <Tab title="YAML"> | |
| 17 | + ```yaml title="config.yaml" | |
| 18 | + models: | |
| 19 | + - name: <MODEL_NAME> | |
| 20 | + provider: lmstudio | |
| 21 | + model: <MODEL_ID> | |
| 22 | + apiBase: http://<MY_ENDPOINT>/v1 # if running a remote instance of LM Studio | |
| 23 | + ``` | |
| 24 | + </Tab> | |
| 25 | + <Tab title="JSON (Deprecated)"> | |
| 26 | + ```json title="config.json" | |
| 27 | + { | |
| 28 | + "models": [ | |
| 29 | + { | |
| 30 | + "title": "<MODEL_NAME>", | |
| 31 | + "provider": "lmstudio", | |
| 32 | + "model": "<MODEL_ID>", | |
| 33 | + "apiBase": "http://<MY_ENDPOINT>/v1" // if running a remote instance of LM Studio | |
| 34 | + } | |
| 35 | + ] | |
| 36 | + } | |
| 37 | + ``` | |
| 38 | + </Tab> | |
| 39 | +</Tabs> | |
| 40 | + | |
| 41 | +<Note> | |
| 42 | + The default `apiBase` is `http://localhost:1234/v1` | |
| 43 | +</Note> | |
| 44 | + | |
| 45 | +<Info> | |
| 46 | + **Check out a more advanced configuration [here](https://hub.continue.dev/lmstudio/qwen-qwen3-coder-30b?view=config)** | |
| 47 | +</Info> | |
| No newline at the end of the file |
deleted docs/customize/model-providers/top-level/mistral.mdx +0 −114
| @@ -1,114 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Configure Mistral with Continue" | |
| 3 | -slug: ../mistral | |
| 4 | -description: "Configure Mistral AI models with Continue, including Mistral Large for chat, Codestral for code autocomplete, and Mistral Embed for embeddings with separate API key options" | |
| 5 | -sidebarTitle: "Mistral" | |
| 6 | ---- | |
| 7 | - | |
| 8 | -<Info> | |
| 9 | - You can get an API key from the [Mistral | |
| 10 | - Dashboard](https://console.mistral.ai). Note that the API key for Codestral | |
| 11 | - (codestral.mistral.ai) is different from for all other models | |
| 12 | - (api.mistral.ai). If you are using a Codestral API key, you should set the | |
| 13 | - `apiBase` to `https://codestral.mistral.ai/v1`. Otherwise, we will default to | |
| 14 | - using `https://api.mistral.ai/v1`. | |
| 15 | -</Info> | |
| 16 | - | |
| 17 | -## How to Set Up Mistral Chat Models | |
| 18 | - | |
| 19 | -We recommend configuring **Mistral Large** as your chat model. | |
| 20 | - | |
| 21 | -<Tabs> | |
| 22 | - <Tab title="YAML"> | |
| 23 | - ```yaml title="config.yaml" | |
| 24 | - models: | |
| 25 | - - name: Mistral Large | |
| 26 | - provider: mistral | |
| 27 | - model: mistral-large-latest | |
| 28 | - apiKey: <YOUR_MISTRAL_API_KEY> | |
| 29 | - roles: | |
| 30 | - - chat | |
| 31 | - ``` | |
| 32 | - </Tab> | |
| 33 | - <Tab title="JSON"> | |
| 34 | - ```json title="config.json" | |
| 35 | - { | |
| 36 | - "models": [ | |
| 37 | - { | |
| 38 | - "title": "Mistral Large", | |
| 39 | - "provider": "mistral", | |
| 40 | - "model": "mistral-large-latest", | |
| 41 | - "apiKey": "<YOUR_MISTRAL_API_KEY>" | |
| 42 | - } | |
| 43 | - ] | |
| 44 | - } | |
| 45 | - ``` | |
| 46 | - </Tab> | |
| 47 | -</Tabs> | |
| 48 | - | |
| 49 | -## How to Set Up Mistral Autocomplete Models | |
| 50 | - | |
| 51 | -We recommend configuring **Codestral** as your autocomplete model. | |
| 52 | - | |
| 53 | -<Tabs> | |
| 54 | - <Tab title="YAML"> | |
| 55 | - ```yaml title="config.yaml" | |
| 56 | - models: | |
| 57 | - - name: Codestral | |
| 58 | - provider: mistral | |
| 59 | - model: codestral-latest | |
| 60 | - # apiBase: https://codestral.mistral.ai/v1 # Do this if you are using a Codestral API key | |
| 61 | - roles: | |
| 62 | - - autocomplete | |
| 63 | - ``` | |
| 64 | - </Tab> | |
| 65 | - <Tab title="JSON"> | |
| 66 | - ```json title="config.json" | |
| 67 | - { | |
| 68 | - "tabAutocompleteModel": { | |
| 69 | - "title": "Codestral", | |
| 70 | - "provider": "mistral", | |
| 71 | - "model": "codestral-latest" | |
| 72 | - // "apiBase": "https://codestral.mistral.ai/v1" // Do this if you are using a Codestral API key | |
| 73 | - } | |
| 74 | - } | |
| 75 | - ``` | |
| 76 | - </Tab> | |
| 77 | -</Tabs> | |
| 78 | - | |
| 79 | -## How to Configure Mistral Embeddings Models | |
| 80 | - | |
| 81 | -We recommend configuring **Mistral Embed** as your embeddings model. | |
| 82 | - | |
| 83 | -<Tabs> | |
| 84 | - <Tab title="YAML"> | |
| 85 | - ```yaml title="config.yaml" | |
| 86 | - models: | |
| 87 | - - name: Mistral Embed | |
| 88 | - provider: mistral | |
| 89 | - model: mistral-embed | |
| 90 | - apiKey: <YOUR_MISTRAL_API_KEY> | |
| 91 | - apiBase: https://api.mistral.ai/v1 | |
| 92 | - roles: | |
| 93 | - - embed | |
| 94 | - ``` | |
| 95 | - </Tab> | |
| 96 | - <Tab title="JSON"> | |
| 97 | - ```json title="config.json" | |
| 98 | - { | |
| 99 | - "embeddingsProvider": { | |
| 100 | - "provider": "mistral", | |
| 101 | - "model": "mistral-embed", | |
| 102 | - "apiKey": "<YOUR_MISTRAL_API_KEY>", | |
| 103 | - "apiBase": "https://api.mistral.ai/v1" | |
| 104 | - } | |
| 105 | - } | |
| 106 | - ``` | |
| 107 | - </Tab> | |
| 108 | -</Tabs> | |
| 109 | - | |
| 110 | -## How to Configure Mistral Reranking Models | |
| 111 | - | |
| 112 | -Mistral currently does not offer any reranking models. | |
| 113 | - | |
| 114 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. |
modified docs/customize/model-providers/top-level/ollama.mdx +26 −109
| @@ -1,33 +1,38 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Ollama with Continue" |
| 3 | 3 | slug: ../ollama |
| 4 | -description: "Configure Ollama with Continue to run powerful open source models locally including Llama3.1 for chat, Qwen2.5-Coder for autocomplete, and Nomic Embed Text for embeddings" | |
| 5 | 4 | sidebarTitle: "Ollama" |
| 6 | 5 | --- |
| 7 | 6 | |
| 8 | -Ollama is an open-source tool that allows to run large language models (LLMs) locally on their own computers. To use Ollama, you can install it [here](https://ollama.ai/download) and download the model you want to run with the `ollama run` command. | |
| 7 | +<Tip> | |
| 8 | + **Discover Ollama models [here](https://hub.continue.dev/lmstudio)** | |
| 9 | +</Tip> | |
| 9 | 10 | |
| 10 | -## How to Set Up Ollama Chat Models | |
| 11 | +<Info> | |
| 12 | + Get started with [Ollama](https://ollama.com/download) | |
| 13 | +</Info> | |
| 11 | 14 | |
| 12 | -We recommend configuring **Llama3.1 8B** as your chat model. | |
| 15 | +## Configuration | |
| 13 | 16 | |
| 14 | 17 | <Tabs> |
| 15 | 18 | <Tab title="YAML"> |
| 16 | 19 | ```yaml title="config.yaml" |
| 17 | 20 | models: |
| 18 | - - name: Llama3.1 8B | |
| 21 | + - name: <MODEL_NAME> | |
| 19 | 22 | provider: ollama |
| 20 | - model: llama3.1:8b | |
| 23 | + model: <MODEL_ID> | |
| 24 | + apiBase: http://<my endpoint>:11434 # if running a remote instance of Ollama | |
| 21 | 25 | ``` |
| 22 | 26 | </Tab> |
| 23 | - <Tab title="JSON"> | |
| 27 | + <Tab title="JSON (Deprecated)"> | |
| 24 | 28 | ```json title="config.json" |
| 25 | 29 | { |
| 26 | 30 | "models": [ |
| 27 | 31 | { |
| 28 | - "title": "Llama3.1 8B", | |
| 32 | + "title": "<MODEL_NAME>", | |
| 29 | 33 | "provider": "ollama", |
| 30 | - "model": "llama3.1:8b" | |
| 34 | + "model": "<MODEL_ID>" | |
| 35 | + "apiBase": "http://<my endpoint>:11434" // if running a remote instance of Ollama | |
| 31 | 36 | } |
| 32 | 37 | ] |
| 33 | 38 | } |
| @@ -35,96 +40,9 @@ | ||
| 35 | 40 | </Tab> |
| 36 | 41 | </Tabs> |
| 37 | 42 | |
| 38 | -## How to Configure Ollama Autocomplete Models | |
| 39 | - | |
| 40 | -We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. | |
| 41 | - | |
| 42 | -<Tabs> | |
| 43 | - <Tab title="YAML"> | |
| 44 | - ```yaml title="config.yaml" | |
| 45 | - models: | |
| 46 | - - name: Qwen2.5-Coder 1.5B | |
| 47 | - provider: ollama | |
| 48 | - model: qwen2.5-coder:1.5b-base | |
| 49 | - roles: | |
| 50 | - - autocomplete | |
| 51 | - ``` | |
| 52 | - </Tab> | |
| 53 | - <Tab title="JSON"> | |
| 54 | - ```json title="config.json" | |
| 55 | - { | |
| 56 | - "tabAutocompleteModel": { | |
| 57 | - "title": "Qwen2.5-Coder 1.5B", | |
| 58 | - "provider": "ollama", | |
| 59 | - "model": "qwen2.5-coder:1.5b-base" | |
| 60 | - } | |
| 61 | - } | |
| 62 | - ``` | |
| 63 | - </Tab> | |
| 64 | -</Tabs> | |
| 65 | - | |
| 66 | -## How to Set Up Ollama Embeddings Models | |
| 67 | - | |
| 68 | -We recommend configuring **Nomic Embed Text** as your embeddings model. | |
| 69 | - | |
| 70 | -<Tabs> | |
| 71 | - <Tab title="YAML"> | |
| 72 | - ```yaml title="config.yaml" | |
| 73 | - models: | |
| 74 | - - name: Nomic Embed Text | |
| 75 | - provider: ollama | |
| 76 | - model: nomic-embed-text | |
| 77 | - roles: | |
| 78 | - - embed | |
| 79 | - ``` | |
| 80 | - </Tab> | |
| 81 | - <Tab title="JSON"> | |
| 82 | - ```json title="config.json" | |
| 83 | - { | |
| 84 | - "embeddingsProvider": { | |
| 85 | - "provider": "ollama", | |
| 86 | - "model": "nomic-embed-text" | |
| 87 | - } | |
| 88 | - } | |
| 89 | - ``` | |
| 90 | - </Tab> | |
| 91 | -</Tabs> | |
| 92 | - | |
| 93 | -## Ollama Reranking Model Availability | |
| 94 | - | |
| 95 | -Ollama currently does not offer any reranking models. | |
| 96 | - | |
| 97 | -[Click here](../../model-roles/reranking) to see a list of reranking model providers. | |
| 98 | - | |
| 99 | -## How to Configure Remote Ollama Instance | |
| 100 | - | |
| 101 | -To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json: | |
| 102 | - | |
| 103 | -<Tabs> | |
| 104 | - <Tab title="YAML"> | |
| 105 | - ```yaml title="config.yaml" | |
| 106 | - models: | |
| 107 | - - name: Llama3.1 8B | |
| 108 | - provider: ollama | |
| 109 | - model: llama3.1:8b | |
| 110 | - apiBase: http://<my endpoint>:11434 | |
| 111 | - ``` | |
| 112 | - </Tab> | |
| 113 | - <Tab title="JSON"> | |
| 114 | - ```json title="config.json" | |
| 115 | - { | |
| 116 | - "models": [ | |
| 117 | - { | |
| 118 | - "title": "Llama3.1 8B", | |
| 119 | - "provider": "ollama", | |
| 120 | - "model": "llama3.1:8b", | |
| 121 | - "apiBase": "http://<my endpoint>:11434" | |
| 122 | - } | |
| 123 | - ] | |
| 124 | - } | |
| 125 | - ``` | |
| 126 | - </Tab> | |
| 127 | -</Tabs> | |
| 43 | +<Info> | |
| 44 | + **Check out a more advanced configuration [here](https://hub.continue.dev/ollama/qwen3-coder-30b?view=config)** | |
| 45 | +</Info> | |
| 128 | 46 | |
| 129 | 47 | ## How to Configure Model Capabilities in Ollama |
| 130 | 48 | |
| @@ -134,25 +52,25 @@ | ||
| 134 | 52 | <Tab title="YAML"> |
| 135 | 53 | ```yaml title="config.yaml" |
| 136 | 54 | models: |
| 137 | - - name: Custom Vision Model | |
| 55 | + - name: <CUSTOM_MODEL_NAME> | |
| 138 | 56 | provider: ollama |
| 139 | - model: my-custom-llava | |
| 57 | + model: <CUSTOM_MODEL_ID> | |
| 140 | 58 | capabilities: |
| 141 | 59 | - tool_use # Enable if your model supports function calling |
| 142 | - - image_input # Enable for vision models like llava | |
| 60 | + - image_input # Enable for vision models | |
| 143 | 61 | ``` |
| 144 | 62 | </Tab> |
| 145 | - <Tab title="JSON"> | |
| 63 | + <Tab title="JSON (Deprecated)"> | |
| 146 | 64 | ```json title="config.json" |
| 147 | 65 | { |
| 148 | 66 | "models": [ |
| 149 | 67 | { |
| 150 | - "title": "Custom Vision Model", | |
| 68 | + "title": "<CUSTOM_MODEL_NAME>", | |
| 151 | 69 | "provider": "ollama", |
| 152 | - "model": "my-custom-llava", | |
| 70 | + "model": "<CUSTOM_MODEL_ID>", | |
| 153 | 71 | "capabilities": { |
| 154 | - "tools": true, | |
| 155 | - "uploadImage": true | |
| 72 | + "tools": true, // Enable if your model supports function calling | |
| 73 | + "uploadImage": true // Enable for vision models | |
| 156 | 74 | } |
| 157 | 75 | } |
| 158 | 76 | ] |
| @@ -162,6 +80,5 @@ | ||
| 162 | 80 | </Tabs> |
| 163 | 81 | |
| 164 | 82 | <Note> |
| 165 | - Most standard Ollama models (like llama3.1, mistral, etc.) support tool use by | |
| 166 | - default. Vision models (like llava) also support image input. | |
| 83 | + Many Ollama models support tool use by default. Vision models often also support image input | |
| 167 | 84 | </Note> |
modified docs/customize/model-providers/top-level/openai.mdx +30 −73
| @@ -1,37 +1,37 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure OpenAI Models with Continue" |
| 3 | 3 | slug: ../openai |
| 4 | -description: "Configure OpenAI models with Continue, including GPT-4o for chat and text-embedding-3-large for embeddings, with support for OpenAI-compatible servers and APIs" | |
| 5 | 4 | sidebarTitle: "OpenAI" |
| 6 | 5 | --- |
| 7 | 6 | |
| 7 | +<Tip> | |
| 8 | + **Discover OpenAI models [here](https://hub.continue.dev/openai)** | |
| 9 | +</Tip> | |
| 10 | + | |
| 8 | 11 | <Info> |
| 9 | - You can get an API key from the [OpenAI | |
| 10 | - console](https://platform.openai.com/account/api-keys) | |
| 12 | + Get an API key from the [OpenAI Console](https://platform.openai.com/account/api-keys) | |
| 11 | 13 | </Info> |
| 12 | 14 | |
| 13 | -## How to Set Up OpenAI Chat Models | |
| 14 | - | |
| 15 | -We recommend configuring **GPT-4o** as your chat model. | |
| 15 | +## Configuration | |
| 16 | 16 | |
| 17 | 17 | <Tabs> |
| 18 | 18 | <Tab title="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - name: GPT-4o | |
| 21 | + - name: <MODEL_NAME> | |
| 22 | 22 | provider: openai |
| 23 | - model: gpt-4o | |
| 23 | + model: <MODEL_ID> | |
| 24 | 24 | apiKey: <YOUR_OPENAI_API_KEY> |
| 25 | 25 | ``` |
| 26 | 26 | </Tab> |
| 27 | - <Tab title="JSON"> | |
| 27 | + <Tab title="JSON (Deprecated)"> | |
| 28 | 28 | ```json title="config.json" |
| 29 | 29 | { |
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | - "title": "GPT-4o", | |
| 33 | - "provider": "openai", | |
| 34 | - "model": "gpt-4o", | |
| 32 | + "title": "<MODEL_NAME>", | |
| 33 | + "provider": "openai", | |
| 34 | + "model": "<MODEL_ID>", | |
| 35 | 35 | "apiKey": "<YOUR_OPENAI_API_KEY>" |
| 36 | 36 | } |
| 37 | 37 | ] |
| @@ -40,50 +40,13 @@ | ||
| 40 | 40 | </Tab> |
| 41 | 41 | </Tabs> |
| 42 | 42 | |
| 43 | -## OpenAI Autocomplete Model Availability | |
| 44 | - | |
| 45 | -OpenAI currently does not offer any autocomplete models. | |
| 46 | - | |
| 47 | -[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers. | |
| 48 | - | |
| 49 | -## How to Configure OpenAI Embeddings Models | |
| 50 | - | |
| 51 | -We recommend configuring **text-embedding-3-large** as your embeddings model. | |
| 52 | - | |
| 53 | -<Tabs> | |
| 54 | - <Tab title="YAML"> | |
| 55 | - ```yaml title="config.yaml" | |
| 56 | - models: | |
| 57 | - - name: OpenAI Embeddings | |
| 58 | - provider: openai | |
| 59 | - model: text-embedding-3-large | |
| 60 | - apiKey: <YOUR_OPENAI_API_KEY> | |
| 61 | - roles: | |
| 62 | - - embed | |
| 63 | - ``` | |
| 64 | - </Tab> | |
| 65 | - <Tab title="JSON"> | |
| 66 | - ```json title="config.json" | |
| 67 | - { | |
| 68 | - "embeddingsProvider": { | |
| 69 | - "provider": "openai", | |
| 70 | - "model": "text-embedding-3-large", | |
| 71 | - "apiKey": "<YOUR_OPENAI_API_KEY>" | |
| 72 | - } | |
| 73 | - } | |
| 74 | - ``` | |
| 75 | - </Tab> | |
| 76 | -</Tabs> | |
| 77 | - | |
| 78 | -## OpenAI Reranking Model Availability | |
| 79 | - | |
| 80 | -OpenAI currently does not offer any reranking models. | |
| 81 | - | |
| 82 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. | |
| 43 | +<Info> | |
| 44 | + **Check out a more advanced configuration [here](https://hub.continue.dev/openai/gpt-5?view=config)** | |
| 45 | +</Info> | |
| 83 | 46 | |
| 84 | -## How to Use OpenAI-Compatible Servers and APIs | |
| 47 | +## OpenAI API compatible providers | |
| 85 | 48 | |
| 86 | -OpenAI compatible servers | |
| 49 | +OpenAI API compatible providers include | |
| 87 | 50 | |
| 88 | 51 | - [KoboldCpp](https://github.com/lostruins/koboldcpp) |
| 89 | 52 | - [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation) |
| @@ -93,35 +56,29 @@ | ||
| 93 | 56 | - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) |
| 94 | 57 | - [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) |
| 95 | 58 | - [BerriAI/litellm](https://github.com/BerriAI/litellm) |
| 59 | +- [Tetrate Agent Router Service](https://router.tetrate.ai) | |
| 96 | 60 | |
| 97 | -OpenAI compatible APIs | |
| 98 | - | |
| 99 | -- [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) | |
| 100 | -- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) | |
| 101 | - | |
| 102 | -### How to Configure Custom API Base for OpenAI-Compatible Services | |
| 103 | - | |
| 104 | -If you are using an OpenAI compatible server / API, you can change the `apiBase` like this: | |
| 61 | +If you are using an OpenAI API compatible providers, you can change the `apiBase` like this: | |
| 105 | 62 | |
| 106 | 63 | <Tabs> |
| 107 | 64 | <Tab title="YAML"> |
| 108 | 65 | ```yaml title="config.yaml" |
| 109 | 66 | models: |
| 110 | - - name: OpenAI-compatible server / API | |
| 67 | + - name: <OPENAI_API_COMPATIBLE_PROVIDER_MODEL> | |
| 111 | 68 | provider: openai |
| 112 | - model: MODEL_NAME | |
| 69 | + model: <MODEL_NAME> | |
| 113 | 70 | apiBase: http://localhost:8000/v1 |
| 114 | 71 | apiKey: <YOUR_CUSTOM_API_KEY> |
| 115 | 72 | ``` |
| 116 | 73 | </Tab> |
| 117 | - <Tab title="JSON"> | |
| 74 | + <Tab title="JSON (Deprecated)"> | |
| 118 | 75 | ```json title="config.json" |
| 119 | 76 | { |
| 120 | 77 | "models": [ |
| 121 | 78 | { |
| 122 | - "title": "OpenAI-compatible server / API", | |
| 79 | + "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>", | |
| 123 | 80 | "provider": "openai", |
| 124 | - "model": "MODEL_NAME", | |
| 81 | + "model": "<MODEL_NAME>", | |
| 125 | 82 | "apiKey": "<YOUR_CUSTOM_API_KEY>", |
| 126 | 83 | "apiBase": "http://localhost:8000/v1" |
| 127 | 84 | } |
| @@ -139,22 +96,22 @@ | ||
| 139 | 96 | <Tab title="YAML"> |
| 140 | 97 | ```yaml title="config.yaml" |
| 141 | 98 | models: |
| 142 | - - name: OpenAI-compatible server / API | |
| 99 | + - name: <OPENAI_API_COMPATIBLE_PROVIDER_MODEL> | |
| 143 | 100 | provider: openai |
| 144 | - model: MODEL_NAME | |
| 101 | + model: <MODEL_NAME>> | |
| 145 | 102 | apiBase: http://localhost:8000/v1 |
| 146 | 103 | useLegacyCompletionsEndpoint: true |
| 147 | 104 | ``` |
| 148 | 105 | </Tab> |
| 149 | - <Tab title="JSON"> | |
| 106 | + <Tab title="JSON (Deprecated)"> | |
| 150 | 107 | ```json title="config.json" |
| 151 | 108 | { |
| 152 | 109 | "models": [ |
| 153 | 110 | { |
| 154 | - "title": "OpenAI-compatible server / API", | |
| 111 | + "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>", | |
| 155 | 112 | "provider": "openai", |
| 156 | - "model": "MODEL_NAME", | |
| 157 | - "apiBase": "http://localhost:8000/v1", | |
| 113 | + "model": "<MODEL_NAME>", | |
| 114 | + "apiBase": "http://localhost:8000/v1", | |
| 158 | 115 | "useLegacyCompletionsEndpoint": true |
| 159 | 116 | } |
| 160 | 117 | ] |
added docs/customize/model-providers/top-level/openrouter.mdx +132 −0
| @@ -0,0 +1,132 @@ | ||
| 1 | +--- | |
| 2 | +title: "How to Configure OpenRouter with Continue" | |
| 3 | +sidebarTitle: "OpenRouter" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Tip> | |
| 7 | + **Discover Inception models [here](https://hub.continue.dev/inceptionlabs)** | |
| 8 | +</Tip> | |
| 9 | + | |
| 10 | +<Info> | |
| 11 | + Get an API key from [OpenRouter](https://openrouter.ai/keys) | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +<Tabs> | |
| 15 | + <Tab title="YAML"> | |
| 16 | + ```yaml title="config.yaml" | |
| 17 | + models: | |
| 18 | + - name: <MODEL_NAME> | |
| 19 | + provider: openrouter | |
| 20 | + model: <MODEL_ID> | |
| 21 | + apiBase: https://openrouter.ai/api/v1 | |
| 22 | + apiKey: <YOUR_OPEN_ROUTER_API_KEY> | |
| 23 | + ``` | |
| 24 | + </Tab> | |
| 25 | + <Tab title="JSON (Deprecated)"> | |
| 26 | + ```json title="config.json" | |
| 27 | + { | |
| 28 | + "models": [ | |
| 29 | + { | |
| 30 | + "title": "<MODEL_NAME>", | |
| 31 | + "provider": "openrouter", | |
| 32 | + "model": "<MODEL_ID>", | |
| 33 | + "apiBase": "https://openrouter.ai/api/v1", | |
| 34 | + "apiKey": "<YOUR_OPEN_ROUTER_API_KEY>" | |
| 35 | + } | |
| 36 | + ] | |
| 37 | + } | |
| 38 | + ``` | |
| 39 | + </Tab> | |
| 40 | +</Tabs> | |
| 41 | + | |
| 42 | +<Info> | |
| 43 | + **Check out a more advanced configuration [here](https://hub.continue.dev/openrouter/qwen3-coder?view=config)** | |
| 44 | +</Info> | |
| 45 | + | |
| 46 | +## Optional configuration | |
| 47 | + | |
| 48 | +OpenRouter allows you configure provider preferences, model routing configuration, and more. You can set these via `requestOptions`. | |
| 49 | + | |
| 50 | +For example, to prevent extra long prompts from being compressed, you can explicitly turn off [Transforms](https://openrouter.ai/docs/features/message-transforms):) | |
| 51 | + | |
| 52 | +<Tabs> | |
| 53 | + <Tab title="YAML"> | |
| 54 | + ```yaml title="config.yaml" | |
| 55 | + models: | |
| 56 | + - name: <MODEL_NAME> | |
| 57 | + provider: openrouter | |
| 58 | + model: <MODEL_ID> | |
| 59 | + requestOptions: | |
| 60 | + extraBodyProperties: | |
| 61 | + transforms: [] | |
| 62 | + ``` | |
| 63 | + </Tab> | |
| 64 | + <Tab title="JSON (Deprecated)"> | |
| 65 | + ```json title="config.json" | |
| 66 | + { | |
| 67 | + "models": [ | |
| 68 | + { | |
| 69 | + "title": "<MODEL_NAME>", | |
| 70 | + "provider": "openrouter", | |
| 71 | + "model": "<MODEL_ID>", | |
| 72 | + "requestOptions": { | |
| 73 | + "extraBodyProperties": { | |
| 74 | + "transforms": [] | |
| 75 | + } | |
| 76 | + } | |
| 77 | + } | |
| 78 | + ] | |
| 79 | + } | |
| 80 | + ``` | |
| 81 | + </Tab> | |
| 82 | +</Tabs> | |
| 83 | + | |
| 84 | +## Model Capabilities | |
| 85 | + | |
| 86 | +OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the function calling support of the original model. | |
| 87 | + | |
| 88 | +<Info> | |
| 89 | + Continue automatically uses system message tools for models that don't support | |
| 90 | + native function calling, so Agent mode should work even without explicit | |
| 91 | + capability configuration. However, you can still override capabilities if | |
| 92 | + needed. | |
| 93 | +</Info> | |
| 94 | + | |
| 95 | +If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field: | |
| 96 | + | |
| 97 | +<Tabs> | |
| 98 | + <Tab title="YAML"> | |
| 99 | + ```yaml title="config.yaml" | |
| 100 | + models: | |
| 101 | + - name: <MODEL_NAME> | |
| 102 | + provider: openrouter | |
| 103 | + model: <MODEL_ID> | |
| 104 | + apiBase: https://openrouter.ai/api/v1 | |
| 105 | + apiKey: <YOUR_OPEN_ROUTER_API_KEY> | |
| 106 | + capabilities: | |
| 107 | + - tool_use # Enable function calling for Agent mode | |
| 108 | + ``` | |
| 109 | + </Tab> | |
| 110 | + <Tab title="JSON (Deprecated)"> | |
| 111 | + ```json title="config.json" | |
| 112 | + { | |
| 113 | + "models": [ | |
| 114 | + { | |
| 115 | + "title": "<MODEL_NAME>", | |
| 116 | + "provider": "openrouter", | |
| 117 | + "model": "<MODEL_ID>", | |
| 118 | + "apiBase": "https://openrouter.ai/api/v1", | |
| 119 | + "apiKey": "<YOUR_OPEN_ROUTER_API_KEY>", | |
| 120 | + "capabilities": { | |
| 121 | + "tools": true, // Enable function calling for Agent mode | |
| 122 | + } | |
| 123 | + } | |
| 124 | + ] | |
| 125 | + } | |
| 126 | + ``` | |
| 127 | + </Tab> | |
| 128 | +</Tabs> | |
| 129 | + | |
| 130 | +<Note> | |
| 131 | + Not all models support function calling. Check the [OpenRouter models page](https://openrouter.ai/models) for specific model capabilities. | |
| 132 | +</Note> |
added docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx +252 −0
| @@ -0,0 +1,252 @@ | ||
| 1 | +--- | |
| 2 | +title: "Tetrate Agent Router Service" | |
| 3 | +sidebarTitle: "Tetrate Agent Router Service" | |
| 4 | +slug: ../tetrate-agent-router-service | |
| 5 | +--- | |
| 6 | +The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities. | |
| 7 | + | |
| 8 | +This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization. | |
| 9 | + | |
| 10 | +<Tip> | |
| 11 | +Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast. | |
| 12 | +</Tip> | |
| 13 | + | |
| 14 | +## Setup | |
| 15 | + | |
| 16 | +<Steps> | |
| 17 | +<Step title="Sign in or sign up"> | |
| 18 | +Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key | |
| 19 | +<img src="../assets/tetrate-sign-in.png" alt="Tetrate sign in page" style={{width: '250px', maxWidth: '100%'}} /> | |
| 20 | +</Step> | |
| 21 | + | |
| 22 | +<Step title="Get your API key"> | |
| 23 | +Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key | |
| 24 | +<img src="../assets/tetrate-get-api-key.png" alt="Tetrate get API key" style={{width: '250px', maxWidth: '100%'}} /> | |
| 25 | +</Step> | |
| 26 | + | |
| 27 | +<Step title="Configure Continue"> | |
| 28 | +- Choose a configuration method below. | |
| 29 | +- If you use the Continue VS Code extension, install version `>=1.2.3`. | |
| 30 | +</Step> | |
| 31 | + | |
| 32 | +</Steps> | |
| 33 | + | |
| 34 | + | |
| 35 | +### Quickstart with Continue Hub | |
| 36 | + | |
| 37 | +Fastest way: use preconfigured models from Tetrate on Continue Hub | |
| 38 | + | |
| 39 | +<Steps> | |
| 40 | +<Step title="Browse models"> | |
| 41 | +Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4)) | |
| 42 | +</Step> | |
| 43 | + | |
| 44 | +<Step title="Use or remix"> | |
| 45 | +Click "Use Model", or "Remix" to change the model ID if needed | |
| 46 | +</Step> | |
| 47 | + | |
| 48 | +<Step title="Add your API key"> | |
| 49 | +Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables) | |
| 50 | +<Tip> | |
| 51 | +Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects. | |
| 52 | +</Tip> | |
| 53 | +</Step> | |
| 54 | +</Steps> | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | +<Info> | |
| 59 | +If a model is missing, remix a similar one and set the `model` field to the target ID. | |
| 60 | +</Info> | |
| 61 | + | |
| 62 | +### Configuration Methods | |
| 63 | + | |
| 64 | +<CardGroup cols={1}> | |
| 65 | + <Card title="In Local Agent Configuration" icon="folder" vertical> | |
| 66 | + Use a Tetrate model block from the Hub or define it directly in your local agent configuration. | |
| 67 | + </Card> | |
| 68 | + <Card title="Continue Hub" icon="cloud" vertical> | |
| 69 | + Use a Tetrate model block from the Hub or define your own on the Hub. | |
| 70 | + </Card> | |
| 71 | + <Card title="Using Local Model Blocks" icon="file-lines" vertical> | |
| 72 | + Create a local model block for reuse across agents without publishing it to the Hub. | |
| 73 | + </Card> | |
| 74 | +</CardGroup> | |
| 75 | + | |
| 76 | + | |
| 77 | +### Configuration Examples | |
| 78 | +<Info> | |
| 79 | +**Click a tab** to see an example. | |
| 80 | +</Info> | |
| 81 | +<Tabs> | |
| 82 | +<Tab title="In Local Agent Configuration"> | |
| 83 | + | |
| 84 | +**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks. | |
| 85 | + | |
| 86 | +Use a Tetrate model block from the Hub in your local agent configuration: | |
| 87 | + | |
| 88 | +```yaml title="~/.continue/config.yaml" | |
| 89 | +name: Local Agent | |
| 90 | +version: 1.0.0 | |
| 91 | +schema: v1 | |
| 92 | +models: | |
| 93 | + - uses: tetrate/claude-sonnet-4 | |
| 94 | + with: | |
| 95 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 96 | +context: | |
| 97 | + - provider: code | |
| 98 | + - provider: docs | |
| 99 | + - provider: diff | |
| 100 | + - provider: terminal | |
| 101 | + - provider: problems | |
| 102 | + - provider: folder | |
| 103 | + - provider: codebase | |
| 104 | +``` | |
| 105 | + | |
| 106 | +Or define the model directly: | |
| 107 | + | |
| 108 | +```yaml title="~/.continue/config.yaml" | |
| 109 | +name: Local Agent | |
| 110 | +version: 1.0.0 | |
| 111 | +schema: v1 | |
| 112 | +models: | |
| 113 | + - name: Claude Sonnet 4 | |
| 114 | + provider: tars | |
| 115 | + model: claude-4-sonnet-20250514 | |
| 116 | + apiKey: ${{ secrets.TETRATE_API_KEY }} | |
| 117 | + roles: | |
| 118 | + - chat | |
| 119 | + - edit | |
| 120 | + - apply | |
| 121 | + capabilities: | |
| 122 | + - tool_use | |
| 123 | +context: | |
| 124 | + - provider: code | |
| 125 | + - provider: docs | |
| 126 | + - provider: diff | |
| 127 | + - provider: terminal | |
| 128 | + - provider: problems | |
| 129 | + - provider: folder | |
| 130 | + - provider: codebase | |
| 131 | +``` | |
| 132 | +</Tab> | |
| 133 | +<Tab title="Continue Hub"> | |
| 134 | +**When to use**: Share configurations across teams or contribute to the community. | |
| 135 | + | |
| 136 | +**The Model Block:** | |
| 137 | + | |
| 138 | +```yaml title="tetrate/claude-sonnet-4" | |
| 139 | +name: Claude Sonnet 4 | |
| 140 | +version: 1.0.14 | |
| 141 | +schema: v1 | |
| 142 | +models: | |
| 143 | + - name: Claude Sonnet 4 - Tetrate | |
| 144 | + provider: tars | |
| 145 | + model: claude-4-sonnet-20250514 | |
| 146 | + apiKey: ${{ inputs.TETRATE_API_KEY }} | |
| 147 | + roles: | |
| 148 | + - chat | |
| 149 | + - edit | |
| 150 | + - apply | |
| 151 | + capabilities: | |
| 152 | + - tool_use | |
| 153 | +``` | |
| 154 | +View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4). | |
| 155 | + | |
| 156 | +**Reference it in your Agent configuration:** | |
| 157 | + | |
| 158 | +```yaml title="my-agent" | |
| 159 | +name: My Agent | |
| 160 | +version: 1.0.0 | |
| 161 | +schema: v1 | |
| 162 | +models: | |
| 163 | + - uses: tetrate/claude-sonnet-4 | |
| 164 | + with: | |
| 165 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 166 | +context: | |
| 167 | + - uses: continuedev/diff-context | |
| 168 | + - uses: continuedev/terminal-context | |
| 169 | + - uses: continuedev/file-context | |
| 170 | +``` | |
| 171 | +<Tip> | |
| 172 | +To customize, see the [model block creation guide](/hub/blocks/create-a-block). | |
| 173 | +</Tip> | |
| 174 | + | |
| 175 | +</Tab> | |
| 176 | + | |
| 177 | +<Tab title="Using Local Model Blocks"> | |
| 178 | +**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub). | |
| 179 | + | |
| 180 | +**The Local Model Block:** | |
| 181 | +<Info> | |
| 182 | +Name the file `my-claude-4-model.yaml` so you can reference it in the Agent. | |
| 183 | +</Info> | |
| 184 | + | |
| 185 | +```yaml title="~/.continue/models/my-claude-4-model.yaml" | |
| 186 | +name: Claude Sonnet 4 | |
| 187 | +version: 1.0.1 | |
| 188 | +schema: v1 | |
| 189 | +models: | |
| 190 | + - name: Claude Sonnet 4 | |
| 191 | + provider: tars | |
| 192 | + model: claude-4-sonnet-20250514 | |
| 193 | + apiKey: ${{ inputs.TETRATE_API_KEY }} | |
| 194 | + roles: | |
| 195 | + - chat | |
| 196 | + - edit | |
| 197 | + - apply | |
| 198 | + capabilities: | |
| 199 | + - tool_use | |
| 200 | +``` | |
| 201 | +Reference it as `my-claude-4-model` in your Agent configuration: | |
| 202 | + | |
| 203 | +```yaml title="~/.continue/agents/simple-agent.yaml" | |
| 204 | +name: Simple Agent | |
| 205 | +version: 1.0.0 | |
| 206 | +schema: v1 | |
| 207 | +models: | |
| 208 | + - uses: my-claude-4-model | |
| 209 | + with: | |
| 210 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 211 | +context: | |
| 212 | + - uses: continuedev/diff-context | |
| 213 | + - uses: continuedev/terminal-context | |
| 214 | + - uses: continuedev/file-context | |
| 215 | +``` | |
| 216 | + | |
| 217 | +<Tip> | |
| 218 | +Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks). | |
| 219 | +</Tip> | |
| 220 | + | |
| 221 | +</Tab> | |
| 222 | +</Tabs> | |
| 223 | + | |
| 224 | +--- | |
| 225 | + | |
| 226 | +## Troubleshooting Common Issues | |
| 227 | + | |
| 228 | +<CardGroup cols={2}> | |
| 229 | + <Card title="Invalid API key" icon="key" vertical> | |
| 230 | + Verify your API key is active and has no extra spaces. | |
| 231 | + </Card> | |
| 232 | + <Card title="Model not found" icon="ban" href="https://router.tetrate.ai/models" vertical> | |
| 233 | + Confirm the model ID matches the Tetrate catalog. | |
| 234 | + </Card> | |
| 235 | + <Card title="Slow responses" icon="code" vertical> | |
| 236 | + Check your network or try a less-loaded model. Contact Tetrate support if issues persist. | |
| 237 | + </Card> | |
| 238 | + <Card title="Configuration not loading" icon="file-lines" vertical> | |
| 239 | + Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published. | |
| 240 | + </Card> | |
| 241 | +</CardGroup> | |
| 242 | + | |
| 243 | +--- | |
| 244 | + | |
| 245 | +## Join the Community | |
| 246 | +Connect with Tetrate and other builders for help and discussion. | |
| 247 | + | |
| 248 | +<CardGroup cols={1}> | |
| 249 | + <Card title="Join the Tetrate Community" icon="slack" href="https://join.slack.com/t/tetrate-agent-router/shared_invite/zt-399tv7hjm-6YMXztGywTOQrMIolvEBNg"> | |
| 250 | +Get answers, insights, and best practices for secure, scalable infrastructure | |
| 251 | + </Card> | |
| 252 | +</CardGroup> |
modified docs/customize/model-providers/top-level/vertexai.mdx +19 −96
| @@ -1,41 +1,36 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Configure Vertex AI with Continue" |
| 3 | 3 | slug: ../vertexai |
| 4 | -description: "Configure Google Cloud's Vertex AI with Continue to access powerful models like Claude 3.5 Sonnet, Codestral, and text-embedding-004 for chat, autocomplete, and embeddings" | |
| 5 | 4 | sidebarTitle: "Vertex AI" |
| 6 | 5 | --- |
| 7 | 6 | |
| 8 | 7 | <Info> |
| 9 | - You need to enable the [Vertex AI | |
| 10 | - API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) | |
| 11 | - and set up the [Google Application Default | |
| 12 | - Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). | |
| 8 | + Enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) | |
| 9 | + and set up [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) | |
| 13 | 10 | </Info> |
| 14 | 11 | |
| 15 | -## How to Set Up Vertex AI Chat Models | |
| 16 | - | |
| 17 | -We recommend configuring **Claude 3.5 Sonnet** as your chat model. | |
| 12 | +## Configuration | |
| 18 | 13 | |
| 19 | 14 | <Tabs> |
| 20 | 15 | <Tab title="YAML"> |
| 21 | 16 | ```yaml title="config.yaml" |
| 22 | 17 | models: |
| 23 | - - name: Claude 3.5 Sonnet | |
| 18 | + - name: <MODEL_NAME> | |
| 24 | 19 | provider: vertexai |
| 25 | - model: claude-3-5-sonnet-20240620 | |
| 20 | + model: <MODEL_ID> | |
| 26 | 21 | env: |
| 27 | 22 | projectId: <PROJECT_ID> |
| 28 | 23 | region: us-east5 |
| 29 | 24 | ``` |
| 30 | 25 | </Tab> |
| 31 | - <Tab title="JSON"> | |
| 26 | + <Tab title="JSON (Deprecated)"> | |
| 32 | 27 | ```json title="config.json" |
| 33 | 28 | { |
| 34 | 29 | "models": [ |
| 35 | 30 | { |
| 36 | - "title": "Claude 3.5 Sonnet", | |
| 31 | + "title": "<MODEL_NAME>", | |
| 37 | 32 | "provider": "vertexai", |
| 38 | - "model": "claude-3-5-sonnet-20240620", | |
| 33 | + "model": "<MODEL_ID>", | |
| 39 | 34 | "projectId": "[PROJECT_ID]", |
| 40 | 35 | "region": "us-east5" |
| 41 | 36 | } |
| @@ -45,104 +40,32 @@ | ||
| 45 | 40 | </Tab> |
| 46 | 41 | </Tabs> |
| 47 | 42 | |
| 48 | -## How to Set Up Vertex AI Autocomplete Models | |
| 49 | - | |
| 50 | -We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. | |
| 51 | - | |
| 52 | -<Tabs> | |
| 53 | - <Tab title="YAML"> | |
| 54 | - ```yaml title="config.yaml" | |
| 55 | - models: | |
| 56 | - - name: Codestral (Vertex AI) | |
| 57 | - provider: vertexai | |
| 58 | - model: codestral | |
| 59 | - roles: | |
| 60 | - - autocomplete | |
| 61 | - env: | |
| 62 | - projectId: <PROJECT_ID> | |
| 63 | - region: us-central1 | |
| 64 | - | |
| 65 | - ``` | |
| 66 | - </Tab> | |
| 67 | - <Tab title="JSON"> | |
| 68 | - ```json title="config.json" | |
| 69 | - { | |
| 70 | - "tabAutocompleteModel": { | |
| 71 | - "title": "Codestral (Vertex AI)", | |
| 72 | - "provider": "vertexai", | |
| 73 | - "model": "codestral", | |
| 74 | - "projectId": "[PROJECT_ID]", | |
| 75 | - "region": "us-central1" | |
| 76 | - } | |
| 77 | - } | |
| 78 | - ``` | |
| 79 | - </Tab> | |
| 80 | -</Tabs> | |
| 81 | - | |
| 82 | -## How to Configure Vertex AI Embeddings Models | |
| 43 | +## How to Enable Vertex AI Express Mode | |
| 83 | 44 | |
| 84 | -We recommend configuring **text-embedding-004** as your embeddings model. | |
| 45 | +You can use Vertex AI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now. | |
| 85 | 46 | |
| 86 | 47 | <Tabs> |
| 87 | 48 | <Tab title="YAML"> |
| 88 | 49 | ```yaml title="config.yaml" |
| 89 | 50 | models: |
| 90 | - - name: Text Embedding-004 | |
| 51 | + - name: <MODEL_NAME> | |
| 91 | 52 | provider: vertexai |
| 92 | - model: text-embedding-004 | |
| 93 | - env: | |
| 94 | - projectId: <PROJECT_ID> | |
| 95 | - region: us-central1 | |
| 96 | - roles: | |
| 97 | - - embed | |
| 98 | - ``` | |
| 99 | - </Tab> | |
| 100 | - <Tab title="JSON"> | |
| 101 | - ```json title="config.json" | |
| 102 | - { | |
| 103 | - "embeddingsProvider": { | |
| 104 | - "provider": "vertexai", | |
| 105 | - "model": "text-embedding-004", | |
| 106 | - "projectId": "[PROJECT_ID]", | |
| 107 | - "region": "us-central1" | |
| 108 | - } | |
| 109 | - } | |
| 53 | + model: <MODEL_ID> | |
| 54 | + apiKey: <YOUR_GOOGLE_CLOUD_API_KEY> | |
| 110 | 55 | ``` |
| 111 | 56 | </Tab> |
| 112 | -</Tabs> | |
| 113 | - | |
| 114 | -## How to Configure Vertex AI Reranking Models | |
| 115 | - | |
| 116 | -Vertex AI currently does not offer any reranking models. | |
| 117 | - | |
| 118 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. | |
| 119 | - | |
| 120 | -## How to Enable Vertex AI Express Mode | |
| 121 | - | |
| 122 | -You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now. | |
| 123 | - | |
| 124 | -<Tabs groupId="config-example"> | |
| 125 | - <TabItem value="yaml" label="YAML"> | |
| 126 | - ```yaml title="config.yaml" | |
| 127 | - models: | |
| 128 | - - name: Gemini 2.5 Flash - VertexAI | |
| 129 | - provider: vertexai | |
| 130 | - model: gemini-2.5-flash | |
| 131 | - apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }} | |
| 132 | - ``` | |
| 133 | - </TabItem> | |
| 134 | - <TabItem value="json" label="JSON"> | |
| 57 | + <Tab title="JSON (Deprecated)"> | |
| 135 | 58 | ```json title="config.json" |
| 136 | 59 | { |
| 137 | 60 | "models": [ |
| 138 | 61 | { |
| 139 | - "title": "Gemini 2.5 Flash - VertexAI", | |
| 62 | + "title": "<MODEL_NAME>", | |
| 140 | 63 | "provider": "vertexai", |
| 141 | - "model": "gemini-2.5-flash", | |
| 142 | - "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]", | |
| 64 | + "model": "<MODEL_ID>", | |
| 65 | + "apiKey": "<YOUR_GOOGLE_CLOUD_API_KEY>", | |
| 143 | 66 | } |
| 144 | 67 | ] |
| 145 | 68 | } |
| 146 | 69 | ``` |
| 147 | - </TabItem> | |
| 148 | -</Tabs> | |
| 70 | + </Tab> | |
| 71 | +</Tabs> | |
| No newline at the end of the file |
deleted docs/customize/model-providers/top-level/xAI.mdx +0 −61
| @@ -1,61 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Configure xAI with Continue" | |
| 3 | -slug: ../xai | |
| 4 | -description: "Configure xAI's Grok 4 model with Continue for advanced chat capabilities, with easy API key setup from the xAI console" | |
| 5 | -sidebarTitle: "xAI" | |
| 6 | ---- | |
| 7 | - | |
| 8 | -<Info> | |
| 9 | - You can get an API key from the [xAI console](https://console.x.ai/) | |
| 10 | -</Info> | |
| 11 | - | |
| 12 | -## How to Set Up xAI Chat Models | |
| 13 | - | |
| 14 | -We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). | |
| 15 | - | |
| 16 | -<Tabs> | |
| 17 | - <Tab title="Config"> | |
| 18 | - Add the [xAI Grok 4 model block](https://hub.continue.dev/xai/grok-4) on the hub. | |
| 19 | - </Tab> | |
| 20 | - <Tab title="YAML"> | |
| 21 | - ```yaml title="config.yaml" | |
| 22 | - models: | |
| 23 | - - name: Grok 4 | |
| 24 | - provider: xAI | |
| 25 | - model: grok-4 | |
| 26 | - apiKey: <YOUR_XAI_API_KEY> | |
| 27 | - ``` | |
| 28 | - </Tab> | |
| 29 | - <Tab title="JSON"> | |
| 30 | - ```json title="config.json" | |
| 31 | - { | |
| 32 | - "models": [ | |
| 33 | - { | |
| 34 | - "title": "Grok 4", | |
| 35 | - "provider": "xAI", | |
| 36 | - "model": "grok-4", | |
| 37 | - "apiKey": "<YOUR_XAI_API_KEY>" | |
| 38 | - } | |
| 39 | - ] | |
| 40 | - } | |
| 41 | - ``` | |
| 42 | - </Tab> | |
| 43 | -</Tabs> | |
| 44 | - | |
| 45 | -## How to Set Up xAI Autocomplete Models | |
| 46 | - | |
| 47 | -xAI currently does not offer any autocomplete models. | |
| 48 | - | |
| 49 | -[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers. | |
| 50 | - | |
| 51 | -## How to Configure xAI Embeddings Models | |
| 52 | - | |
| 53 | -xAI currently does not offer any embeddings models. | |
| 54 | - | |
| 55 | -[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers. | |
| 56 | - | |
| 57 | -## How to Configure xAI Reranking Models | |
| 58 | - | |
| 59 | -xAI currently does not offer any reranking models. | |
| 60 | - | |
| 61 | -[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. |
modified docs/customize/model-roles.mdx +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | title: "Model roles" |
| 3 | 3 | sidebarTitle: Overview |
| 4 | 4 | icon: "circle-info" |
| 5 | -description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding assistant's capabilities" | |
| 5 | +description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding agent's capabilities" | |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | 8 | <CardGroup> |
modified docs/customize/model-roles/00-intro.mdx +5 −1
| @@ -17,9 +17,13 @@ | ||
| 17 | 17 | |
| 18 | 18 | These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](/reference#models) for more details. |
| 19 | 19 | |
| 20 | +<Info> | |
| 21 | + For recommendations on which models work best for each role, see our [comprehensive model recommendations](/customization/models#recommended-models). | |
| 22 | +</Info> | |
| 23 | + | |
| 20 | 24 | ## Selecting model roles |
| 21 | 25 | |
| 22 | -You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. | |
| 26 | +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. | |
| 23 | 27 | |
| 24 | 28 |  |
| 25 | 29 |
modified docs/customize/model-roles/apply.mdx +4 −0
| @@ -9,6 +9,10 @@ | ||
| 9 | 9 | |
| 10 | 10 | ## Recommended Apply models |
| 11 | 11 | |
| 12 | +<Info> | |
| 13 | + For the latest Apply model recommendations, see our [comprehensive model recommendations](/customization/models#recommended-models). | |
| 14 | +</Info> | |
| 15 | + | |
| 12 | 16 | We recommend [Morph Fast Apply](https://morphllm.com) or [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can sign up for Morph's free tier [here](https://morphllm.com/dashboard) or get a Relace API key [here](https://app.relace.ai/settings/api-keys). |
| 13 | 17 | |
| 14 | 18 | However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku. |