Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into save-chat
Changeset93be46abab09d83a95f572d18b9b27dcaeaa350e220a6cb0f2dafd09e8e7266f
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-22 13:45 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-22 13:45 -07:00
Parents00c2dcd72a7c, 23e5f6ffdfa7

Browse the files at this changeset

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 @@
5252 // TODO: add info for openai, ollama, etc
5353
5454 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.
5656 Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
5757
5858 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 @@
2929 - **Continue version**: v0.9.4
3030 - **IDE version**: VSCode 1.85.1
3131 - Model: Claude Sonnet 3.5
32- - Assistant configuration
32+ - Agent configuration
3333 value: |
3434 - OS:
3535 - Continue version:
@@ -39,7 +39,7 @@
3939 ```yaml
4040
4141 ```
42- OR link to assistant in Continue hub:
42+ OR link to agent in Continue hub:
4343 render: Markdown
4444 validations:
4545 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 @@
4444 - name: Setup FFmpeg
4545 uses: AnimMouse/setup-ffmpeg@v1
4646 with:
47+ version: 7.1
4748 token: ${{ inputs.github-token }}
4849
4950 - name: Setup Gradle
@@ -93,13 +94,20 @@
9394 path: binary/node_modules
9495 key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
9596
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+
96104 - name: Build the binaries
97105 shell: bash
98106 run: |
99107 cd binary
100108 npm run build
101109
102- - name: Start test IDE
110+ - name: Run tests
103111 shell: bash
104112 run: |
105113 cd extensions/intellij
@@ -107,35 +115,29 @@
107115 Xvfb -ac :99 -screen 0 1920x1080x24 &
108116 sleep 10
109117 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
125119
126120 - name: Move video
127121 if: ${{ failure() }}
128122 shell: bash
129123 run: |
130124 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
132130
133131 - name: Copy logs
134132 if: ${{ failure() }}
135133 shell: bash
136134 run: |
137135 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
139141
140142 - name: Save fails report
141143 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"
33 inputs:
44 test_file:
5- description: 'E2E test file to run'
5+ description: "E2E test file to run"
66 required: true
77 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)"
99 required: true
1010 ssh_key:
11- description: 'SSH private key for testing'
11+ description: "SSH private key for testing"
1212 required: false
1313 ssh_host:
14- description: 'SSH host for testing'
14+ description: "SSH host for testing"
1515 required: false
1616 is_fork:
17- description: 'Whether this is a fork (affects SSH tests)'
17+ description: "Whether this is a fork (affects SSH tests)"
1818 required: false
19- default: 'false'
19+ default: "false"
2020
2121 runs:
22- using: 'composite'
22+ using: "composite"
2323 steps:
2424 - uses: actions/setup-node@v4
2525 with:
@@ -58,6 +58,7 @@
5858 cd core
5959 npm ci
6060 cd ../extensions/vscode
61+ npm ci
6162 npm run e2e:ci:download
6263 else
6364 cd core
@@ -131,4 +132,4 @@
131132 uses: actions/upload-artifact@v4
132133 with:
133134 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 @@
2727 path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
2828 branch: cla-signatures
2929 # 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
3131 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 @@
3636 else
3737 echo "❌ PR title does not follow conventional commit format"
3838 echo "valid=false" >> $GITHUB_OUTPUT
39- exit 1
39+ # Don't exit with failure - just mark as invalid for comment
4040 fi
4141
4242 - name: Add PR title guidance comment
4343 if: always() && steps.pr-title-check.outputs.valid == 'false'
44- uses: actions/github-script@v7
44+ uses: actions/github-script@v8
4545 with:
4646 script: |
4747 const { data: comments } = await github.rest.issues.listComments({
@@ -104,7 +104,7 @@
104104 uses: actions/checkout@v5
105105
106106 - name: Setup Node.js
107- uses: actions/setup-node@v4
107+ uses: actions/setup-node@v5
108108 with:
109109 node-version-file: ".nvmrc"
110110 cache: "npm"
modified .github/workflows/continue-detailed-review.yaml +1 −1
@@ -18,7 +18,7 @@
1818 timeout-minutes: 10
1919 steps:
2020 - name: Run Detailed PR Review
21- uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070
21+ uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52
2222 with:
2323 continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
2424 continue-org: continuedev
modified .github/workflows/continue-general-review.yaml +1 −1
@@ -18,7 +18,7 @@
1818 timeout-minutes: 10
1919 steps:
2020 - name: Run Continue PR Review Action
21- uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070
21+ uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52
2222 with:
2323 continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
2424 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 @@
120120
121121 # # Set up Java environment for the next steps
122122 - name: Setup Java
123- uses: actions/setup-java@v4
123+ uses: actions/setup-java@v5
124124 with:
125125 distribution: zulu
126126 java-version: 17
@@ -152,7 +152,7 @@
152152
153153 # # Setup Node.js
154154 - name: Use Node.js from .nvmrc
155- uses: actions/setup-node@v4
155+ uses: actions/setup-node@v5
156156 with:
157157 node-version-file: ".nvmrc"
158158
@@ -189,6 +189,8 @@
189189 cd ../../gui
190190 npm ci
191191 npm run build
192+ env:
193+ NODE_OPTIONS: "--max-old-space-size=8192"
192194
193195 # Run prepackage.js script
194196 - name: Run prepackage script
@@ -255,6 +257,7 @@
255257 # Publish the plugin to JetBrains Marketplace
256258 - name: Publish EAP Plugin
257259 if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true')
260+ continue-on-error: true
258261 env:
259262 PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
260263 CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@@ -265,6 +268,7 @@
265268
266269 - name: Publish Stable Plugin
267270 if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true')
271+ continue-on-error: true
268272 env:
269273 PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
270274 CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@@ -366,7 +370,7 @@
366370
367371 # 2. Install npm dependencies
368372 - name: Use Node.js from .nvmrc
369- uses: actions/setup-node@v4
373+ uses: actions/setup-node@v5
370374 with:
371375 node-version-file: ".nvmrc"
372376
@@ -433,7 +437,7 @@
433437
434438 # Set up Java environment for the next steps
435439 - name: Setup Java
436- uses: actions/setup-java@v4
440+ uses: actions/setup-java@v5
437441 with:
438442 distribution: zulu
439443 java-version: 17
@@ -456,12 +460,6 @@
456460 name: tests-result
457461 path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
458462
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-
465463 # Run Qodana inspections and provide report
466464 inspectCode:
467465 if: false
@@ -486,7 +484,7 @@
486484
487485 # Set up Java environment for the next steps
488486 - name: Setup Java
489- uses: actions/setup-java@v4
487+ uses: actions/setup-java@v5
490488 with:
491489 distribution: zulu
492490 java-version: 17
@@ -517,7 +515,7 @@
517515
518516 # Set up Java environment for the next steps
519517 - name: Setup Java
520- uses: actions/setup-java@v4
518+ uses: actions/setup-java@v5
521519 with:
522520 distribution: zulu
523521 java-version: 17
modified .github/workflows/label-merged-prs.yml +1 −1
@@ -44,7 +44,7 @@
4444
4545 - name: Determine and apply tier label
4646 if: steps.check-author.outputs.should_label == 'true'
47- uses: actions/github-script@v7
47+ uses: actions/github-script@v8
4848 with:
4949 script: |
5050 const pr = context.payload.pull_request;
modified .github/workflows/main-build.yaml +9 −7
@@ -24,17 +24,19 @@
2424
2525 - name: Get merged PR number
2626 id: get-pr
27+ env:
28+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
2729 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"
3133
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')
3437
3538 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"
3840 exit 1
3941 fi
4042
modified .github/workflows/main.yaml +3 −3
@@ -9,7 +9,7 @@
99 publish_build:
1010 description: "Whether or not to publish the built extension to the VS Code marketplace"
1111 required: true
12- default: false
12+ default: "false"
1313
1414 jobs:
1515 check_release_name:
@@ -20,7 +20,7 @@
2020 - id: check
2121 working-directory: .
2222 run: |
23- if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
23+ if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
2424 echo "should_run=true" >> $GITHUB_OUTPUT
2525 else
2626 echo "should_run=false" >> $GITHUB_OUTPUT
@@ -70,7 +70,7 @@
7070 with:
7171 fetch-depth: 0
7272
73- - uses: actions/setup-node@v4
73+ - uses: actions/setup-node@v5
7474 with:
7575 node-version-file: ".nvmrc"
7676
modified .github/workflows/pr-checks.yaml +36 −5
@@ -11,11 +11,19 @@
1111 - main
1212
1313 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+
1422 prettier-check:
1523 runs-on: ubuntu-latest
1624 steps:
1725 - uses: actions/checkout@v5
18- - uses: actions/setup-node@v4
26+ - uses: actions/setup-node@v5
1927 with:
2028 node-version-file: ".nvmrc"
2129
@@ -36,6 +44,8 @@
3644 runs-on: ubuntu-latest
3745 steps:
3846 - uses: actions/checkout@v5
47+ with:
48+ fetch-depth: 0 # Needed for git diff to work
3949 - name: Setup packages
4050 uses: ./.github/actions/setup-packages
4151 - name: Setup core component
@@ -44,6 +54,13 @@
4454 component: core
4555 include-root: true
4656
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+
4764 - name: Type check and lint
4865 run: |
4966 cd core
@@ -58,7 +75,7 @@
5875 npm test
5976 npm run vitest
6077 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 }}
6279 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
6380 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
6481 GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@@ -67,6 +84,9 @@
6784 AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
6885 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
6986 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 }}
7090
7191 gui-checks:
7292 runs-on: ubuntu-latest
@@ -172,16 +192,25 @@
172192 package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
173193 steps:
174194 - uses: actions/checkout@v5
195+ with:
196+ fetch-depth: 0 # Needed for git diff to work
175197 - name: Setup packages
176198 uses: ./.github/actions/setup-packages
177199
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+
178207 - name: Test and check ${{ matrix.package }}
179208 run: |
180209 cd packages/${{ matrix.package }}
181210 npm ci
182211 npm test
183212 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 }}
185214 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
186215 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
187216 GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@@ -191,6 +220,8 @@
191220 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
192221 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
193222 VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
223+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
224+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
194225
195226 vscode-get-test-file-matrix:
196227 runs-on: ubuntu-latest
@@ -198,7 +229,7 @@
198229 test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
199230 steps:
200231 - uses: actions/checkout@v5
201- - uses: actions/setup-node@v4
232+ - uses: actions/setup-node@v5
202233 with:
203234 node-version-file: ".nvmrc"
204235
@@ -316,7 +347,7 @@
316347 runs-on: ubuntu-latest
317348 steps:
318349 - uses: actions/checkout@v5
319- - uses: actions/setup-node@v4
350+ - uses: actions/setup-node@v5
320351 with:
321352 node-version: 20
322353
modified .github/workflows/preview.yaml +4 −4
@@ -9,7 +9,7 @@
99 publish_build:
1010 description: "Whether or not to publish the built extension to the VS Code marketplace"
1111 required: true
12- default: false
12+ default: "false"
1313
1414 jobs:
1515 check_release_name:
@@ -20,7 +20,7 @@
2020 - id: check
2121 working-directory: .
2222 run: |
23- if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
23+ if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then
2424 echo "should_run=true" >> $GITHUB_OUTPUT
2525 else
2626 echo "should_run=false" >> $GITHUB_OUTPUT
@@ -70,7 +70,7 @@
7070 with:
7171 fetch-depth: 0
7272
73- - uses: actions/setup-node@v4
73+ - uses: actions/setup-node@v5
7474 with:
7575 node-version-file: ".nvmrc"
7676
@@ -165,7 +165,7 @@
165165
166166 # 4. Create PR with version bump
167167 - name: Setup Node.js
168- uses: actions/setup-node@v4
168+ uses: actions/setup-node@v5
169169 with:
170170 node-version-file: ".nvmrc"
171171
modified .github/workflows/release-config-yaml.yml +2 −0
@@ -32,3 +32,5 @@
3232 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
3333 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
3434 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 @@
3232 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
3333 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
3434 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 @@
2323 AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
2424 AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
2525 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 @@
3232 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
3333 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
3434 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 @@
3232 required: false
3333 VOYAGE_API_KEY:
3434 required: false
35+ RELACE_API_KEY:
36+ required: false
37+ INCEPTION_API_KEY:
38+ required: false
3539
3640 permissions:
3741 contents: write
@@ -51,8 +55,11 @@
5155 with:
5256 fetch-depth: 0
5357
58+ - name: Setup packages
59+ uses: ./.github/actions/setup-packages
60+
5461 - name: Use Node.js from .nvmrc
55- uses: actions/setup-node@v4
62+ uses: actions/setup-node@v5
5663 with:
5764 node-version-file: ".nvmrc"
5865
@@ -74,6 +81,8 @@
7481 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
7582 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
7683 VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
84+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
85+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
7786
7887 - name: Release
7988 env:
modified .github/workflows/similar-issues.yml +3 −3
@@ -31,7 +31,7 @@
3131 path: deja-view
3232
3333 - name: Setup Python
34- uses: actions/setup-python@v5
34+ uses: actions/setup-python@v6
3535 with:
3636 python-version: "3.11"
3737
@@ -190,7 +190,7 @@
190190 echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
191191
192192 - name: Comment with analysis
193- uses: actions/github-script@v7
193+ uses: actions/github-script@v8
194194 with:
195195 script: |
196196 let comment = '';
@@ -307,7 +307,7 @@
307307
308308 - name: Add labels
309309 if: github.event_name == 'issues'
310- uses: actions/github-script@v7
310+ uses: actions/github-script@v8
311311 with:
312312 script: |
313313 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 @@
1010 pull-requests: write
1111 runs-on: ubuntu-latest
1212 steps:
13- - uses: actions/stale@v9
13+ - uses: actions/stale@v10
1414 with:
1515 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!"
1616 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 @@
1414 - name: Checkout sources
1515 uses: actions/checkout@v5
1616 - name: Setup Java
17- uses: actions/setup-java@v4
17+ uses: actions/setup-java@v5
1818 with:
1919 distribution: "temurin"
2020 java-version: 17
modified .github/workflows/vscode-version-bump.yml +1 −1
@@ -21,7 +21,7 @@
2121 gh auth login --with-token <<< "${{ github.token }}"
2222
2323 - name: Use Node.js from .nvmrc
24- uses: actions/setup-node@v4
24+ uses: actions/setup-node@v5
2525 with:
2626 node-version-file: ".nvmrc"
2727
modified .gitignore +2 −0
@@ -158,6 +158,7 @@
158158 **/.idea/shelf/
159159 **/.idea/inspectionProfiles/Project_Default.xml
160160 **/.idea/php.xml
161+**/.idea/kotlinc.xml
161162
162163
163164 extensions/intellij/bin
@@ -170,4 +171,5 @@
170171
171172 .continuerules
172173 **/.continue/assistants/
174+**/.continue/agents/
173175 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 @@
2323 **/CODEOWNERS
2424 core/vendor
2525 coverage
26-e2e
26+# e2e
2727 packages/continue-sdk
No newline at the end of the file
modified .vscode/launch.json +44 −1
@@ -18,7 +18,7 @@
1818 ],
1919 "pauseForSourceMap": false,
2020 "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
21- "preLaunchTask": "vscode-extension:build-with-packages",
21+ "preLaunchTask": "vscode-extension:build-without-watch",
2222 "env": {
2323 // "CONTROL_PLANE_ENV": "local",
2424 "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
@@ -131,6 +131,49 @@
131131 "env": {
132132 "NODE_OPTIONS": "--experimental-vm-modules"
133133 }
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"
134177 }
135178 ]
136179 }
modified .vscode/settings.json +3 −1
@@ -42,7 +42,9 @@
4242 "extensions/vscode/e2e/_output": true,
4343 "extensions/vscode/e2e/storage": true,
4444 "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
4648 // "sync/**": true
4749 },
4850 "editor.formatOnSave": true,
modified .vscode/tasks.json +116 −0
@@ -174,6 +174,25 @@
174174 }
175175 ]
176176 },
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+ },
177196 {
178197 "label": "binary:esbuild",
179198 "type": "shell",
@@ -311,6 +330,103 @@
311330 "close": true,
312331 "focus": false
313332 }
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+ }
314430 }
315431 ]
316432 }
modified CONTRIBUTING.md +3 −3
@@ -176,9 +176,9 @@
176176 ### Our Git Workflow
177177
178178 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
180180 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
182182 workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
183183 extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
184184 is well explained by <http://releaseflow.org>.
@@ -288,4 +288,4 @@
288288 I have read the CLA Document and I hereby sign the CLA
289289 ```
290290
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 @@
3535
3636 ## Agent
3737
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
3939
4040 ![agent](docs/images/agent.gif)
4141
4242 ## Chat
4343
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
4545
4646 ![chat](docs/images/chat.gif)
4747
4848 ## Edit
4949
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
5151
5252 ![edit](docs/images/edit.gif)
5353
5454 ## Autocomplete
5555
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
5757
5858 ![autocomplete](docs/images/autocomplete.gif)
5959
modified actions/README.md +1 −1
@@ -219,7 +219,7 @@
219219 Example:
220220
221221 ```yaml
222-uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266
222+uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
223223 ```
224224
225225 ## Troubleshooting
modified actions/detailed-review/action.yml +119 −35
@@ -29,12 +29,17 @@
2929 SHOULD_RUN="false"
3030
3131 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"
3635 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
3843 fi
3944 elif [ "${{ github.event_name }}" = "issue_comment" ]; then
4045 # Check if it's a PR comment with the trigger phrase
@@ -68,7 +73,7 @@
6873 - name: Install Continue CLI
6974 if: env.SKIP_REVIEW != 'true'
7075 shell: bash
71- run: npm install -g @continuedev/cli@1.4.25
76+ run: npm install -g @continuedev/cli@1.4.30
7277
7378 - name: Build Inline Review Prompt
7479 if: env.SKIP_REVIEW != 'true'
@@ -189,6 +194,21 @@
189194 exit 1
190195 fi
191196
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+
192212 # Log the prompt for debugging
193213 echo "===== START REVIEW PROMPT ====="
194214 head -n 50 inline_review_prompt.txt
@@ -196,23 +216,67 @@
196216 tail -n 20 inline_review_prompt.txt
197217 echo "===== END REVIEW PROMPT ====="
198218
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
205235
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
210279 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
216280
217281 - name: Post Inline Review Comments
218282 if: env.SKIP_REVIEW != 'true'
@@ -268,7 +332,23 @@
268332 console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
269333 }
270334
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 => ({
272352 path: comment.path,
273353 position: comment.position,
274354 body: comment.body
@@ -283,12 +363,19 @@
283363 // Create the review
284364 if (comments.length > 0) {
285365 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+
286373 await github.rest.pulls.createReview({
287374 owner: context.repo.owner,
288375 repo: context.repo.repo,
289376 pull_number: prNumber,
290377 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,
292379 event: 'COMMENT',
293380 comments: comments
294381 });
@@ -310,22 +397,19 @@
310397 }
311398 } else {
312399 // 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+
313408 await github.rest.issues.createComment({
314409 issue_number: prNumber,
315410 owner: context.repo.owner,
316411 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
329413 });
330414 }
331415
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."
44
55 inputs:
66 continue-api-key:
7- description: 'API key for Continue service'
7+ description: "API key for Continue service"
88 required: true
99 continue-org:
10- description: 'Organization for Continue config'
10+ description: "Organization for Continue config"
1111 required: true
1212 continue-config:
1313 description: 'Config path to use (e.g., "myorg/review-bot")'
1414 required: true
1515
1616 runs:
17- using: 'composite'
17+ using: "composite"
1818 steps:
1919 - name: Checkout Repository
2020 uses: actions/checkout@v4
@@ -27,14 +27,19 @@
2727 run: |
2828 # Check if this action should run based on event type and user permissions
2929 SHOULD_RUN="false"
30-
30+
3131 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"
3635 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
3843 fi
3944 elif [ "${{ github.event_name }}" = "issue_comment" ]; then
4045 # Check if it's a PR comment with the trigger phrase
@@ -51,7 +56,7 @@
5156 else
5257 echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
5358 fi
54-
59+
5560 echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
5661
5762 - name: Setup Node.js
@@ -63,7 +68,7 @@
6368 - name: Install Continue CLI
6469 if: env.SHOULD_RUN == 'true'
6570 shell: bash
66- run: npm install -g @continuedev/cli@1.4.25
71+ run: npm install -g @continuedev/cli@1.4.30
6772
6873 - name: Build PR Review Prompt
6974 if: env.SHOULD_RUN == 'true'
@@ -152,19 +157,84 @@
152157 echo "=================================="
153158 echo ""
154159
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+
155178 # Validate inputs to prevent command injection
156179 if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
157180 echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
158181 exit 1
159182 fi
160-
183+
161184 if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
162185 echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
163186 exit 1
164187 fi
165188
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
168238
169239 - name: Upload Review Results
170240 if: env.SHOULD_RUN == 'true' && always()
@@ -224,5 +294,5 @@
224294 }
225295
226296 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 @@
3939 "pkg": "^5.8.1",
4040 "rimraf": "^5.0.7",
4141 "ts-jest": "^29.1.4",
42- "typescript": "^5.3.3"
42+ "typescript": "^5.6.3"
4343 },
4444 "dependencies": {
4545 "@octokit/rest": "^20.0.2",
modified core/autocomplete/CompletionProvider.ts +6 −7
@@ -6,12 +6,13 @@
66 import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
77 import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
88
9+import { isSecurityConcern } from "../indexing/ignore.js";
910 import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
1011 import { CompletionStreamer } from "./generation/CompletionStreamer.js";
1112 import { postprocessCompletion } from "./postprocessing/index.js";
1213 import { shouldPrefilter } from "./prefiltering/index.js";
13-import { renderPromptWithTokenLimit } from "./templating/index.js";
1414 import { getAllSnippetsWithoutRace } from "./snippets/index.js";
15+import { renderPromptWithTokenLimit } from "./templating/index.js";
1516 import { GetLspDefinitionsFunction } from "./types.js";
1617 import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
1718 import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
@@ -150,6 +151,10 @@
150151 return undefined;
151152 }
152153
154+ if (isSecurityConcern(input.filepath)) {
155+ return undefined;
156+ }
157+
153158 const options = await this._getAutocompleteOptions(llm);
154159
155160 // Debounce
@@ -210,12 +215,6 @@
210215 const multiline =
211216 !helper.options.transform || shouldCompleteMultiline(helper);
212217
213- const rawGeneration = await llm.complete(
214- prompt,
215- token,
216- completionOptions,
217- );
218-
219218 const completionStream =
220219 this.completionStreamer.streamCompletionWithFilters(
221220 token,
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +7 −2
@@ -166,8 +166,13 @@
166166 export const CODE_STOP_BLOCK = "[/CODE]";
167167 export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
168168 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|>"];
171176 export const LINES_TO_REMOVE_BEFORE_START = [
172177 "<COMPLETION>",
173178 "[CODE]",
modified core/autocomplete/prefiltering/index.ts +1 −1
@@ -4,7 +4,7 @@
44 import {
55 getGlobalContinueIgArray,
66 getWorkspaceContinueIgArray,
7-} from "../../indexing/ignore";
7+} from "../../indexing/continueignore";
88 import { getConfigJsonPath } from "../../util/paths";
99 import { findUriInDirs } from "../../util/uri";
1010 import { HelperVars } from "../util/HelperVars";
modified core/codeRenderer/CodeRenderer.ts +76 −51
@@ -19,7 +19,7 @@
1919 getSingletonHighlighter,
2020 Highlighter,
2121 } from "shiki";
22-import { DiffLine } from "..";
22+import { DiffChar, DiffLine } from "..";
2323 import { escapeForSVG, kebabOfThemeStr } from "../util/text";
2424
2525 interface CodeRendererOptions {
@@ -228,6 +228,7 @@
228228 options: ConversionOptions,
229229 currLineOffsetFromTop: number,
230230 newDiffLines: DiffLine[],
231+ newDiffChars: DiffChar[],
231232 ): Promise<Buffer> {
232233 const strokeWidth = 1;
233234 const highlightedCodeHtml = await this.highlightCode(
@@ -236,13 +237,14 @@
236237 currLineOffsetFromTop,
237238 newDiffLines,
238239 );
239- // console.log(highlightedCodeHtml);
240240
241241 const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
242242 highlightedCodeHtml,
243243 options,
244+ newDiffChars,
244245 );
245246 const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
247+ const borderColor = "#6b6b6b";
246248
247249 const lines = code.split("\n");
248250 const actualHeight = lines.length * options.lineHeight;
@@ -256,12 +258,11 @@
256258 }
257259 </style>
258260 <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" />
260262 ${lineBackgrounds}
261263 ${guts}
262264 </g>
263265 </svg>`;
264- // console.log(svg);
265266
266267 return Buffer.from(svg, "utf8");
267268 }
@@ -269,11 +270,56 @@
269270 convertShikiHtmlToSvgGut(
270271 shikiHtml: string,
271272 options: ConversionOptions,
273+ diffChars: DiffChar[],
272274 ): { guts: string; lineBackgrounds: string } {
273275 const dom = new JSDOM(shikiHtml);
274276 const document = dom.window.document;
275277
276278 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+ });
277323 const svgLines = lines.map((line, index) => {
278324 const spans = Array.from(line.childNodes)
279325 .map((node) => {
@@ -309,60 +355,37 @@
309355 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>`;
310356 });
311357
358+ const estimatedCharWidth = options.fontSize * 0.6;
359+ const additionFill = "rgba(40, 167, 69, 0.25)";
360+
312361 const lineBackgrounds = lines
313362 .map((line, index) => {
314363 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-
321364 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+ );
340372 }
341373
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");
365387 })
388+ .filter((bg) => bg.length > 0)
366389 .join("\n");
367390
368391 return {
@@ -394,6 +417,7 @@
394417 options: ConversionOptions,
395418 currLineOffsetFromTop: number,
396419 newDiffLines: DiffLine[],
420+ newDiffChars: DiffChar[],
397421 ): Promise<DataUri> {
398422 switch (options.imageType) {
399423 // case "png":
@@ -413,6 +437,7 @@
413437 options,
414438 currLineOffsetFromTop,
415439 newDiffLines,
440+ newDiffChars,
416441 );
417442 return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
418443 }
modified core/commands/slash/built-in-legacy/onboard.ts +2 −5
@@ -1,11 +1,8 @@
11 import ignore from "ignore";
22
33 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";
96 import { renderChatMessage } from "../../../util/messageContent";
107 import {
118 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 @@
2121 import { Logger } from "../util/Logger.js";
2222 import { Telemetry } from "../util/posthog.js";
2323 import {
24- ASSISTANTS,
2524 getAllDotContinueDefinitionFiles,
2625 LoadAssistantFilesOptions,
2726 } from "./loadLocalAssistants.js";
@@ -60,27 +59,17 @@
6059
6160 constructor(
6261 private readonly ide: IDE,
63- private ideSettingsPromise: Promise<IdeSettings>,
6462 private llmLogger: ILLMLogger,
65- sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
63+ initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
6664 ) {
67- this.ide = ide;
68- this.ideSettingsPromise = ideSettingsPromise;
69-
7065 this.controlPlaneClient = new ControlPlaneClient(
71- sessionInfoPromise,
72- ideSettingsPromise,
73- this.ide.getIdeInfo(),
66+ initialSessionInfoPromise,
67+ this.ide,
7468 );
7569
7670 // This profile manager will always be available
7771 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),
8473 this.ide,
8574 );
8675
@@ -98,6 +87,7 @@
9887 }
9988
10089 private workspaceDirs: string[] | null = null;
90+
10191 async getWorkspaceId() {
10292 if (!this.workspaceDirs) {
10393 this.workspaceDirs = await this.ide.getWorkspaceDirs();
@@ -114,6 +104,13 @@
114104 const signal = this.cascadeAbortController.signal;
115105 this.workspaceDirs = null; // forces workspace dirs reload
116106
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+
117114 try {
118115 const { orgs, errors } = await this.getOrgs();
119116
@@ -203,6 +200,8 @@
203200 message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
204201 });
205202 }
203+ } else {
204+ PolicySingleton.getInstance().policy = null;
206205 }
207206 // Load local org if not signed in or hub orgs fail
208207 try {
@@ -247,7 +246,6 @@
247246 versionSlug: assistant.configResult.config?.version ?? "latest",
248247 controlPlaneClient: this.controlPlaneClient,
249248 ide: this.ide,
250- ideSettingsPromise: this.ideSettingsPromise,
251249 llmLogger: this.llmLogger,
252250 rawYaml: assistant.rawYaml,
253251 orgScopeId: orgScopeId,
@@ -339,7 +337,7 @@
339337
340338 async getLocalProfiles(options: LoadAssistantFilesOptions) {
341339 /**
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
343341 */
344342
345343 // Local customization disabled for on-premise deployments
@@ -358,12 +356,16 @@
358356 const assistantFiles = await getAllDotContinueDefinitionFiles(
359357 this.ide,
360358 options,
361- ASSISTANTS,
359+ "assistants",
360+ );
361+ const agentFiles = await getAllDotContinueDefinitionFiles(
362+ this.ide,
363+ options,
364+ "agents",
362365 );
363- const profiles = assistantFiles.map((assistant) => {
366+ const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
364367 return new LocalProfileLoader(
365368 this.ide,
366- this.ideSettingsPromise,
367369 this.controlPlaneClient,
368370 this.llmLogger,
369371 assistant,
@@ -388,7 +390,6 @@
388390
389391 // Ide settings change: refresh session and cascade refresh from the top
390392 async updateIdeSettings(ideSettings: IdeSettings) {
391- this.ideSettingsPromise = Promise.resolve(ideSettings);
392393 this.abortCascade();
393394 await this.cascadeInit("IDE settings update");
394395 }
@@ -426,8 +427,7 @@
426427 if (reload) {
427428 this.controlPlaneClient = new ControlPlaneClient(
428429 Promise.resolve(sessionInfo),
429- this.ideSettingsPromise,
430- this.ide.getIdeInfo(),
430+ this.ide,
431431 );
432432 this.abortCascade();
433433 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 @@
11 import { ConfigYaml } from "@continuedev/config-yaml";
22
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-
233 export const defaultConfig: ConfigYaml = {
24- name: "Local Assistant",
4+ name: "Local Agent",
255 version: "1.0.0",
266 schema: "v1",
277 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,
378 };
modified core/config/load.ts +43 −60
@@ -19,7 +19,6 @@
1919 ContinueRcJson,
2020 CustomContextProvider,
2121 EmbeddingsProviderDescription,
22- IContextProvider,
2322 IDE,
2423 IdeInfo,
2524 IdeSettings,
@@ -36,10 +35,6 @@
3635 import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
3736 import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
3837 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";
4338 import { useHub } from "../control-plane/env";
4439 import { BaseLLM } from "../llm";
4540 import { LLMClasses, llmFromDescription } from "../llm/llms";
@@ -62,9 +57,12 @@
6257 } from "../util/paths";
6358 import { localPathToUri } from "../util/pathToUri";
6459
65-import { getToolsForIde } from "../tools";
60+import { PolicySingleton } from "../control-plane/PolicySingleton";
61+import CustomContextProviderClass from "../context/providers/CustomContextProvider";
62+import { getBaseToolDefinitions } from "../tools";
6663 import { resolveRelativePathInDir } from "../util/ideUtils";
6764 import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
65+import { loadConfigContextProviders } from "./loadContextProviders";
6866 import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
6967 import {
7068 getModelByRole,
@@ -217,8 +215,8 @@
217215 // Prepare models
218216 for (const model of models) {
219217 model.requestOptions = {
220- ...model.requestOptions,
221218 ...config.requestOptions,
219+ ...model.requestOptions,
222220 };
223221 if (roles !== undefined) {
224222 model.roles = model.roles ?? roles;
@@ -229,7 +227,7 @@
229227 export function isContextProviderWithParams(
230228 contextProvider: CustomContextProvider | ContextProviderWithParams,
231229 ): contextProvider is ContextProviderWithParams {
232- return (contextProvider as ContextProviderWithParams).name !== undefined;
230+ return "name" in contextProvider && !!contextProvider.name;
233231 }
234232
235233 /** Only difference between intermediate and final configs is the `models` array */
@@ -285,6 +283,7 @@
285283 ...desc,
286284 model: modelName,
287285 title: modelName,
286+ isFromAutoDetect: true,
288287 },
289288 ide.readFile.bind(ide),
290289 getUriFromPath,
@@ -322,6 +321,7 @@
322321 ...desc.options,
323322 model: modelName,
324323 logger: llmLogger,
324+ isFromAutoDetect: true,
325325 },
326326 }),
327327 );
@@ -386,50 +386,25 @@
386386
387387 applyRequestOptionsToModels(tabAutocompleteModels, config);
388388
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+ );
427401
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));
431405 }
432406 }
407+ errors.push(...contextErrors);
433408
434409 // Embeddings Provider
435410 function getEmbeddingsILLM(
@@ -526,7 +501,7 @@
526501 const continueConfig: ContinueConfig = {
527502 ...config,
528503 contextProviders,
529- tools: await getToolsForIde(ide),
504+ tools: getBaseToolDefinitions(),
530505 mcpServerStatuses: [],
531506 slashCommands: [],
532507 modelsByRole: {
@@ -570,16 +545,23 @@
570545
571546 // Trigger MCP server refreshes (Config is reloaded again once connected!)
572547 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+ }
583565
584566 // Handle experimental modelRole config values for apply and edit
585567 const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
@@ -654,6 +636,7 @@
654636 apiKeyLocation: llm.apiKeyLocation,
655637 envSecretLocations: llm.envSecretLocations,
656638 sourceFile: llm.sourceFile,
639+ isFromAutoDetect: llm.isFromAutoDetect,
657640 };
658641 }
659642
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 @@
1010 import { localPathToUri } from "../util/pathToUri";
1111 import { joinPathsToUri } from "../util/uri";
1212
13-export const ASSISTANTS = "assistants";
14-export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
15-
1613 export function isLocalDefinitionFile(uri: string): boolean {
1714 if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
1815 return false;
1916 }
2017
2118 const normalizedUri = URI.normalize(uri);
22- return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
19+ return (
20+ normalizedUri.includes(`/.continue/agents/`) ||
21+ normalizedUri.includes(`/.continue/assistants/`)
22+ );
2323 }
2424
2525 async function getDefinitionFilesInDir(
@@ -35,7 +35,11 @@
3535 }
3636
3737 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+ )
3943 .add(DEFAULT_IGNORE_DIRS);
4044
4145 const uris = await walkDir(dir, ide, {
modified core/config/loadLocalAssistants.vitest.ts +263 −9
@@ -6,7 +6,7 @@
66 getAllDotContinueDefinitionFiles,
77 LoadAssistantFilesOptions,
88 } from "./loadLocalAssistants";
9-describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
9+describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", () => {
1010 beforeEach(() => {
1111 setUpTestDir();
1212 walkDirCache.invalidate();
@@ -18,6 +18,8 @@
1818 [".continue/assistants/assistant2.yml", "yaml content 2"],
1919 [".continue/assistants/assistant3.md", "markdown content 1"],
2020 [".continue/assistants/assistant4.txt", "txt content"],
21+ [".continue/assistants/config.yaml", "txt content"],
22+ [".continue/assistants/config.yml", "txt content"],
2123 ]);
2224 });
2325
@@ -38,9 +40,14 @@
3840 options,
3941 "assistants",
4042 );
41- expect(result).toHaveLength(2);
43+ expect(result).toHaveLength(4);
4244 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+ ]),
4451 );
4552 expect(result.map((f) => f.path.split("/").pop())).not.toContain(
4653 "assistant3.md",
@@ -69,6 +76,12 @@
6976 expect(result.map((f) => f.path.split("/").pop())).not.toContain(
7077 "assistant2.yml",
7178 );
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+ );
7285 });
7386
7487 it("should return all supported files when fileExtType is not specified", async () => {
@@ -83,11 +96,13 @@
8396 options,
8497 "assistants",
8598 );
86- expect(result).toHaveLength(3);
99+ expect(result).toHaveLength(5);
87100 expect(result.map((f) => f.path.split("/").pop())).toEqual(
88101 expect.arrayContaining([
89102 "assistant1.yaml",
90103 "assistant2.yml",
104+ "config.yml",
105+ "config.yaml",
91106 "assistant3.md",
92107 ]),
93108 );
@@ -124,9 +139,14 @@
124139 workspaceOnOptions,
125140 "assistants",
126141 );
127- expect(workspaceResult).toHaveLength(2);
142+ expect(workspaceResult).toHaveLength(4);
128143 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+ ]),
130150 );
131151 });
132152
@@ -187,7 +207,7 @@
187207 options,
188208 "assistants",
189209 );
190- expect(result).toHaveLength(2);
210+ expect(result).toHaveLength(4);
191211 const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
192212 expect(yamlFile?.content).toBe("yaml content 1");
193213 });
@@ -212,9 +232,14 @@
212232 "assistants",
213233 );
214234 // Should only get lowercase extensions (current implementation)
215- expect(yamlResult).toHaveLength(2);
235+ expect(yamlResult).toHaveLength(4);
216236 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+ ]),
218243 );
219244 expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
220245 "assistant5.YAML",
@@ -240,3 +265,232 @@
240265 );
241266 });
242267 });
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 @@
11 import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
22
33 import { ControlPlaneClient } from "../../control-plane/client.js";
4-import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
4+import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
55 import { ProfileDescription } from "../ProfileLifecycleManager.js";
66
77 import { getPrimaryConfigFilePath } from "../../util/paths.js";
@@ -15,7 +15,6 @@
1515
1616 constructor(
1717 private ide: IDE,
18- private ideSettingsPromise: Promise<IdeSettings>,
1918 private controlPlaneClient: ControlPlaneClient,
2019 private llmLogger: ILLMLogger,
2120 private overrideAssistantFile?:
@@ -33,7 +32,7 @@
3332 iconUrl: "",
3433 title: overrideAssistantFile?.path
3534 ? getUriPathBasename(overrideAssistantFile.path)
36- : "Local Assistant",
35+ : "Local Agent",
3736 errors: undefined,
3837 uri:
3938 overrideAssistantFile?.path ??
@@ -48,7 +47,7 @@
4847 );
4948 this.description.title = parsedAssistant.name;
5049 } catch (e) {
51- console.error("Failed to parse assistant file: ", e);
50+ console.error("Failed to parse agent file: ", e);
5251 }
5352 }
5453 }
@@ -57,7 +56,6 @@
5756 async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
5857 const result = await doLoadConfig({
5958 ide: this.ide,
60- ideSettingsPromise: this.ideSettingsPromise,
6159 controlPlaneClient: this.controlPlaneClient,
6260 llmLogger: this.llmLogger,
6361 profileId: this.description.id,
modified core/config/profile/PlatformProfileLoader.ts +2 −10
@@ -2,7 +2,7 @@
22
33 import { ControlPlaneClient } from "../../control-plane/client.js";
44 import { getControlPlaneEnv } from "../../control-plane/env.js";
5-import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
5+import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
66 import { ProfileDescription } from "../ProfileLifecycleManager.js";
77
88 import doLoadConfig from "./doLoadConfig.js";
@@ -28,7 +28,6 @@
2828 private readonly versionSlug: string;
2929 private readonly controlPlaneClient: ControlPlaneClient;
3030 private readonly ide: IDE;
31- private ideSettingsPromise: Promise<IdeSettings>;
3231 private llmLogger: ILLMLogger;
3332 readonly description: ProfileDescription;
3433 private readonly orgScopeId: string | null;
@@ -41,7 +40,6 @@
4140 versionSlug,
4241 controlPlaneClient,
4342 ide,
44- ideSettingsPromise,
4543 llmLogger,
4644 description,
4745 orgScopeId,
@@ -53,7 +51,6 @@
5351 versionSlug: string;
5452 controlPlaneClient: ControlPlaneClient;
5553 ide: IDE;
56- ideSettingsPromise: Promise<IdeSettings>;
5754 llmLogger: ILLMLogger;
5855 description: ProfileDescription;
5956 orgScopeId: string | null;
@@ -65,7 +62,6 @@
6562 this.versionSlug = versionSlug;
6663 this.controlPlaneClient = controlPlaneClient;
6764 this.ide = ide;
68- this.ideSettingsPromise = ideSettingsPromise;
6965 this.llmLogger = llmLogger;
7066 this.description = description;
7167 this.orgScopeId = orgScopeId;
@@ -79,7 +75,6 @@
7975 versionSlug,
8076 controlPlaneClient,
8177 ide,
82- ideSettingsPromise,
8378 llmLogger,
8479 rawYaml,
8580 orgScopeId,
@@ -91,12 +86,11 @@
9186 versionSlug: string;
9287 controlPlaneClient: ControlPlaneClient;
9388 ide: IDE;
94- ideSettingsPromise: Promise<IdeSettings>;
9589 llmLogger: ILLMLogger;
9690 rawYaml: string;
9791 orgScopeId: string | null;
9892 }): Promise<PlatformProfileLoader> {
99- const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
93+ const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings());
10094
10195 const description: ProfileDescription = {
10296 id: `${ownerSlug}/${packageSlug}`,
@@ -121,7 +115,6 @@
121115 versionSlug,
122116 controlPlaneClient,
123117 ide,
124- ideSettingsPromise,
125118 llmLogger,
126119 description,
127120 orgScopeId,
@@ -139,7 +132,6 @@
139132
140133 const results = await doLoadConfig({
141134 ide: this.ide,
142- ideSettingsPromise: this.ideSettingsPromise,
143135 controlPlaneClient: this.controlPlaneClient,
144136 llmLogger: this.llmLogger,
145137 overrideConfigYaml: this.configResult.config,
modified core/config/profile/doLoadConfig.ts +20 −23
@@ -11,7 +11,6 @@
1111 import {
1212 ContinueConfig,
1313 IDE,
14- IdeSettings,
1514 ILLMLogger,
1615 RuleWithSource,
1716 SerializedContinueConfig,
@@ -20,9 +19,8 @@
2019 } from "../../";
2120 import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
2221 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
23-import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
22+import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
2423 import MCPContextProvider from "../../context/providers/MCPContextProvider";
25-import RulesContextProvider from "../../context/providers/RulesContextProvider";
2624 import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
2725 import { ControlPlaneClient } from "../../control-plane/client.js";
2826 import { getControlPlaneEnv } from "../../control-plane/env.js";
@@ -71,7 +69,6 @@
7169 }
7270 export default async function doLoadConfig(options: {
7371 ide: IDE;
74- ideSettingsPromise: Promise<IdeSettings>;
7572 controlPlaneClient: ControlPlaneClient;
7673 llmLogger: ILLMLogger;
7774 overrideConfigJson?: SerializedContinueConfig;
@@ -83,7 +80,6 @@
8380 }): Promise<ConfigResult<ContinueConfig>> {
8481 const {
8582 ide,
86- ideSettingsPromise,
8783 controlPlaneClient,
8884 llmLogger,
8985 overrideConfigJson,
@@ -96,8 +92,9 @@
9692
9793 const ideInfo = await ide.getIdeInfo();
9894 const uniqueId = await ide.getUniqueId();
99- const ideSettings = await ideSettingsPromise;
95+ const ideSettings = await ide.getIdeSettings();
10096 const workOsAccessToken = await controlPlaneClient.getAccessToken();
97+ const isSignedIn = await controlPlaneClient.isSignedIn();
10198
10299 // Migrations for old config files
103100 // Removes
@@ -157,17 +154,13 @@
157154 const { rules, errors: rulesErrors } = await loadRules(ide);
158155 errors.push(...rulesErrors);
159156 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;
171164 }
172165
173166 // Show deprecation warnings for providers
@@ -194,7 +187,6 @@
194187 const mcpManager = MCPManagerSingleton.getInstance();
195188 const mcpServerStatuses = mcpManager.getStatuses();
196189
197- // Slightly hacky just need connection's client to make slash command for now
198190 const serializableStatuses = mcpServerStatuses.map((server) => {
199191 const { client, ...rest } = server;
200192 return rest;
@@ -285,6 +277,9 @@
285277 rules: newConfig.rules,
286278 enableExperimentalTools:
287279 newConfig.experimental?.enableExperimentalTools ?? false,
280+ isSignedIn,
281+ isRemote: await ide.isWorkspaceRemote(),
282+ modelName: newConfig.selectedModelByRole.chat?.model,
288283 }),
289284 );
290285
@@ -333,12 +328,14 @@
333328 }
334329 }
335330
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) {
340334 newConfig.allowAnonymousTelemetry = false;
341335 }
336+ if (policy?.allowCodebaseIndexing === false) {
337+ newConfig.disableIndexing = true;
338+ }
342339
343340 // Setup telemetry only after (and if) we know it is enabled
344341 await Telemetry.setup(
@@ -373,7 +370,7 @@
373370 const useOnPremProxy =
374371 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
375372
376- const env = await getControlPlaneEnv(ideSettingsPromise);
373+ const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
377374 let controlPlaneProxyUrl: string = useOnPremProxy
378375 ? controlPlane?.proxyUrl
379376 : env.DEFAULT_CONTROL_PLANE_PROXY_URL;
modified core/config/sharedConfig.ts +6 −0
@@ -32,6 +32,7 @@
3232 displayRawMarkdown: z.boolean(),
3333 showChatScrollbar: z.boolean(),
3434 autoAcceptEditToolDiffs: z.boolean(),
35+ continueAfterToolRejection: z.boolean(),
3536
3637 // `tabAutocompleteOptions` in `ContinueConfig`
3738 useAutocompleteCache: z.boolean(),
@@ -158,6 +159,11 @@
158159 configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
159160 }
160161
162+ if (sharedConfig.continueAfterToolRejection !== undefined) {
163+ configCopy.ui.continueAfterToolRejection =
164+ sharedConfig.continueAfterToolRejection;
165+ }
166+
161167 configCopy.experimental = {
162168 ...configCopy.experimental,
163169 };
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 @@
280280 replacement: string;
281281 }
282282
283- export interface ContinueError {
284- title: string;
285- message: string;
286- }
287-
288283 export interface CompletionOptions extends BaseCompletionOptions {
289284 model: string;
290285 }
@@ -692,6 +687,8 @@
692687
693688 openUrl(url: string): Promise<void>;
694689
690+ getExternalUri?(uri: string): Promise<string>;
691+
695692 runCommand(command: string): Promise<void>;
696693
697694 saveFile(filepath: string): Promise<void>;
@@ -1061,6 +1058,7 @@
10611058 filepath?: string;
10621059 fileContent?: string;
10631060 originalFileContent?: string;
1061+ autoFormattingDiff?: string;
10641062 }
10651063
10661064 export interface RangeInFileWithContents {
modified core/config/yaml/default.ts +2 −2
@@ -4,7 +4,7 @@
44 export const defaultConfigYaml: AssistantUnrolled = {
55 models: [],
66 context: [],
7- name: "Local Assistant",
7+ name: "Local Agent",
88 version: "1.0.0",
99 schema: "v1",
1010 };
@@ -12,7 +12,7 @@
1212 export const defaultConfigYamlJetBrains: AssistantUnrolled = {
1313 models: [],
1414 context: [],
15- name: "Local Assistant",
15+ name: "Local Agent",
1616 version: "1.0.0",
1717 schema: "v1",
1818 };
modified core/config/yaml/loadYaml.ts +64 −80
@@ -4,6 +4,7 @@
44 ConfigResult,
55 ConfigValidationError,
66 isAssistantUnrolledNonNullable,
7+ mergeConfigYamlRequestOptions,
78 mergeUnrolledAssistants,
89 ModelRole,
910 PackageIdentifier,
@@ -14,18 +15,8 @@
1415 } from "@continuedev/config-yaml";
1516 import { dirname } from "node:path";
1617
17-import {
18- ContinueConfig,
19- IContextProvider,
20- IDE,
21- IdeInfo,
22- IdeSettings,
23- ILLMLogger,
24-} from "../..";
18+import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
2519 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";
2920 import { ControlPlaneClient } from "../../control-plane/client";
3021 import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
3122 import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
@@ -34,17 +25,17 @@
3425
3526 import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
3627 import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
28+import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
3729 import { getControlPlaneEnvSync } from "../../control-plane/env";
38-import { getToolsForIde } from "../../tools";
30+import { PolicySingleton } from "../../control-plane/PolicySingleton";
31+import { getBaseToolDefinitions } from "../../tools";
3932 import { getCleanUriPath } from "../../util/uri";
33+import { loadConfigContextProviders } from "../loadContextProviders";
4034 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4135 import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
4236 import { LocalPlatformClient } from "./LocalPlatformClient";
4337 import { llmsFromModelConfig } from "./models";
44-import {
45- convertYamlMcpToContinueMcp,
46- convertYamlRuleToContinueRule,
47-} from "./yamlToContinueConfig";
38+import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
4839
4940 async function loadConfigYaml(options: {
5041 overrideConfigYaml: AssistantUnrolled | undefined;
@@ -162,22 +153,21 @@
162153 };
163154 }
164155
165-async function configYamlToContinueConfig(options: {
156+export async function configYamlToContinueConfig(options: {
166157 config: AssistantUnrolled;
167158 ide: IDE;
168- ideSettings: IdeSettings;
169159 ideInfo: IdeInfo;
170160 uniqueId: string;
171161 llmLogger: ILLMLogger;
172162 workOsAccessToken: string | undefined;
173163 }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
174- let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
164+ let { config, ide, ideInfo, uniqueId, llmLogger } = options;
175165
176166 const localErrors: ConfigValidationError[] = [];
177167
178168 const continueConfig: ContinueConfig = {
179169 slashCommands: [],
180- tools: await getToolsForIde(ide),
170+ tools: getBaseToolDefinitions(),
181171 mcpServerStatuses: [],
182172 contextProviders: [],
183173 modelsByRole: {
@@ -199,6 +189,7 @@
199189 summarize: null,
200190 },
201191 rules: [],
192+ requestOptions: { ...config.requestOptions },
202193 };
203194
204195 // Right now, if there are any missing packages in the config, then we will just throw an error
@@ -216,10 +207,30 @@
216207 }
217208
218209 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+ }
220225 }
221226
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+ }));
223234 continueConfig.docs = config.docs?.map((doc) => ({
224235 title: doc.name,
225236 startUrl: doc.startUrl,
@@ -243,12 +254,6 @@
243254 });
244255 });
245256
246- continueConfig.experimental = {
247- modelContextProtocolServers: config.mcpServers?.map(
248- convertYamlMcpToContinueMcp,
249- ),
250- };
251-
252257 // Prompt files -
253258 try {
254259 const promptFiles = await getAllPromptFiles(ide, undefined, true);
@@ -300,9 +305,7 @@
300305 try {
301306 const llms = await llmsFromModelConfig({
302307 model,
303- ide,
304308 uniqueId,
305- ideSettings,
306309 llmLogger,
307310 config: continueConfig,
308311 });
@@ -376,60 +379,42 @@
376379 });
377380 }
378381
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,
384386 );
385387
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);
415390
416391 // Trigger MCP server refreshes (Config is reloaded again once connected!)
417392 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+ }
433418
434419 return { config: continueConfig, errors: localErrors };
435420 }
@@ -480,7 +465,6 @@
480465 await configYamlToContinueConfig({
481466 config: configYamlResult.config,
482467 ide,
483- ideSettings,
484468 ideInfo,
485469 uniqueId,
486470 llmLogger,
modified core/config/yaml/loadYaml.vitest.ts +7 −7
@@ -1,14 +1,14 @@
1-import { describe, it, expect } from "vitest";
21 import {
3- validateConfigYaml,
42 AssistantUnrolledNonNullable,
3+ validateConfigYaml,
54 } from "@continuedev/config-yaml";
5+import { describe, expect, it } from "vitest";
66
77 describe("MCP Server cwd configuration", () => {
88 describe("YAML schema validation", () => {
99 it("should accept valid MCP server with cwd", () => {
1010 const config: AssistantUnrolledNonNullable = {
11- name: "test-assistant",
11+ name: "test-agent",
1212 version: "1.0.0",
1313 mcpServers: [
1414 {
@@ -28,7 +28,7 @@
2828
2929 it("should accept MCP server without cwd", () => {
3030 const config: AssistantUnrolledNonNullable = {
31- name: "test-assistant",
31+ name: "test-agent",
3232 version: "1.0.0",
3333 mcpServers: [
3434 {
@@ -45,7 +45,7 @@
4545
4646 it("should accept relative paths in cwd", () => {
4747 const config: AssistantUnrolledNonNullable = {
48- name: "test-assistant",
48+ name: "test-agent",
4949 version: "1.0.0",
5050 mcpServers: [
5151 {
@@ -63,7 +63,7 @@
6363
6464 it("should accept empty string cwd", () => {
6565 const config: AssistantUnrolledNonNullable = {
66- name: "test-assistant",
66+ name: "test-agent",
6767 version: "1.0.0",
6868 mcpServers: [
6969 {
@@ -115,7 +115,7 @@
115115
116116 configs.forEach(({ name, server }) => {
117117 const config: AssistantUnrolledNonNullable = {
118- name: "test-assistant",
118+ name: "test-agent",
119119 version: "1.0.0",
120120 mcpServers: [server],
121121 };
modified core/config/yaml/models.ts +15 −23
@@ -1,12 +1,9 @@
1-import { ModelConfig } from "@continuedev/config-yaml";
2-
31 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 "../..";
107 import { BaseLLM } from "../../llm";
118 import { LLMClasses } from "../../llm/llms";
129
@@ -29,15 +26,15 @@
2926 async function modelConfigToBaseLLM({
3027 model,
3128 uniqueId,
32- ideSettings,
3329 llmLogger,
3430 config,
31+ isFromAutoDetect,
3532 }: {
3633 model: ModelConfig;
3734 uniqueId: string;
38- ideSettings: IdeSettings;
3935 llmLogger: ILLMLogger;
4036 config: ContinueConfig;
37+ isFromAutoDetect?: boolean;
4138 }): Promise<BaseLLM | undefined> {
4239 const cls = getModelClass(model);
4340
@@ -47,6 +44,11 @@
4744
4845 const { capabilities, ...rest } = model;
4946
47+ const mergedRequestOptions = mergeConfigYamlRequestOptions(
48+ rest.requestOptions,
49+ config.requestOptions,
50+ );
51+
5052 let options: LLMOptions = {
5153 ...rest,
5254 contextLength: model.defaultCompletionOptions?.contextLength,
@@ -71,6 +73,8 @@
7173 nextEdit: model.capabilities?.includes("next_edit"),
7274 },
7375 autocompleteOptions: model.autocompleteOptions,
76+ isFromAutoDetect,
77+ requestOptions: mergedRequestOptions,
7478 };
7579
7680 // Model capabilities - need to be undefined if not found
@@ -151,17 +155,13 @@
151155 async function autodetectModels({
152156 llm,
153157 model,
154- ide,
155158 uniqueId,
156- ideSettings,
157159 llmLogger,
158160 config,
159161 }: {
160162 llm: BaseLLM;
161163 model: ModelConfig;
162- ide: IDE;
163164 uniqueId: string;
164- ideSettings: IdeSettings;
165165 llmLogger: ILLMLogger;
166166 config: ContinueConfig;
167167 }): Promise<BaseLLM[]> {
@@ -173,7 +173,6 @@
173173 if (modelName === AUTODETECT) {
174174 return undefined;
175175 }
176-
177176 return await modelConfigToBaseLLM({
178177 model: {
179178 ...model,
@@ -181,9 +180,9 @@
181180 name: modelName,
182181 },
183182 uniqueId,
184- ideSettings,
185183 llmLogger,
186184 config,
185+ isFromAutoDetect: true,
187186 });
188187 }),
189188 );
@@ -196,23 +195,18 @@
196195
197196 export async function llmsFromModelConfig({
198197 model,
199- ide,
200198 uniqueId,
201- ideSettings,
202199 llmLogger,
203200 config,
204201 }: {
205202 model: ModelConfig;
206- ide: IDE;
207203 uniqueId: string;
208- ideSettings: IdeSettings;
209204 llmLogger: ILLMLogger;
210205 config: ContinueConfig;
211206 }): Promise<BaseLLM[]> {
212207 const baseLlm = await modelConfigToBaseLLM({
213208 model,
214209 uniqueId,
215- ideSettings,
216210 llmLogger,
217211 config,
218212 });
@@ -224,9 +218,7 @@
224218 const models = await autodetectModels({
225219 llm: baseLlm,
226220 model,
227- ide,
228221 uniqueId,
229- ideSettings,
230222 llmLogger,
231223 config,
232224 });
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 @@
1313 rule: rule.rule,
1414 globs: rule.globs,
1515 name: rule.name,
16+ description: rule.description,
1617 ruleFile: rule.sourceFile,
1718 alwaysApply: rule.alwaysApply,
19+ invokable: rule.invokable ?? false,
1820 };
1921 }
2022 }
modified core/context/mcp/MCPConnection.ts +36 −9
@@ -1,6 +1,4 @@
11 import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2-import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
3-
42 import {
53 SSEClientTransport,
64 SseError,
@@ -8,7 +6,8 @@
86 import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
97 import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
108 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";
1211 import {
1312 IDE,
1413 MCPConnectionStatus,
@@ -53,6 +52,7 @@
5352 public status: MCPConnectionStatus = "not-connected";
5453 public isProtectedResource = false;
5554 public errors: string[] = [];
55+ public infos: string[] = [];
5656 public prompts: MCPPrompt[] = [];
5757 public tools: MCPTool[] = [];
5858 public resources: MCPResource[] = [];
@@ -94,6 +94,7 @@
9494 return {
9595 ...this.options,
9696 errors: this.errors,
97+ infos: this.infos,
9798 prompts: this.prompts,
9899 resources: this.resources,
99100 resourceTemplates: this.resourceTemplates,
@@ -123,6 +124,7 @@
123124 this.resources = [];
124125 this.resourceTemplates = [];
125126 this.errors = [];
127+ this.infos = [];
126128 this.stdioOutput = { stdout: "", stderr: "" };
127129
128130 this.abortController.abort();
@@ -281,6 +283,16 @@
281283 if (msg.includes("spawn") && msg.includes("enoent")) {
282284 const command = msg.split(" ")[1];
283285 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+ }
284296 } else {
285297 errorMessage += "Error: " + error.message;
286298 }
@@ -393,6 +405,11 @@
393405 case "websocket":
394406 return new WebSocketClientTransport(new URL(options.transport.url));
395407 case "sse":
408+ const sseAgent =
409+ options.transport.requestOptions?.verifySsl === false
410+ ? new HttpsAgent({ rejectUnauthorized: false })
411+ : undefined;
412+
396413 return new SSEClientTransport(new URL(options.transport.url), {
397414 eventSourceInit: {
398415 fetch: (input, init) =>
@@ -404,17 +421,27 @@
404421 | Record<string, string>
405422 | undefined),
406423 },
424+ ...(sseAgent && { agent: sseAgent }),
407425 }),
408426 },
409- requestInit: { headers: options.transport.requestOptions?.headers },
427+ requestInit: {
428+ headers: options.transport.requestOptions?.headers,
429+ ...(sseAgent && { agent: sseAgent }),
430+ },
410431 });
411432 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 }),
416443 },
417- );
444+ });
418445 default:
419446 throw new Error(
420447 `Unsupported transport type: ${(options.transport as any).type}`,
modified core/context/mcp/MCPConnection.vitest.ts +1 −0
@@ -142,6 +142,7 @@
142142 expect(status).toEqual({
143143 ...options,
144144 errors: [],
145+ infos: [],
145146 isProtectedResource: false,
146147 prompts: [],
147148 resources: [],
modified core/context/mcp/MCPManagerSingleton.ts +15 −0
@@ -48,6 +48,21 @@
4848 this.connections.delete(id);
4949 }
5050
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+
5166 setConnections(
5267 servers: MCPOptions[],
5368 forceRefresh: boolean,
modified core/context/mcp/MCPOauth.ts +193 −63
@@ -12,65 +12,121 @@
1212
1313 import http from "http";
1414 import url from "url";
15+import crypto from "crypto";
1516 import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
1617
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>();
2130
2231 const PORT = 3000;
2332
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;
2934
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+ }
3446
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;
3649
37- const html = `
50+ void handleMCPOauthCode(code, state);
51+
52+ const html = `
3853 <!DOCTYPE html>
3954 <html>
4055 <head><title>Authentication Complete</title></head>
4156 <body>Authentication Complete. You can close this page now.</body>
4257 </html>`;
4358
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+ });
5368
5469 type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
5570 type MCPOauthStorageKey = keyof MCPOauthStorage;
5671
5772 class MCPConnectionOauthProvider implements OAuthClientProvider {
5873 private globalContext: GlobalContext;
74+ private _redirectUrl: string;
75+ private _redirectUrlInitialized: Promise<void>;
5976
6077 constructor(
6178 public oauthServerUrl: string,
6279 private ide: IDE,
6380 ) {
6481 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+ }
65101 }
66102
67103 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;
69119 }
70120
71121 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+
72128 return {
73- redirect_uris: [this.redirectUrl],
129+ redirect_uris: [redirectUri],
74130 token_endpoint_auth_method: "none",
75131 grant_types: ["authorization_code", "refresh_token"],
76132 response_types: ["code"],
@@ -151,14 +207,28 @@
151207 }
152208
153209 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+ }
160230 }
161- void this.ide.openUrl(authorizationUrl.toString());
231+ await this.ide.openUrl(authorizationUrl.toString());
162232 }
163233 }
164234
@@ -175,49 +245,109 @@
175245 export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
176246 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
177247 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, {
179256 authenticatingServer: mcpServer,
180257 ide,
181- };
182- return await auth(authProvider, {
183- serverUrl: mcpServerUrl,
258+ state,
184259 });
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+ }
185274 }
186275
187276 /**
188277 * handle the authentication code received from the oauth redirect
189278 */
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+ }
193297 }
194- const { ide, authenticatingServer } = authenticatingMCPContext;
195- const serverUrl = (authenticatingServer.transport as SSEOptions).url;
196298
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);
199301 return;
200302 }
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+ }
219350 }
220- authenticatingMCPContext = null;
221351 }
222352
223353 export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
modified core/context/mcp/MCPOauth.vitest.ts +149 −0
@@ -33,6 +33,7 @@
3333 mockIde = {
3434 openUrl: vi.fn(),
3535 showToast: vi.fn(),
36+ getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
3637 };
3738
3839 mockMcpServer = {
@@ -178,4 +179,152 @@
178179 });
179180 });
180181 });
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+ });
181330 });
modified core/context/providers/CodeContextProvider.ts +1 −1
@@ -16,7 +16,7 @@
1616 displayTitle: "Code",
1717 description: "Type to search",
1818 type: "submenu",
19- dependsOnIndexing: true,
19+ dependsOnIndexing: ["chunk", "codeSnippets"],
2020 };
2121
2222 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 @@
1313 description: "Automatically find relevant files",
1414 type: "normal",
1515 renderInlineAs: "",
16+ dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"],
1617 };
1718
1819 async getContextItems(
modified core/context/providers/DatabaseContextProvider.ts +4 −0
@@ -18,6 +18,10 @@
1818 renderInlineAs: "",
1919 };
2020
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+
2125 async getContextItems(
2226 query: string,
2327 extras: ContextProviderExtras,
modified core/context/providers/DiscordContextProvider.ts +5 −1
@@ -3,8 +3,8 @@
33 ContextProviderDescription,
44 ContextProviderExtras,
55 ContextSubmenuItem,
6- LoadSubmenuItemsArgs,
76 FetchFunction,
7+ LoadSubmenuItemsArgs,
88 } from "../../index.js";
99 import { BaseContextProvider } from "../index.js";
1010
@@ -43,6 +43,10 @@
4343 return `${this.baseUrl}${path}`;
4444 }
4545
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+
4650 async fetchMessages(
4751 channelId: string,
4852 fetch: FetchFunction,
modified core/context/providers/FileContextProvider.ts +1 −0
@@ -6,6 +6,7 @@
66 ContextSubmenuItem,
77 LoadSubmenuItemsArgs,
88 } from "../../";
9+import { isSecurityConcern } from "../../indexing/ignore";
910 import { walkDirs } from "../../indexing/walkDir";
1011 import {
1112 getShortestUniqueRelativeUriPaths,
modified core/context/providers/FolderContextProvider.ts +1 −1
@@ -19,7 +19,7 @@
1919 displayTitle: "Folder",
2020 description: "Type to search",
2121 type: "submenu",
22- dependsOnIndexing: true,
22+ dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"],
2323 };
2424
2525 async getContextItems(
modified core/context/providers/GitCommitContextProvider.ts +4 −0
@@ -44,6 +44,10 @@
4444 type: "submenu",
4545 };
4646
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+
4751 async getContextItems(
4852 query: string,
4953 extras: ContextProviderExtras,
modified core/context/providers/GitHubIssuesContextProvider.ts +4 −0
@@ -15,6 +15,10 @@
1515 type: "submenu",
1616 };
1717
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+
1822 async getContextItems(
1923 query: string,
2024 extras: ContextProviderExtras,
modified core/context/providers/GitLabMergeRequestContextProvider.ts +4 −0
@@ -76,6 +76,10 @@
7676 type: "normal",
7777 };
7878
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+
7983 private async getApi(): Promise<AxiosInstance> {
8084 const { default: Axios } = await import("axios");
8185
modified core/context/providers/GoogleContextProvider.ts +4 −0
@@ -20,6 +20,10 @@
2020 this._serperApiKey = options.serperApiKey;
2121 }
2222
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+
2327 async getContextItems(
2428 query: string,
2529 extras: ContextProviderExtras,
modified core/context/providers/GreptileContextProvider.ts +4 −0
@@ -17,6 +17,10 @@
1717 type: "query",
1818 };
1919
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+
2024 async getContextItems(
2125 query: string,
2226 extras: ContextProviderExtras,
modified core/context/providers/JiraIssuesContextProvider/index.ts +4 −0
@@ -17,6 +17,10 @@
1717 type: "submenu",
1818 };
1919
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+
2024 private getApi() {
2125 return new JiraClient({
2226 domain: this.options.domain,
modified core/context/providers/OpenFilesContextProvider.ts +15 −1
@@ -3,6 +3,7 @@
33 ContextProviderDescription,
44 ContextProviderExtras,
55 } from "../../index.js";
6+import { isSecurityConcern } from "../../indexing/ignore.js";
67 import { getUriDescription } from "../../util/uri.js";
78 import { BaseContextProvider } from "../index.js";
89
@@ -27,10 +28,23 @@
2728
2829 return await Promise.all(
2930 openFiles.map(async (filepath: string) => {
30- const content = await ide.readFile(filepath);
3131 const { relativePathOrBasename, last2Parts, baseName } =
3232 getUriDescription(filepath, workspaceDirs);
3333
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+
3448 return {
3549 description: last2Parts,
3650 content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
modified core/context/providers/ProblemsContextProvider.ts +2 −1
@@ -3,6 +3,7 @@
33 ContextProviderDescription,
44 ContextProviderExtras,
55 } from "../../index.js";
6+import { isSecurityConcern } from "../../indexing/ignore.js";
67 import { getUriDescription } from "../../util/uri.js";
78 import { BaseContextProvider } from "../index.js";
89
@@ -40,7 +41,7 @@
4041 return {
4142 description: "Problems in current file",
4243 content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
43- name: `Warning in ${baseName}`,
44+ name: `Warnings in ${baseName}`,
4445 };
4546 }),
4647 );
modified core/context/providers/_context-providers.vitest.ts +0 −2
@@ -28,11 +28,9 @@
2828 ): Promise<ContextProviderExtras> {
2929 setUpTestDir();
3030 const ide = new FileSystemIde(TEST_DIR);
31- const ideSettingsPromise = ide.getIdeSettings();
3231 const llmLogger = new LLMLogger();
3332 const configHandler = new ConfigHandler(
3433 ide,
35- ideSettingsPromise,
3634 llmLogger,
3735 Promise.resolve(undefined),
3836 );
modified core/context/providers/index.ts +2 −6
@@ -1,6 +1,5 @@
11 import { BaseContextProvider } from "../";
22 import { ContextProviderName } from "../../";
3-import { Telemetry } from "../../util/posthog";
43
54 import ClipboardContextProvider from "./ClipboardContextProvider";
65 import CodebaseContextProvider from "./CodebaseContextProvider";
@@ -12,6 +11,7 @@
1211 import DiffContextProvider from "./DiffContextProvider";
1312 import DiscordContextProvider from "./DiscordContextProvider";
1413 import DocsContextProvider from "./DocsContextProvider";
14+import FileContextProvider from "./FileContextProvider";
1515 import FileTreeContextProvider from "./FileTreeContextProvider";
1616 import FolderContextProvider from "./FolderContextProvider";
1717 import GitCommitContextProvider from "./GitCommitContextProvider";
@@ -41,6 +41,7 @@
4141 * See this issue for details: https://github.com/continuedev/continue/issues/1365
4242 */
4343 export const Providers: (typeof BaseContextProvider)[] = [
44+ FileContextProvider,
4445 DiffContextProvider,
4546 FileTreeContextProvider,
4647 GitHubIssuesContextProvider,
@@ -78,10 +79,5 @@
7879 ): typeof BaseContextProvider | undefined {
7980 const provider = Providers.find((cls) => cls.description.title === name);
8081
81- void Telemetry.capture("context_provider_load", {
82- providerName: name,
83- found: !!provider, // also capture those which user expected to be present
84- });
85-
8682 return provider;
8783 }
modified core/context/retrieval/retrieval.ts +1 −1
@@ -37,7 +37,7 @@
3737 const nFinal =
3838 options?.nFinal ??
3939 Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
40- const useReranking = !!extras.reranker;
40+ const useReranking = options?.useReranking ?? !!extras.reranker;
4141 const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
4242
4343 const branches = (await Promise.race([
modified core/control-plane/client.ts +142 −6
@@ -11,10 +11,19 @@
1111 import fetch, { RequestInit, Response } from "node-fetch";
1212
1313 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";
1520 import { Logger } from "../util/Logger.js";
1621
17-import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
22+import {
23+ ControlPlaneSessionInfo,
24+ HubSessionInfo,
25+ isOnPremSession,
26+} from "./AuthTypes.js";
1827 import { getControlPlaneEnv } from "./env.js";
1928
2029 export interface PolicyResponse {
@@ -41,11 +50,15 @@
4150 export const TRIAL_PROXY_URL =
4251 "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
4352
53+export interface RemoteSessionMetadata extends BaseSessionMetadata {
54+ isRemote: true;
55+ remoteId: string;
56+}
57+
4458 export class ControlPlaneClient {
4559 constructor(
4660 readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
47- private readonly ideSettingsPromise: Promise<IdeSettings>,
48- private readonly ideInfoPromise: Promise<IdeInfo>,
61+ private readonly ide: IDE,
4962 ) {}
5063
5164 async resolveFQSNs(
@@ -90,9 +103,9 @@
90103 throw new Error("No access token");
91104 }
92105
93- const env = await getControlPlaneEnv(this.ideSettingsPromise);
106+ const env = await getControlPlaneEnv(this.ide.getIdeSettings());
94107 const url = new URL(path, env.CONTROL_PLANE_URL).toString();
95- const ideInfo = await this.ideInfoPromise;
108+ const ideInfo = await this.ide.getIdeInfo();
96109
97110 const resp = await fetch(url, {
98111 ...init,
@@ -304,4 +317,127 @@
304317 return null;
305318 }
306319 }
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+ }
307443 }
modified core/core.ts +118 −35
@@ -10,7 +10,6 @@
1010 import { ConfigHandler } from "./config/ConfigHandler";
1111 import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
1212 import { addModel, deleteModel } from "./config/util";
13-import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
1413 import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
1514 import { getControlPlaneEnv } from "./control-plane/env";
1615 import { DevDataSqliteDb } from "./data/devdataSqlite";
@@ -18,6 +17,7 @@
1817 import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
1918 import DocsService from "./indexing/docs/DocsService";
2019 import { countTokens } from "./llm/countTokens";
20+import Lemonade from "./llm/llms/Lemonade";
2121 import Ollama from "./llm/llms/Ollama";
2222 import { EditAggregator } from "./nextEdit/context/aggregateEdits";
2323 import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
@@ -30,8 +30,9 @@
3030 import { Telemetry } from "./util/posthog";
3131 import {
3232 isProcessBackgrounded,
33+ killTerminalProcess,
3334 markProcessAsBackgrounded,
34-} from "./util/processTerminalBackgroundStates";
35+} from "./util/processTerminalStates";
3536 import { getSymbolsForManyFiles } from "./util/treeSitter";
3637 import { TTS } from "./util/tts";
3738
@@ -51,6 +52,7 @@
5152 import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
5253 import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
5354 import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
55+import { createNewAssistantFile } from "./config/createNewAssistantFile";
5456 import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
5557 import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
5658 import {
@@ -139,7 +141,7 @@
139141
140142 const ideInfoPromise = messenger.request("getIdeInfo", undefined);
141143 const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
142- const sessionInfoPromise = messenger.request(
144+ const initialSessionInfoPromise = messenger.request(
143145 "getControlPlaneSessionInfo",
144146 {
145147 silent: true,
@@ -149,9 +151,8 @@
149151
150152 this.configHandler = new ConfigHandler(
151153 this.ide,
152- ideSettingsPromise,
153154 this.llmLogger,
154- sessionInfoPromise,
155+ initialSessionInfoPromise,
155156 );
156157
157158 this.docsService = DocsService.createSingleton(
@@ -176,6 +177,13 @@
176177 }
177178 };
178179
180+ this.codeBaseIndexer = new CodebaseIndexer(
181+ this.configHandler,
182+ this.ide,
183+ this.messenger,
184+ this.globalContext.get("indexingPaused"),
185+ );
186+
179187 this.configHandler.onConfigUpdate((result) => {
180188 void (async () => {
181189 const serializedResult =
@@ -188,6 +196,12 @@
188196 selectedOrgId: this.configHandler.currentOrg?.id ?? null,
189197 });
190198
199+ if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
200+ await this.codeBaseIndexer.refreshCodebaseIndex(
201+ await this.ide.getWorkspaceDirs(),
202+ );
203+ }
204+
191205 // update additional submenu context providers registered via VSCode API
192206 const additionalProviders =
193207 this.configHandler.getAdditionalSubmenuContextProviders();
@@ -199,13 +213,6 @@
199213 })();
200214 });
201215
202- this.codeBaseIndexer = new CodebaseIndexer(
203- this.configHandler,
204- this.ide,
205- this.messenger,
206- this.globalContext.get("indexingPaused"),
207- );
208-
209216 // Dev Data Logger
210217 const dataLogger = DataLogger.getInstance();
211218 dataLogger.core = this;
@@ -226,6 +233,17 @@
226233 return;
227234 }
228235
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+
229247 void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
230248 });
231249 });
@@ -308,8 +326,27 @@
308326 });
309327
310328 // 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);
313350 });
314351
315352 on("history/delete", (msg) => {
@@ -320,6 +357,12 @@
320357 return historyManager.load(msg.data.id);
321358 });
322359
360+ on("history/loadRemote", async (msg) => {
361+ return this.configHandler.controlPlaneClient.loadRemoteSession(
362+ msg.data.remoteId,
363+ );
364+ });
365+
323366 on("history/save", (msg) => {
324367 historyManager.save(msg.data);
325368 });
@@ -362,6 +405,13 @@
362405 );
363406 });
364407
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+
365415 on("config/addLocalWorkspaceBlock", async (msg) => {
366416 await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
367417 await this.configHandler.reloadConfig(
@@ -669,6 +719,8 @@
669719 return queue.dequeueProcessed() || null;
670720 });
671721
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.
672724 on("nextEdit/queue/processOne", async (msg) => {
673725 console.log("nextEdit/queue/processOne");
674726 const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
@@ -721,20 +773,13 @@
721773 data.fileUri ?? "current-file-stream",
722774 ); // not super important since currently cancelling apply will cancel all streams it's one file at a time
723775
724- return streamDiffLines({
725- highlighted: data.highlighted,
726- prefix: data.prefix,
727- suffix: data.suffix,
776+ return streamDiffLines(
777+ data,
728778 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,
736779 abortController,
737- });
780+ undefined,
781+ data.includeRulesInSystemMessage ? config.rules : undefined,
782+ );
738783 });
739784
740785 on("cancelApply", async (msg) => {
@@ -967,6 +1012,10 @@
9671012 on("docs/getDetails", async (msg) => {
9681013 return await this.docsService.getDetails(msg.data.startUrl);
9691014 });
1015+ on("docs/getIndexedPages", async (msg) => {
1016+ const pages = await this.docsService.getIndexedPages(msg.data.startUrl);
1017+ return Array.from(pages);
1018+ });
9701019
9711020 on("didChangeSelectedProfile", async (msg) => {
9721021 if (msg.data.id) {
@@ -1004,6 +1053,37 @@
10041053 this.handleToolCall(toolCall),
10051054 );
10061055
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+
10071087 on("isItemTooBig", async ({ data: { item } }) => {
10081088 return this.isItemTooBig(item);
10091089 });
@@ -1021,6 +1101,10 @@
10211101 },
10221102 );
10231103
1104+ on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
1105+ await killTerminalProcess(toolCallId);
1106+ });
1107+
10241108 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
10251109 const isValid = setMdmLicenseKey(licenseKey);
10261110 return isValid;
@@ -1217,6 +1301,9 @@
12171301 if (msg.data.title === "Ollama") {
12181302 const models = await new Ollama({ model: "" }).listModels();
12191303 return models;
1304+ } else if (msg.data.title === "Lemonade") {
1305+ const models = await new Lemonade({ model: "" }).listModels();
1306+ return models;
12201307 } else {
12211308 return undefined;
12221309 }
@@ -1281,15 +1368,9 @@
12811368 throw new Error("No chat model selected");
12821369 }
12831370
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+ );
12931374 if (!provider) {
12941375 return [];
12951376 }
@@ -1308,6 +1389,8 @@
13081389 selectedCode,
13091390 reranker: config.selectedModelByRole.rerank,
13101391 fetch: (url, init) =>
1392+ // Important note: context providers fetch uses global request options not LLM request options
1393+ // Because LLM calls are handled separately
13111394 fetchwithRequestOptions(url, init, config.requestOptions),
13121395 isInAgentMode: msg.data.isInAgentMode,
13131396 });
modified core/edit/constants.ts +2 −0
@@ -1,1 +1,3 @@
11 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 "..";
28 import { DEFAULT_MAX_TOKENS } from "../llm/constants";
39 import { countTokens } from "../llm/countTokens";
410 import { renderChatMessage } from "../util/messageContent";
11+import { APPLY_UNIQUE_TOKEN } from "./constants.js";
512
613 const INFINITE_STREAM_SAFETY = 0.9;
714
815 const DUD_PROMPT_LOG: PromptLog = {
916 modelTitle: "",
1017 modelProvider: "",
11- completionOptions: { model: "" },
1218 prompt: "",
1319 completion: "",
1420 };
@@ -18,6 +24,7 @@
1824 export async function* recursiveStream(
1925 llm: ILLM,
2026 abortController: AbortController,
27+ type: StreamDiffLinesType,
2128 prompt: ChatMessage[] | string,
2229 prediction: Prediction | undefined,
2330 currentBuffer = "",
@@ -29,8 +36,11 @@
2936 let buffer = currentBuffer;
3037 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
3138
39+ const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm);
3240 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, {
3444 raw: true,
3545 prediction: undefined,
3646 reasoning: false,
@@ -63,7 +73,11 @@
6373 }
6474 }
6575 } 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, {
6781 raw: true,
6882 prediction: undefined,
6983 reasoning: false,
@@ -105,3 +119,36 @@
105119 }
106120 }
107121 }
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 @@
44 interface BasicMatchResult {
55 /** The starting character index of the match in the file content */
66 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)*/
88 endIndex: number;
99 }
1010
@@ -43,48 +43,20 @@
4343
4444 /**
4545 * 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
4846 */
4947 function trimmedMatch(
5048 fileContent: string,
5149 searchContent: string,
5250 ): BasicMatchResult | null {
5351 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+ };
8258 }
83-
84- return {
85- startIndex,
86- endIndex,
87- };
59+ return null;
8860 }
8961
9062 /**
@@ -109,32 +81,38 @@
10981 }
11082
11183 // Map the stripped position back to the original file content
112- let originalStartIndex = 0;
84+ let originalStartIndex = -1;
11385 let strippedCharCount = 0;
11486
115- // Find the original position by counting non-whitespace characters
87+ // Find the original start position by counting non-whitespace characters
11688 for (let i = 0; i < fileContent.length; i++) {
117- if (strippedCharCount === strippedIndex) {
118- originalStartIndex = i;
119- break;
120- }
12189 if (!/\s/.test(fileContent[i])) {
90+ if (strippedCharCount === strippedIndex) {
91+ originalStartIndex = i;
92+ break;
93+ }
12294 strippedCharCount++;
12395 }
12496 }
12597
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
127104 let originalEndIndex = originalStartIndex;
128- let matchedChars = 0;
105+ let matchedNonWhitespaceChars = 0;
129106
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++) {
135108 if (!/\s/.test(fileContent[i])) {
136- matchedChars++;
109+ matchedNonWhitespaceChars++;
110+ if (matchedNonWhitespaceChars === strippedSearchContent.length) {
111+ originalEndIndex = i + 1;
112+ break;
113+ }
137114 }
115+ // Always update end index to include current position (whether whitespace or not)
138116 originalEndIndex = i + 1;
139117 }
140118
@@ -146,6 +124,7 @@
146124
147125 /**
148126 * 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
149128 */
150129 function jaroSimilarity(s1: string, s2: string): number {
151130 if (s1 === s2) return 1.0;
@@ -306,7 +285,7 @@
306285 { strategy: exactMatch, name: "exactMatch" },
307286 { strategy: trimmedMatch, name: "trimmedMatch" },
308287 { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
309- { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
288+ // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
310289 ];
311290
312291 /**
@@ -326,24 +305,10 @@
326305 fileContent: string,
327306 searchContent: string,
328307 ): 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
335308 const trimmedSearchContent = searchContent.trim();
309+
336310 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
347312 return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
348313 }
349314
@@ -357,3 +322,58 @@
357322
358323 return null;
359324 }
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 @@
44 ILLM,
55 Prediction,
66 RuleWithSource,
7+ StreamDiffLinesPayload,
78 ToolResultChatMessage,
89 UserChatMessage,
910 } from "../";
@@ -20,6 +21,7 @@
2021 import { streamLines } from "../diff/util";
2122 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2223 import { gptEditPrompt } from "../llm/templates/edit";
24+import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
2325 import { findLast } from "../util/findLast";
2426 import { Telemetry } from "../util/posthog";
2527 import { recursiveStream } from "./recursiveStream";
@@ -42,6 +44,20 @@
4244 });
4345 }
4446
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+
4561 export async function* addIndentation(
4662 diffLineGenerator: AsyncGenerator<DiffLine>,
4763 indentation: string,
@@ -58,27 +74,15 @@
5874 return !(model.includes("gpt") || model.includes("claude"));
5975 }
6076
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+
8286 void Telemetry.capture(
8387 "inlineEdit",
8488 {
@@ -104,27 +108,30 @@
104108 // For apply can be overridden with simply apply prompt
105109 let prompt =
106110 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));
108114
109115 // Rules can be included with edit prompt
110116 // 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;
128135
129136 if (systemMessage) {
130137 if (typeof prompt === "string") {
@@ -158,7 +165,13 @@
158165 content: highlighted,
159166 };
160167
161- const completion = recursiveStream(llm, abortController, prompt, prediction);
168+ const completion = recursiveStream(
169+ llm,
170+ abortController,
171+ type,
172+ prompt,
173+ prediction,
174+ );
162175
163176 let lines = streamLines(completion);
164177
modified core/index.d.ts +42 −14
@@ -173,6 +173,11 @@
173173 }
174174
175175 export type ContextProviderType = "normal" | "query" | "submenu";
176+export type ContextIndexingType =
177+ | "chunk"
178+ | "embeddings"
179+ | "fullTextSearch"
180+ | "codeSnippets";
176181
177182 export interface ContextProviderDescription {
178183 title: ContextProviderName;
@@ -180,7 +185,7 @@
180185 description: string;
181186 renderInlineAs?: string;
182187 type: ContextProviderType;
183- dependsOnIndexing?: boolean;
188+ dependsOnIndexing?: ContextIndexingType[];
184189 }
185190
186191 export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
@@ -267,7 +272,7 @@
267272 history: ChatHistoryItem[];
268273 }
269274
270-export interface SessionMetadata {
275+export interface BaseSessionMetadata {
271276 sessionId: string;
272277 title: string;
273278 dateCreated: string;
@@ -305,11 +310,6 @@
305310 replacement: string;
306311 }
307312
308-export interface ContinueError {
309- title: string;
310- message: string;
311-}
312-
313313 export interface CompletionOptions extends BaseCompletionOptions {
314314 model: string;
315315 }
@@ -456,7 +456,6 @@
456456 export interface PromptLog {
457457 modelTitle: string;
458458 modelProvider: string;
459- completionOptions: CompletionOptions;
460459 prompt: string;
461460 completion: string;
462461 }
@@ -666,6 +665,7 @@
666665 env?: Record<string, string | number | boolean>;
667666
668667 sourceFile?: string;
668+ isFromAutoDetect?: boolean;
669669 }
670670
671671 type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@@ -819,6 +819,8 @@
819819
820820 openUrl(url: string): Promise<void>;
821821
822+ getExternalUri?(uri: string): Promise<string>;
823+
822824 runCommand(command: string, options?: TerminalOptions): Promise<void>;
823825
824826 saveFile(fileUri: string): Promise<void>;
@@ -1070,11 +1072,6 @@
10701072 codeBaseIndexer?: CodebaseIndexer;
10711073 }
10721074
1073-export type ToolPolicy =
1074- | "allowedWithPermission"
1075- | "allowedWithoutPermission"
1076- | "disabled";
1077-
10781075 export interface Tool {
10791076 type: "function";
10801077 function: {
@@ -1099,6 +1096,11 @@
10991096 exampleArgs?: Array<[string, string | number]>;
11001097 };
11011098 defaultToolPolicy?: ToolPolicy;
1099+ toolCallIcon?: string;
1100+ evaluateToolCallPolicy?: (
1101+ basePolicy: ToolPolicy,
1102+ parsedArgs: Record<string, unknown>,
1103+ ) => ToolPolicy;
11021104 }
11031105
11041106 interface ToolChoice {
@@ -1111,6 +1113,9 @@
11111113 export interface ConfigDependentToolParams {
11121114 rules: RuleWithSource[];
11131115 enableExperimentalTools: boolean;
1116+ isSignedIn: boolean;
1117+ isRemote: boolean;
1118+ modelName: string | undefined;
11141119 }
11151120
11161121 export type GetTool = (params: ConfigDependentToolParams) => Tool;
@@ -1174,6 +1179,7 @@
11741179 configurationStatus?: LLMConfigurationStatuses;
11751180
11761181 sourceFile?: string;
1182+ isFromAutoDetect?: boolean;
11771183 }
11781184
11791185 export interface JSONEmbedOptions {
@@ -1273,6 +1279,7 @@
12731279 transport: TransportOptions;
12741280 faviconUrl?: string;
12751281 timeout?: number;
1282+ requestOptions?: RequestOptions;
12761283 }
12771284
12781285 export type MCPConnectionStatus =
@@ -1325,6 +1332,7 @@
13251332 export interface MCPServerStatus extends MCPOptions {
13261333 status: MCPConnectionStatus;
13271334 errors: string[];
1335+ infos: string[];
13281336 isProtectedResource: boolean;
13291337
13301338 prompts: MCPPrompt[];
@@ -1342,6 +1350,7 @@
13421350 codeWrap?: boolean;
13431351 showSessionTabs?: boolean;
13441352 autoAcceptEditToolDiffs?: boolean;
1353+ continueAfterToolRejection?: boolean;
13451354 }
13461355
13471356 export interface ContextMenuConfig {
@@ -1378,9 +1387,12 @@
13781387 fileContent?: string;
13791388 originalFileContent?: string;
13801389 toolCallId?: string;
1390+ autoFormattingDiff?: string;
13811391 }
13821392
1383-export interface StreamDiffLinesPayload {
1393+export type StreamDiffLinesType = "edit" | "apply";
1394+interface StreamDiffLinesOptionsBase {
1395+ type: StreamDiffLinesType;
13841396 prefix: string;
13851397 highlighted: string;
13861398 suffix: string;
@@ -1391,6 +1403,19 @@
13911403 fileUri?: string;
13921404 }
13931405
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+
13941419 export interface HighlightedCodePayload {
13951420 rangeInFileWithContents: RangeInFileWithContents;
13961421 prompt?: string;
@@ -1604,6 +1629,7 @@
16041629 aiGatewaySlug?: string;
16051630 useLegacyCompletionsEndpoint?: boolean;
16061631 deploymentId?: string;
1632+ isFromAutoDetect?: boolean;
16071633 }
16081634
16091635 // config.json
@@ -1681,6 +1707,7 @@
16811707 experimental?: ExperimentalConfig;
16821708 /** Analytics configuration */
16831709 analytics?: AnalyticsConfig;
1710+ docs?: SiteIndexingConfig[];
16841711 data?: DataDestination[];
16851712 }
16861713
@@ -1796,6 +1823,7 @@
17961823 description?: string;
17971824 ruleFile?: string;
17981825 alwaysApply?: boolean;
1826+ invokable?: boolean;
17991827 }
18001828 export interface CompleteOnboardingPayload {
18011829 mode: OnboardingModes;
modified core/indexing/CodebaseIndexer.test.ts +177 −61
@@ -21,6 +21,7 @@
2121 import { ContinueConfig } from "../index.js";
2222 import { localPathToUri } from "../util/pathToUri.js";
2323 import { CodebaseIndexer } from "./CodebaseIndexer.js";
24+import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
2425 import { getComputeDeleteAddRemove } from "./refreshIndex.js";
2526 import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
2627 import { CodebaseIndex } from "./types.js";
@@ -64,8 +65,8 @@
6465 }
6566
6667 // 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();
6970 }
7071
7172 public async testHandleConfigUpdate(
@@ -202,7 +203,7 @@
202203
203204 test("should have indexed all of the files", async () => {
204205 const indexed = await getAllIndexedFiles();
205- expect(indexed.length).toBe(4); // Files are indexed twice due to test execution
206+ expect(indexed.length).toBe(2);
206207 expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
207208 expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
208209 });
@@ -226,7 +227,7 @@
226227
227228 // Check that the new file was indexed
228229 const files = await getAllIndexedFiles();
229- expect(files.length).toBe(5); // Updated to match actual behavior
230+ expect(files.length).toBe(3);
230231 expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
231232 });
232233
@@ -240,7 +241,7 @@
240241
241242 // Check that the deleted file was removed from the index
242243 const files = await getAllIndexedFiles();
243- expect(files.length).toBe(4); // Updated to match actual behavior
244+ expect(files.length).toBe(2);
244245 expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
245246 });
246247
@@ -474,20 +475,14 @@
474475 jest.clearAllMocks();
475476 });
476477
477- describe("hasCodebaseContextProvider", () => {
478+ describe("hasIndexingProvider", () => {
478479 test("should return true when codebase context provider is present", () => {
479480 // Set up config with codebase context provider
480481 (testIndexer as any).config = {
481- contextProviders: [
482- {
483- description: {
484- title: CodebaseContextProvider.description.title,
485- },
486- },
487- ],
482+ contextProviders: [new CodebaseContextProvider({})],
488483 };
489484
490- const result = testIndexer.testHasCodebaseContextProvider();
485+ const result = testIndexer.testHasIndexingProvider();
491486 expect(result).toBe(true);
492487 });
493488
@@ -496,7 +491,7 @@
496491 contextProviders: undefined,
497492 };
498493
499- const result = testIndexer.testHasCodebaseContextProvider();
494+ const result = testIndexer.testHasIndexingProvider();
500495 expect(result).toBe(false);
501496 });
502497
@@ -511,7 +506,7 @@
511506 ],
512507 };
513508
514- const result = testIndexer.testHasCodebaseContextProvider();
509+ const result = testIndexer.testHasIndexingProvider();
515510 expect(result).toBe(false);
516511 });
517512
@@ -520,7 +515,7 @@
520515 contextProviders: [],
521516 };
522517
523- const result = testIndexer.testHasCodebaseContextProvider();
518+ const result = testIndexer.testHasIndexingProvider();
524519 expect(result).toBe(false);
525520 });
526521 });
@@ -535,9 +530,8 @@
535530
536531 await testIndexer.testHandleConfigUpdate(configResult);
537532
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);
541535 });
542536
543537 test("should return early when newConfig is undefined", async () => {
@@ -549,9 +543,8 @@
549543
550544 await testIndexer.testHandleConfigUpdate(configResult);
551545
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);
555548 });
556549
557550 test("should return early when no codebase context provider is present", async () => {
@@ -577,21 +570,14 @@
577570
578571 await testIndexer.testHandleConfigUpdate(configResult);
579572
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);
583575 });
584576
585577 test("should return early when no embed model is configured", async () => {
586578 const configResult: ConfigResult<ContinueConfig> = {
587579 config: {
588- contextProviders: [
589- {
590- description: {
591- title: CodebaseContextProvider.description.title,
592- },
593- },
594- ],
580+ contextProviders: [new CodebaseContextProvider({})],
595581 selectedModelByRole: {
596582 embed: undefined,
597583 },
@@ -602,21 +588,14 @@
602588
603589 await testIndexer.testHandleConfigUpdate(configResult);
604590
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);
608593 });
609594
610595 test("should call refreshCodebaseIndex when all conditions are met", async () => {
611596 const configResult: ConfigResult<ContinueConfig> = {
612597 config: {
613- contextProviders: [
614- {
615- description: {
616- title: CodebaseContextProvider.description.title,
617- },
618- },
619- ],
598+ contextProviders: [new CodebaseContextProvider({})],
620599 selectedModelByRole: {
621600 embed: {
622601 model: "test-model",
@@ -630,9 +609,8 @@
630609
631610 await testIndexer.testHandleConfigUpdate(configResult);
632611
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);
636614 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
637615 "/test/workspace",
638616 ]);
@@ -640,13 +618,7 @@
640618
641619 test("should set config property before checking conditions", async () => {
642620 const testConfig = {
643- contextProviders: [
644- {
645- description: {
646- title: CodebaseContextProvider.description.title,
647- },
648- },
649- ],
621+ contextProviders: [new CodebaseContextProvider({})],
650622 selectedModelByRole: {
651623 embed: {
652624 model: "test-model",
@@ -666,7 +638,7 @@
666638 // Verify that the config was set
667639 expect((testIndexer as any).config).toBe(testConfig);
668640 // These get called once on init, and we want them to get called again
669- expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
641+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
670642 });
671643
672644 test("should handle multiple context providers correctly", async () => {
@@ -678,11 +650,7 @@
678650 title: "SomeOtherProvider",
679651 },
680652 },
681- {
682- description: {
683- title: CodebaseContextProvider.description.title,
684- },
685- },
653+ new CodebaseContextProvider({}),
686654 {
687655 description: {
688656 title: "AnotherProvider",
@@ -702,12 +670,160 @@
702670
703671 await testIndexer.testHandleConfigUpdate(configResult);
704672
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);
707674 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
708675 "/test/workspace",
709676 ]);
710677 });
711678 });
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+ });
712828 });
713829 });
modified core/indexing/CodebaseIndexer.ts +51 −34
@@ -2,6 +2,7 @@
22
33 import { ConfigHandler } from "../config/ConfigHandler.js";
44 import {
5+ ContextIndexingType,
56 ContinueConfig,
67 IDE,
78 IndexingProgressUpdate,
@@ -12,11 +13,9 @@
1213 import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
1314 import { Logger } from "../util/Logger.js";
1415 import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
15-import { Telemetry } from "../util/posthog.js";
1616 import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
1717
1818 import { ConfigResult } from "@continuedev/config-yaml";
19-import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
2019 import { ContinueServerClient } from "../continueServer/stubs/client";
2120 import { LLMError } from "../llm/index.js";
2221 import { getRootCause } from "../util/errors.js";
@@ -60,6 +59,7 @@
6059 private indexingCancellationController: AbortController;
6160 private codebaseIndexingState: IndexingProgressUpdate;
6261 private readonly pauseToken: PauseToken;
62+ private builtIndexes: CodebaseIndex[] = [];
6363
6464 private getUserFriendlyIndexName(artifactId: string): string {
6565 if (artifactId === FullTextSearchCodebaseIndex.artifactId)
@@ -168,28 +168,46 @@
168168 return [];
169169 }
170170
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(),
182176 );
183177
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+ };
187198
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+ }
192209
210+ this.builtIndexes = indexes;
193211 return indexes;
194212 }
195213
@@ -668,14 +686,6 @@
668686 update.desc,
669687 update.debugInfo,
670688 );
671- void Telemetry.capture(
672- "indexing_error",
673- {
674- error: update.desc,
675- stack: update.debugInfo,
676- },
677- false,
678- );
679689 }
680690
681691 /**
@@ -704,6 +714,15 @@
704714 }
705715 }
706716
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+
707726 public async refreshCodebaseIndex(paths: string[]) {
708727 if (!this.indexingCancellationController.signal.aborted) {
709728 this.indexingCancellationController.abort();
@@ -804,11 +823,9 @@
804823 return this.codebaseIndexingState;
805824 }
806825
807- private hasCodebaseContextProvider() {
826+ private hasIndexingContextProvider() {
808827 return !!this.config.contextProviders?.some(
809- (provider) =>
810- provider.description.title ===
811- CodebaseContextProvider.description.title,
828+ ({ description: { dependsOnIndexing } }) => dependsOnIndexing,
812829 );
813830 }
814831
@@ -837,8 +854,8 @@
837854 this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
838855
839856 // 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) {
842859 return;
843860 }
844861
modified core/indexing/chunk/chunk.ts +16 −1
@@ -22,7 +22,22 @@
2222 return;
2323 }
2424 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+ ) {
2641 try {
2742 for await (const chunk of codeChunker(fileUri, contents, maxChunkSize)) {
2843 yield chunk;
modified core/indexing/chunk/code.test.ts +58 −1
@@ -1,5 +1,5 @@
11 import { ChunkWithoutID } from "../..";
2-
2+import { cleanupAsyncEncoders, countTokensAsync } from "../../llm/countTokens";
33 import { codeChunker } from "./code";
44
55 async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {
@@ -71,3 +71,60 @@
7171 expect(chunks).toContain('def method20():\n return "Hello, 20!"');
7272 });
7373 });
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 @@
128128 maxChunkSize: number,
129129 ): Promise<string> {
130130 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 =
136136 node.parent &&
137137 ["block", "declaration_list"].includes(node.parent.type) &&
138138 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;
148169 }
149- return funcText;
170+ return collapsedBody;
150171 }
151172
152173 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 @@
272272 id: doc.startUrl,
273273 isReindexing: false,
274274 title: doc.title,
275- debugInfo: `max depth: ${doc.maxDepth}`,
275+ debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`,
276276 icon: doc.faviconUrl,
277277 url: doc.startUrl,
278278 };
@@ -468,7 +468,7 @@
468468 embeddingsProviderId: provider.embeddingId,
469469 isReindexing: forceReindex && indexExists,
470470 title: siteIndexingConfig.title,
471- debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
471+ debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`,
472472 icon: siteIndexingConfig.faviconUrl,
473473 url: siteIndexingConfig.startUrl,
474474 };
@@ -858,6 +858,27 @@
858858 return docs.map(this.lanceDBRowToChunk);
859859 }
860860
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+
861882 // SQLITE DB
862883 private async getOrCreateSqliteDb() {
863884 if (!this.sqliteDb) {
modified core/indexing/docs/crawlers/DocsCrawler.test.ts +21 −3
@@ -155,9 +155,27 @@
155155 test(
156156 `Default crawler common site: ${url}`,
157157 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+ }
161179 },
162180 TIMEOUT_MS,
163181 );
modified core/indexing/ignore.ts +170 −44
@@ -1,11 +1,101 @@
1-import fs from "fs";
2-
31 import ignore from "ignore";
42
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";
76
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 = [
999 "*.DS_Store",
10100 "*-lock.json",
11101 "*.lock",
@@ -46,8 +136,6 @@
46136 "*.mpeg",
47137 "*.mov",
48138 "*.mp3",
49- "*.mp4",
50- "*.mkv",
51139 "*.mkv",
52140 "*.webm",
53141 "*.jar",
@@ -56,20 +144,15 @@
56144 "*.pqt",
57145 "*.wav",
58146 "*.webp",
59- "*.db",
60- "*.sqlite",
61147 "*.wasm",
62148 "*.plist",
63149 "*.profraw",
64150 "*.gcda",
65151 "*.gcno",
66152 "go.sum",
67- "*.env",
68153 "*.gitignore",
69154 "*.gitkeep",
70155 "*.continueignore",
71- "config.json",
72- "config.yaml",
73156 "*.csv",
74157 "*.uasset",
75158 "*.pdb",
@@ -78,19 +161,13 @@
78161 "*.swp",
79162 "*.jsonl",
80163 // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
164+ // Application specific
165+ ".continue/",
81166 ];
82167
83-export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
84-export const DEFAULT_IGNORE_DIRS = [
168+export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
85169 ".git/",
86170 ".svn/",
87- ".vscode/",
88- ".idea/",
89- ".vs/",
90- "venv/",
91- ".venv/",
92- "env/",
93- ".env/",
94171 "node_modules/",
95172 "dist/",
96173 "build/",
@@ -100,7 +177,6 @@
100177 "bin/",
101178 ".pytest_cache/",
102179 ".vscode-test/",
103- ".continue/",
104180 "__pycache__/",
105181 "site-packages/",
106182 ".gradle/",
@@ -108,42 +184,92 @@
108184 ".cache/",
109185 "gems/",
110186 "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,
111210 ];
112211
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);
113222 export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
114223
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+
115230 export const DEFAULT_IGNORE =
116231 DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
117232
233+// Combined ignore instances
234+export const defaultFileAndFolderSecurityIgnores = ignore()
235+ .add(defaultSecurityIgnoreFile)
236+ .add(defaultSecurityIgnoreDir);
237+
118238 export const defaultIgnoreFileAndDir = ignore()
119239 .add(defaultIgnoreFile)
120240 .add(defaultIgnoreDir);
121241
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+
122270 export function gitIgArrayFromFile(file: string) {
123271 return file
124272 .split(/\r?\n/) // Split on new line
125273 .map((l) => l.trim()) // Remove whitespace
126274 .filter((l) => !/^#|^$/.test(l)); // Remove empty lines
127275 }
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 @@
11 import ignore from "ignore";
22 import type { FileType, IDE } from "../";
33 import { findUriInDirs, getUriPathBasename } from "../util/uri";
4-import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
4+import { getGlobalContinueIgArray } from "./continueignore";
5+import { defaultIgnoreFileAndDir } from "./ignore";
56 import { getIgnoreContext } from "./walkDir";
67
78 /*
modified core/indexing/walkDir.ts +2 −5
@@ -3,11 +3,8 @@
33 import type { FileType, IDE } from "..";
44
55 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";
118
129 export interface WalkerOptions {
1310 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";
27 import { NEXT_EDIT_MODELS } from "./constants.js";
38
49 import {
@@ -40,6 +45,7 @@
4045
4146 const PROVIDER_HANDLES_TEMPLATING: string[] = [
4247 "lmstudio",
48+ "lemonade",
4349 "openai",
4450 "nvidia",
4551 "ollama",
@@ -62,6 +68,7 @@
6268 const PROVIDER_SUPPORTS_IMAGES: string[] = [
6369 "openai",
6470 "ollama",
71+ "lemonade",
6572 "cohere",
6673 "gemini",
6774 "msty",
@@ -80,26 +87,24 @@
8087 "watsonx",
8188 ];
8289
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/,
103108 ];
104109
105110 function modelSupportsImages(
@@ -115,10 +120,14 @@
115120 return false;
116121 }
117122
118- const lower = model.toLowerCase();
123+ const lowerModel = model.toLowerCase();
124+ const lowerTitle = title?.toLowerCase() ?? "";
125+
119126 if (
127+ lowerModel.includes("vision") ||
128+ lowerTitle.includes("vision") ||
120129 MODEL_SUPPORTS_IMAGES.some(
121- (modelName) => lower.includes(modelName) || title?.includes(modelName),
130+ (modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle),
122131 )
123132 ) {
124133 return true;
@@ -126,6 +135,26 @@
126135
127136 return false;
128137 }
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+
129158 const PARALLEL_PROVIDERS: string[] = [
130159 "anthropic",
131160 "bedrock",
@@ -177,7 +206,7 @@
177206 // NOTE: When updating this list,
178207 // update core/nextEdit/templating/NextEditPromptEngine.ts as well.
179208 const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
180- NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
209+ NEXT_EDIT_MODELS.MERCURY_CODER,
181210 NEXT_EDIT_MODELS.INSTINCT,
182211 ];
183212
@@ -421,4 +450,5 @@
421450 llmCanGenerateInParallel,
422451 modelSupportsImages,
423452 modelSupportsNextEdit,
453+ modelSupportsReasoning,
424454 };
modified core/llm/autodetect.vitest.ts +12 −12
@@ -220,7 +220,7 @@
220220 expect(
221221 modelSupportsNextEdit(
222222 { nextEdit: false },
223- "mercury-coder-nextedit",
223+ "mercury-coder",
224224 "Mercury Coder",
225225 ),
226226 ).toBe(false);
@@ -231,7 +231,7 @@
231231 expect(
232232 modelSupportsNextEdit(
233233 { nextEdit: false },
234- "mercury-coder-nextedit",
234+ "mercury-coder",
235235 "Mercury Coder",
236236 ),
237237 ).toBe(false);
@@ -239,10 +239,10 @@
239239 });
240240
241241 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+ );
246246 });
247247
248248 it("should return true for instinct", () => {
@@ -255,7 +255,7 @@
255255 expect(
256256 modelSupportsNextEdit(
257257 undefined,
258- "provider/mercury-coder-nextedit-v2",
258+ "provider/mercury-coder-v2",
259259 undefined,
260260 ),
261261 ).toBe(true);
@@ -266,7 +266,7 @@
266266 modelSupportsNextEdit(
267267 undefined,
268268 "some-model",
269- "This is mercury-coder-nextedit model",
269+ "This is mercury-coder model",
270270 ),
271271 ).toBe(true);
272272 });
@@ -312,14 +312,14 @@
312312 });
313313
314314 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+ );
318318 });
319319
320320 it("should handle case sensitivity correctly", () => {
321321 expect(
322- modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
322+ modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"),
323323 ).toBe(true);
324324 });
325325
modified core/llm/constants.ts +1 −1
@@ -20,7 +20,7 @@
2020 }
2121
2222 export enum NEXT_EDIT_MODELS {
23- MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
23+ MERCURY_CODER = "mercury-coder",
2424 INSTINCT = "instinct",
2525 }
2626
modified core/llm/countTokens.ts +1 −1
@@ -85,7 +85,7 @@
8585
8686 function countImageTokens(content: MessagePart): number {
8787 if (content.type === "imageUrl") {
88- return 85;
88+ return 1024;
8989 }
9090 throw new Error("Non-image content type");
9191 }
modified core/llm/defaultSystemMessages.ts +11 −1
@@ -46,6 +46,8 @@
4646 of changes unless the user specifically asks for code only.
4747 `;
4848
49+const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`;
50+
4951 export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
5052 <important_rules>
5153 You are in chat mode.
@@ -64,6 +66,11 @@
6466 If you need to use multiple tools, you can call multiple read only tools simultaneously.
6567
6668 ${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+
6774 </important_rules>`;
6875
6976 // The note about read-only tools is for MCP servers
@@ -75,7 +82,10 @@
7582 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.
7683
7784 ${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.
7989
8090 In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
8191 </important_rules>`;
modified core/llm/index.test.ts +21 −0
@@ -95,10 +95,31 @@
9595 test("should return true when modelSupportsImages returns true", () => {
9696 baseLLM.model = "gpt-4-vision";
9797 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);
98116 });
99117
100118 test("should return false when modelSupportsImages returns false", () => {
101119 expect(baseLLM.supportsImages()).toBe(false);
120+
121+ baseLLM.model = "gemma3n";
122+ expect(baseLLM.supportsImages()).toBe(false);
102123 });
103124 });
104125
modified core/llm/index.ts +49 −30
@@ -9,7 +9,6 @@
99 import Handlebars from "handlebars";
1010
1111 import { DevDataSqliteDb } from "../data/devdataSqlite.js";
12-import { Logger } from "../util/Logger.js";
1312 import { DataLogger } from "../data/log.js";
1413 import {
1514 CacheBehavior,
@@ -31,10 +30,12 @@
3130 TemplateType,
3231 Usage,
3332 } from "../index.js";
33+import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
34+import { Logger } from "../util/Logger.js";
3435 import mergeJson from "../util/merge.js";
3536 import { renderChatMessage } from "../util/messageContent.js";
3637 import { isOllamaInstalled } from "../util/ollamaHelper.js";
37-import { Telemetry } from "../util/posthog.js";
38+import { TokensBatchingService } from "../util/TokensBatchingService.js";
3839 import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
3940
4041 import {
@@ -191,6 +192,8 @@
191192 //URI to local block defining this LLM
192193 sourceFile?: string;
193194
195+ isFromAutoDetect?: boolean;
196+
194197 private _llmOptions: LLMOptions;
195198
196199 protected openaiAdapter?: BaseLlmApi;
@@ -294,6 +297,7 @@
294297
295298 this.autocompleteOptions = options.autocompleteOptions;
296299 this.sourceFile = options.sourceFile;
300+ this.isFromAutoDetect = options.isFromAutoDetect;
297301 }
298302
299303 get contextLength() {
@@ -343,15 +347,11 @@
343347 let generatedTokens = this.countTokens(completion);
344348 let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
345349
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,
355355 );
356356
357357 void DevDataSqliteDb.logTokensGenerated(
@@ -371,8 +371,17 @@
371371 },
372372 });
373373
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")) {
376385 interaction?.logItem({
377386 kind: "cancel",
378387 promptTokens,
@@ -394,15 +403,6 @@
394403 });
395404 return "error";
396405 }
397- } else {
398- interaction?.logItem({
399- kind: "success",
400- promptTokens,
401- generatedTokens,
402- thinkingTokens,
403- usage,
404- });
405- return "success";
406406 }
407407 }
408408
@@ -504,6 +504,24 @@
504504 : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
505505 throw new Error(message);
506506 }
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+ }
507525 }
508526 throw e;
509527 }
@@ -538,18 +556,14 @@
538556 }
539557
540558 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
546562 ?.map(
547563 (toolCall) =>
548564 `${toolCall.function?.name}(${toolCall.function?.arguments})`,
549565 )
550566 .join("\n");
551- } else if ("content" in msg) {
552- contentToShow = renderChatMessage(msg);
553567 }
554568
555569 return `<${msg.role}>\n${contentToShow}\n\n`;
@@ -616,6 +630,7 @@
616630 kind: "chunk",
617631 chunk: formattedContent,
618632 });
633+
619634 completion += formattedContent;
620635 yield content;
621636 }
@@ -631,6 +646,7 @@
631646 kind: "chunk",
632647 chunk,
633648 });
649+
634650 completion += chunk;
635651 yield chunk;
636652 }
@@ -1040,6 +1056,10 @@
10401056 const msg = fromChatResponse(response);
10411057 yield msg;
10421058 completion = this._formatChatMessage(msg);
1059+ interaction?.logItem({
1060+ kind: "message",
1061+ message: msg,
1062+ });
10431063 } else {
10441064 // Stream true
10451065 const stream = this.openaiAdapter.chatCompletionStream(
@@ -1143,7 +1163,6 @@
11431163 modelProvider: this.underlyingProviderName,
11441164 prompt,
11451165 completion,
1146- completionOptions,
11471166 };
11481167 }
11491168
modified core/llm/llm-pre-fetch.vitest.ts +0 −3
@@ -19,9 +19,6 @@
1919 await gen.next();
2020 await gen.return({
2121 completion: "",
22- completionOptions: {
23- model: "",
24- },
2522 modelTitle: "",
2623 modelProvider: "",
2724 prompt: "",
modified core/llm/llm.test.ts +12 −2
@@ -145,6 +145,7 @@
145145 description: "Say Hello",
146146 parameters: {
147147 type: "object",
148+ required: ["name"],
148149 properties: {
149150 name: {
150151 type: "string",
@@ -165,7 +166,7 @@
165166 },
166167 )) {
167168 const typedChunk = chunk as AssistantChatMessage;
168- if (!typedChunk.toolCalls) {
169+ if (!typedChunk.toolCalls || typedChunk.toolCalls.length === 0) {
169170 continue;
170171 }
171172 const toolCall = typedChunk.toolCalls[0];
@@ -182,6 +183,15 @@
182183 }
183184 }
184185
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+
185195 const parsedArgs = JSON.parse(args);
186196 expect(parsedArgs.name).toBe("Nate");
187197 }),
@@ -203,7 +213,7 @@
203213
204214 testLLM(
205215 new Anthropic({
206- model: "claude-3-5-sonnet-latest",
216+ model: "claude-sonnet-4-0",
207217 apiKey: process.env.ANTHROPIC_API_KEY,
208218 }),
209219 { skip: false, testToolCall: true },
modified core/llm/llms/Anthropic.ts +31 −6
@@ -68,6 +68,17 @@
6868 return finalOptions;
6969 }
7070
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+
7182 private convertMessage(message: ChatMessage, addCaching: boolean): any {
7283 if (message.role === "tool") {
7384 return {
@@ -81,14 +92,30 @@
8192 ],
8293 };
8394 } 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) => ({
87110 type: "tool_use",
88111 id: toolCall.id,
89112 name: toolCall.function?.name,
90113 input: safeParseToolCallArgs(toolCall),
91114 })),
115+ );
116+ return {
117+ role: "assistant",
118+ content: parts,
92119 };
93120 } else if (message.role === "thinking" && !message.redactedThinking) {
94121 return {
@@ -154,9 +181,7 @@
154181
155182 public convertMessages(msgs: ChatMessage[]): any[] {
156183 // 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");
160185 const lastTwoUserMsgIndices = filteredmessages
161186 .map((msg, index) => (msg.role === "user" ? index : -1))
162187 .filter((index) => index !== -1)
modified core/llm/llms/Bedrock.test.ts +91 −1
@@ -532,7 +532,7 @@
532532 );
533533 });
534534
535- it("should add cache points for prompt caching when needed", () => {
535+ it("should add cache points when cacheBehavior.cacheConversation is enabled", () => {
536536 // Create a test instance with caching behavior enabled
537537 const bedrockWithCaching = new TestBedrock({
538538 apiKey: "test-key",
@@ -576,5 +576,95 @@
576576 const userMessageText = converted[0].content?.[0].text;
577577 expect(userMessageText).toMatch(/First message.+/);
578578 });
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+ });
579669 });
580670 });
modified core/llm/llms/Bedrock.ts +71 −78
@@ -1,13 +1,19 @@
11 import {
22 BedrockRuntimeClient,
33 ContentBlock,
4+ ContentBlockDelta,
5+ ContentBlockStart,
6+ ContentBlockStartEvent,
47 ConversationRole,
58 ConverseStreamCommand,
69 ConverseStreamCommandOutput,
710 ImageFormat,
811 InvokeModelCommand,
912 Message,
13+ ReasoningContentBlockDelta,
1014 ToolConfiguration,
15+ ToolUseBlock,
16+ ToolUseBlockDelta,
1117 } from "@aws-sdk/client-bedrock-runtime";
1218 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
1319
@@ -25,15 +31,6 @@
2531 extractEmbeddings: (responseBody: any) => number[][];
2632 }
2733
28-/**
29- * Interface for tool use state tracking
30- */
31-interface ToolUseState {
32- toolUseId: string;
33- name: string;
34- input: string;
35-}
36-
3734 /**
3835 * Interface for prompt caching metrics
3936 */
@@ -50,7 +47,6 @@
5047 profile: "bedrock",
5148 };
5249
53- private _currentToolResponse: Partial<ToolUseState> | null = null;
5450 private _promptCachingMetrics: PromptCachingMetrics = {
5551 cacheReadInputTokens: 0,
5652 cacheWriteInputTokens: 0,
@@ -149,108 +145,99 @@
149145 console.log(`${JSON.stringify(chunk.metadata.usage)}`);
150146 }
151147
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) {
155151 // Handle text content
156- if (chunk.contentBlockDelta.delta.text) {
152+ if (contentBlockDelta.text) {
157153 yield {
158154 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,
170156 };
171157 continue;
172158 }
173-
174- // Handle signature for thinking
175- if (delta.reasoningContent?.signature) {
159+ if (contentBlockDelta.reasoningContent?.text) {
176160 yield {
177161 role: "thinking",
178- content: "",
179- signature: delta.reasoningContent.signature,
162+ content: contentBlockDelta.reasoningContent.text,
180163 };
181164 continue;
182165 }
183-
184- // Handle redacted thinking
185- if (delta.redactedReasoning?.data) {
166+ if (contentBlockDelta.reasoningContent?.signature) {
186167 yield {
187168 role: "thinking",
188169 content: "",
189- redactedThinking: delta.redactedReasoning.data,
170+ signature: contentBlockDelta.reasoningContent.signature,
190171 };
191172 continue;
192173 }
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- }
206174 }
207175
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) {
211180 yield {
212181 role: "thinking",
213182 content: "",
214- redactedThinking: start.redactedReasoning.data,
183+ redactedThinking: reasoningDelta.text,
215184 };
216185 continue;
217186 }
187+ }
218188
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+ };
227208 continue;
228209 }
229210
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+ },
242231 },
243- },
244- ],
245- };
246- this._currentToolResponse = null;
232+ ],
233+ };
234+ continue;
235+ }
247236 }
248- continue;
249237 }
250238 }
251239 } catch (error: unknown) {
252240 // Clean up state and let the original error bubble up to the retry decorator
253- this._currentToolResponse = null;
254241 throw error;
255242 }
256243 }
@@ -348,6 +335,9 @@
348335 budget_tokens: options.reasoningBudgetTokens,
349336 }
350337 : undefined,
338+ anthropic_beta: options.model.includes("claude")
339+ ? ["fine-grained-tool-streaming-2025-05-14"]
340+ : undefined,
351341 },
352342 };
353343 }
@@ -513,7 +503,10 @@
513503 // The second-to-last because it retrieves potentially already cached contents,
514504 // The last one because we want it cached for later retrieval.
515505 // 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+ ) {
517510 this._addCachingToLastTwoUserMessages(converted);
518511 }
519512
modified core/llm/llms/Inception.ts +123 −1
@@ -1,6 +1,9 @@
11 import { streamSse } from "@continuedev/fetch";
2-import { CompletionOptions, LLMOptions } from "../../index.js";
2+import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
33
4+import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
5+import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js";
6+import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
47 import OpenAI from "./OpenAI.js";
58
69 /**
@@ -32,6 +35,26 @@
3235 return true;
3336 }
3437
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+
3558 async *_streamFim(
3659 prefix: string,
3760 suffix: string,
@@ -67,6 +90,105 @@
6790 yield chunk.choices[0].text;
6891 }
6992 }
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+ }
70192 }
71193
72194 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 @@
99 CompletionOptions,
1010 LLMOptions,
1111 ModelInstaller,
12+ ThinkingChatMessage,
1213 } from "../../index.js";
1314 import { renderChatMessage } from "../../util/messageContent.js";
1415 import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
@@ -18,6 +19,7 @@
1819 role: ChatMessageRole;
1920 content: string;
2021 images?: string[] | null;
22+ thinking?: string;
2123 tool_calls?: {
2224 function: {
2325 name: string;
@@ -85,6 +87,7 @@
8587 tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
8688 // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
8789 // And correspondingly, tool calls in OllamaChatMessage
90+ think?: boolean; // if true the model will be prompted to think about the response before generating it
8891 }
8992
9093 type OllamaBaseResponse = {
@@ -144,7 +147,6 @@
144147 private static modelsBeingInstalledMutex = new Mutex();
145148
146149 private fimSupported: boolean = false;
147-
148150 constructor(options: LLMOptions) {
149151 super(options);
150152
@@ -267,6 +269,11 @@
267269 return this.modelMap[this.model] ?? this.model;
268270 }
269271
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+
270277 private _getModelFileParams(
271278 options: CompletionOptions,
272279 ): OllamaModelFileParams {
@@ -391,6 +398,7 @@
391398 model: this._getModel(),
392399 messages: ollamaMessages,
393400 options: this._getModelFileParams(options),
401+ think: options.reasoning,
394402 keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
395403 stream: options.stream,
396404 // format: options.format, // Not currently in base completion options
@@ -420,24 +428,35 @@
420428 signal,
421429 });
422430
423- function convertChatMessage(res: OllamaChatResponse): ChatMessage {
431+ function convertChatMessage(res: OllamaChatResponse): ChatMessage[] {
424432 if ("error" in res) {
425433 throw new Error(res.error);
426434 }
427- if (res.message.role === "tool") {
435+
436+ const { role, content, thinking, tool_calls: toolCalls } = res.message;
437+
438+ if (role === "tool") {
428439 throw new Error(
429- "Unexpected message received from ollama with role = tool",
440+ "Unexpected message received from Ollama with role = tool",
430441 );
431442 }
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) {
438457 // Continue handles the response as a tool call delta but
439458 // 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) => ({
441460 type: "function",
442461 id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
443462 function: {
@@ -446,13 +465,13 @@
446465 },
447466 }));
448467 }
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];
455471 }
472+
473+ // Fallback for all other roles
474+ return [{ role, content }];
456475 }
457476
458477 if (chatOptions.stream === false) {
@@ -460,7 +479,9 @@
460479 return; // Aborted by user
461480 }
462481 const json = (await response.json()) as OllamaChatResponse;
463- yield convertChatMessage(json);
482+ for (const msg of convertChatMessage(json)) {
483+ yield msg;
484+ }
464485 } else {
465486 let buffer = "";
466487 for await (const value of streamResponse(response)) {
@@ -475,8 +496,9 @@
475496 if (chunk.trim() !== "") {
476497 try {
477498 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+ }
480502 } catch (e) {
481503 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
482504 }
modified core/llm/llms/OpenAI.ts +1 −1
@@ -174,7 +174,7 @@
174174 protected _getHeaders() {
175175 return {
176176 "Content-Type": "application/json",
177- Authorization: `Bearer ${this.apiKey}`,
177+ ...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }),
178178 "api-key": this.apiKey ?? "", // For Azure
179179 };
180180 }
modified core/llm/llms/Scaleway.ts +8 −1
@@ -7,16 +7,23 @@
77 static providerName = "scaleway";
88 static defaultOptions: Partial<LLMOptions> = {
99 apiBase: "https://api.scaleway.ai/v1/",
10- model: "qwen2.5-coder-32b-instruct",
10+ model: "qwen3-coder-30b-a3b-instruct",
1111 useLegacyCompletionsEndpoint: false,
1212 };
1313
1414 private static MODEL_IDS: { [name: string]: string } = {
1515 "llama3.1-8b": "llama-3.1-8b-instruct",
1616 "llama3.3-70b": "llama-3.3-70b-instruct",
17+ "pixtral-12b": "pixtral-12b-2409",
1718 "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",
1821 "deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b",
1922 "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",
2027 };
2128
2229 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 @@
2525 constructor(options: LLMOptions) {
2626 super(options);
2727
28- if (options.model === "AUTODETECT") {
28+ if (options.isFromAutoDetect) {
2929 this._setupCompletionOptions();
3030 }
3131 }
@@ -45,7 +45,7 @@
4545 // vLLM uses 'results' array instead of 'data'
4646 if (results.results && Array.isArray(results.results)) {
4747 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);
4949 }
5050
5151 throw new Error(
modified core/llm/llms/index.ts +4 −0
@@ -33,6 +33,7 @@
3333 import LlamaCpp from "./LlamaCpp";
3434 import Llamafile from "./Llamafile";
3535 import LlamaStack from "./LlamaStack";
36+import Lemonade from "./Lemonade";
3637 import LMStudio from "./LMStudio";
3738 import Mistral from "./Mistral";
3839 import MockLLM from "./Mock";
@@ -53,6 +54,7 @@
5354 import Scaleway from "./Scaleway";
5455 import SiliconFlow from "./SiliconFlow";
5556 import ContinueProxy from "./stubs/ContinueProxy";
57+import TARS from "./TARS";
5658 import TestLLM from "./Test";
5759 import TextGenWebUI from "./TextGenWebUI";
5860 import Together from "./Together";
@@ -81,6 +83,7 @@
8183 LlamaCpp,
8284 OpenAI,
8385 OVHcloud,
86+ Lemonade,
8487 LMStudio,
8588 Mistral,
8689 Bedrock,
@@ -116,6 +119,7 @@
116119 Inception,
117120 Voyage,
118121 LlamaStack,
122+ TARS,
119123 ];
120124
121125 export async function llmFromDescription(
modified core/llm/openaiTypeConverters.ts +36 −19
@@ -101,15 +101,17 @@
101101 };
102102
103103 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+ }));
113115 }
114116
115117 return params;
@@ -158,7 +160,16 @@
158160 return {
159161 role: "assistant",
160162 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+ })),
162173 };
163174 }
164175
@@ -179,18 +190,24 @@
179190 content: delta.content,
180191 };
181192 } 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) => ({
186196 id: tool_call.id,
187- type: tool_call.type,
197+ type: "function" as const,
188198 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,
191201 },
192- })),
193- };
202+ }));
203+
204+ if (toolCalls.length > 0) {
205+ return {
206+ role: "assistant",
207+ content: "",
208+ toolCalls,
209+ };
210+ }
194211 }
195212
196213 return undefined;
modified core/llm/rules/nestedDirectoryRules.vitest.ts +1 −1
@@ -20,7 +20,7 @@
2020 // A global rule for comparison
2121 const globalRule: RuleWithSource = {
2222 name: "Global Rule",
23- rule: "SOLID Design Principles - Coding Assistant Guidelines",
23+ rule: "SOLID Design Principles - Coding Agent Guidelines",
2424 source: "rules-block",
2525 ruleFile: ".continue/rules.md",
2626 };
modified core/llm/streamChat.ts +1 −1
@@ -95,7 +95,7 @@
9595 ...init,
9696 signal: abortController.signal,
9797 },
98- config.requestOptions,
98+ model.requestOptions,
9999 ),
100100 completionOptions,
101101 abortController,
modified core/llm/templates/edit.ts +1 −1
@@ -164,7 +164,7 @@
164164 \`\`\`{{{language}}}
165165 `;
166166
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.
168168 <user>: Please rewrite the following code with these instructions: "{{{userInput}}}"
169169 \`\`\`{{{language}}}
170170 {{{codeToEdit}}}
modified core/llm/templates/edit/gpt.ts +7 −0
@@ -71,3 +71,10 @@
7171
7272 return paragraphs.join("\n\n");
7373 };
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 @@
280280 });
281281 });
282282
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+
283320 describe("edge cases", () => {
284321 it("should handle empty model names", () => {
285322 expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false);
@@ -288,6 +325,7 @@
288325 expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
289326 expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
290327 expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
328+ expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false);
291329 });
292330
293331 it("should handle non-existent provider", () => {
modified core/llm/toolSupport.ts +41 −2
@@ -124,6 +124,7 @@
124124 "nova-pro",
125125 "nova-micro",
126126 "nova-premier",
127+ "gpt-oss",
127128 ].some((part) => model.toLowerCase().includes(part))
128129 ) {
129130 return true;
@@ -239,6 +240,13 @@
239240 },
240241 openrouter: (model) => {
241242 // 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+
242250 if (
243251 ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
244252 (part) => model.toLowerCase().includes(part),
@@ -295,6 +303,7 @@
295303 "meta-llama/llama-3-70b-instruct",
296304 "arcee-ai/caller-large",
297305 "nousresearch/hermes-3-llama-3.1-70b",
306+ "moonshotai/kimi-k2",
298307 ];
299308 for (const model of specificModels) {
300309 if (model.toLowerCase() === model) {
@@ -325,6 +334,36 @@
325334 return true;
326335 }
327336
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+
328367 return false;
329368 },
330369 };
@@ -335,8 +374,8 @@
335374 [/o[134]/],
336375 [/deepseek/, /r1|reasoner/],
337376 [/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/],
340379 [/claude/, /opus/, /-4/],
341380 ];
342381 for (const combo of recs) {
modified core/nextEdit/NextEditEditableRegionCalculator.ts +4 −0
@@ -13,6 +13,10 @@
1313 Static = "static",
1414 }
1515
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+ */
1620 export async function getNextEditableRegion(
1721 strategy: EditableRegionStrategy,
1822 ctx: any,
modified core/nextEdit/NextEditLoggingService.ts +110 −1
@@ -11,6 +11,16 @@
1111 private _abortControllers = new Map<string, AbortController>();
1212 private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
1313 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+ >();
1424 _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
1525 undefined;
1626
@@ -26,21 +36,54 @@
2636 public createAbortController(completionId: string): AbortController {
2737 const abortController = new AbortController();
2838 this._abortControllers.set(completionId, abortController);
39+ this.trackPendingCompletion(completionId);
2940 return abortController;
3041 }
3142
3243 public deleteAbortController(completionId: string) {
3344 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+ }
3474 }
3575
3676 public cancel() {
37- this._abortControllers.forEach((abortController, id) => {
77+ this._abortControllers.forEach((abortController, completionId) => {
78+ this.handleAbort(completionId);
3879 abortController.abort();
3980 });
4081 this._abortControllers.clear();
4182 }
4283
4384 public accept(completionId: string): NextEditOutcome | undefined {
85+ this._pendingCompletions.delete(completionId);
86+
4487 if (this._logRejectionTimeouts.has(completionId)) {
4588 clearTimeout(this._logRejectionTimeouts.get(completionId));
4689 this._logRejectionTimeouts.delete(completionId);
@@ -48,6 +91,7 @@
4891 if (this._outcomes.has(completionId)) {
4992 const outcome = this._outcomes.get(completionId)!;
5093 outcome.accepted = true;
94+ outcome.aborted = false;
5195 this.logNextEditOutcome(outcome);
5296 this._outcomes.delete(completionId);
5397 return outcome;
@@ -55,6 +99,8 @@
5599 }
56100
57101 public reject(completionId: string): NextEditOutcome | undefined {
102+ this._pendingCompletions.delete(completionId);
103+
58104 if (this._logRejectionTimeouts.has(completionId)) {
59105 clearTimeout(this._logRejectionTimeouts.get(completionId));
60106 this._logRejectionTimeouts.delete(completionId);
@@ -63,6 +109,7 @@
63109 if (this._outcomes.has(completionId)) {
64110 const outcome = this._outcomes.get(completionId)!;
65111 outcome.accepted = false;
112+ outcome.aborted = false;
66113 this.logNextEditOutcome(outcome);
67114 this._outcomes.delete(completionId);
68115 return outcome;
@@ -86,12 +133,19 @@
86133 }
87134
88135 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+
89140 const logRejectionTimeout = setTimeout(() => {
90141 // Wait 10 seconds, then assume it wasn't accepted
91142 outcome.accepted = false;
143+ outcome.aborted = false;
92144 this.logNextEditOutcome(outcome);
93145 this._logRejectionTimeouts.delete(completionId);
146+ this._outcomes.delete(completionId);
94147 }, COUNT_COMPLETION_REJECTED_AFTER);
148+
95149 this._outcomes.set(completionId, outcome);
96150 this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
97151
@@ -124,7 +178,62 @@
124178 };
125179 }
126180
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+
127232 private logNextEditOutcome(outcome: NextEditOutcome) {
233+ if (outcome.aborted === undefined) {
234+ outcome.aborted = false;
235+ }
236+
128237 void DataLogger.getInstance().logDevData({
129238 name: "nextEditOutcome",
130239 data: outcome,
modified core/nextEdit/NextEditPrefetchQueue.ts +8 −0
@@ -7,6 +7,14 @@
77 outcome: NextEditOutcome; // Result from the model
88 }
99
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+ */
1018 export class PrefetchQueue {
1119 private static instance: PrefetchQueue | null = null;
1220
modified core/nextEdit/NextEditProvider.ts +128 −622
@@ -1,15 +1,6 @@
1-import * as path from "path";
21 import { v4 as uuidv4 } from "uuid";
32 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";
134 import OpenAI from "../llm/llms/OpenAI.js";
145 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
156
@@ -18,10 +9,7 @@
189 import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
1910 import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
2011 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";
2513 import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
2614 import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
2715 import { getAst } from "../autocomplete/util/ast.js";
@@ -29,37 +17,22 @@
2917 import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
3018 import { HelperVars } from "../autocomplete/util/HelperVars.js";
3119 import { AutocompleteInput } from "../autocomplete/util/types.js";
32-import { myersDiff } from "../diff/myers.js";
20+import { isSecurityConcern } from "../indexing/ignore.js";
3321 import { modelSupportsNextEdit } from "../llm/autodetect.js";
34-import { countTokens } from "../llm/countTokens.js";
3522 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";
4223 import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
43-import {
44- calculateFinalCursorPosition,
45- DiffGroup,
46- groupDiffLines,
47-} from "./diff/diff.js";
4824 import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
4925 import { NextEditLoggingService } from "./NextEditLoggingService.js";
5026 import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
27+import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
28+import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
5129 import {
52- renderDefaultSystemPrompt,
53- renderDefaultUserPrompt,
54- renderPrompt,
55-} from "./templating/NextEditPromptEngine.js";
56-import {
30+ ModelSpecificContext,
5731 NextEditOutcome,
5832 Prompt,
5933 PromptMetadata,
6034 RecentlyEditedRange,
6135 } from "./types.js";
62-import { isWhitespaceOnlyDeletion } from "./utils.js";
6336
6437 const autocompleteCache = AutocompleteLruCache.get();
6538
@@ -71,6 +44,14 @@
7144 "operation was aborted",
7245 ];
7346
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+ */
7455 export class NextEditProvider {
7556 private static instance: NextEditProvider | null = null;
7657
@@ -88,7 +69,9 @@
8869 private currentEditChainId: string | null = null;
8970 private previousRequest: AutocompleteInput | null = null;
9071 private previousCompletions: NextEditOutcome[] = [];
91- // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
72+
73+ // Model-specific provider instance.
74+ private modelProvider: BaseNextEditModelProvider | null = null;
9275
9376 private constructor(
9477 private readonly configHandler: ConfigHandler,
@@ -246,14 +229,14 @@
246229
247230 this.currentEditChainId = null;
248231 this.previousCompletions = [];
249- // TODO: this should be cleaned up in the prefetch queue.
250- // this.nextEditableRegionsInTheCurrentChain = [];
251232
252233 if (this.previousRequest) {
253234 const fileContent = (
254235 await this.ide.readFile(this.previousRequest.filepath)
255236 ).toString();
237+
256238 const ast = await getAst(this.previousRequest.filepath, fileContent);
239+
257240 if (ast) {
258241 DocumentHistoryTracker.getInstance().push(
259242 localPathOrUriToPath(this.previousRequest.filepath),
@@ -276,6 +259,9 @@
276259 return this.previousCompletions.length === 1;
277260 }
278261
262+ /**
263+ * This is the main entry point to this class.
264+ */
279265 public async provideInlineCompletionItems(
280266 input: AutocompleteInput,
281267 token: AbortSignal | undefined,
@@ -284,6 +270,9 @@
284270 usingFullFileDiff: boolean;
285271 },
286272 ): Promise<NextEditOutcome | undefined> {
273+ if (isSecurityConcern(input.filepath)) {
274+ return undefined;
275+ }
287276 try {
288277 this.previousRequest = input;
289278 const {
@@ -293,28 +282,23 @@
293282 } = await this._initializeCompletionRequest(input, token);
294283 if (!helper) return undefined;
295284
285+ // Create model-specific provider based on the model name.
286+ this.modelProvider = NextEditProviderFactory.createProvider(
287+ helper.modelName,
288+ );
289+
296290 const { editableRegionStartLine, editableRegionEndLine, prompts } =
297291 await this._generatePrompts(helper, opts);
298292
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+ );
318302 } catch (e: any) {
319303 this.onError(e);
320304 } finally {
@@ -330,17 +314,21 @@
330314 startTime: number;
331315 helper: HelperVars | undefined;
332316 }> {
333- // Create abort signal if not given.
317+ // Create abort signal if not given
334318 if (!token) {
335319 const controller = this.loggingService.createAbortController(
336320 input.completionId,
337321 );
338322 token = controller.signal;
323+ } else {
324+ // Token was provided externally, just track the completion.
325+ this.loggingService.trackPendingCompletion(input.completionId);
339326 }
327+
340328 const startTime = Date.now();
341329 const options = await this._getAutocompleteOptions();
342330
343- // Debounce.
331+ // Debounce
344332 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
345333 return { token, startTime, helper: undefined };
346334 }
@@ -350,9 +338,14 @@
350338 return { token, startTime, helper: undefined };
351339 }
352340
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
356349 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
357350 console.error(`${llm.model} is not capable of next edit.`);
358351 return { token, startTime, helper: undefined };
@@ -382,6 +375,12 @@
382375 editableRegionEndLine: number;
383376 prompts: Prompt[];
384377 }> {
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.
385384 const [snippetPayload, workspaceDirs] = await Promise.all([
386385 getAllSnippetsWithoutRace({
387386 helper,
@@ -392,277 +391,41 @@
392391 this.ide.getWorkspaceDirs(),
393392 ]);
394393
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.
399395 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,
437399 );
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- }
527400
528- return {
401+ // Build context for model-specific prompt generation.
402+ const context: ModelSpecificContext = {
403+ helper,
404+ snippetPayload,
529405 editableRegionStartLine,
530406 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+ }),
531419 };
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);
630420
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);
658422
659- return outcomeNext;
660- }
423+ this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
661424
662- return undefined;
425+ return { editableRegionStartLine, editableRegionEndLine, prompts };
663426 }
664427
665- private async _handleFineTunedEndpointCompletion(
428+ private async _handleCompletion(
666429 helper: HelperVars,
667430 prompts: Prompt[],
668431 token: AbortSignal,
@@ -674,338 +437,75 @@
674437 usingFullFileDiff: boolean;
675438 },
676439 ): Promise<NextEditOutcome | undefined> {
440+ if (!this.modelProvider) {
441+ throw new Error("Model provider not initialized");
442+ }
443+
677444 const llm = await this._prepareLlm();
678445 if (!llm) return undefined;
679446
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+ });
683465
684466 if (typeof msg.content !== "string") {
685467 return undefined;
686468 }
687469
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);
699472
473+ let outcome: NextEditOutcome | undefined;
474+
475+ // Handle based on diff type.
700476 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
701- return await this._handlePartialFileDiff(
702- // we could use fillFileDiff
477+ outcome = await this.modelProvider.handlePartialFileDiff(
703478 helper,
704479 editableRegionStartLine,
705480 editableRegionEndLine,
706481 startTime,
707482 llm,
708483 nextCompletion,
484+ this.promptMetadata!,
485+ this.ide,
709486 );
710487 } else {
711- return await this._handleFullFileDiff(
488+ outcome = await this.modelProvider.handleFullFileDiff(
712489 helper,
713490 editableRegionStartLine,
714491 editableRegionEndLine,
715492 startTime,
716493 llm,
717494 nextCompletion,
495+ this.promptMetadata!,
496+ this.ide,
718497 );
719498 }
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- }
819499
820- return undefined;
821- }
500+ if (outcome) {
501+ // Handle NextEditProvider-specific state.
502+ this.previousCompletions.push(outcome);
822503
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);
849506 }
850507
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;
1009509 }
1010510
1011511 private async _markDisplayedIfJetBrains(
@@ -1018,6 +518,12 @@
1018518 }
1019519 }
1020520
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+ */
1021527 public async provideInlineCompletionItemsWithChain(
1022528 ctx: {
1023529 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 @@
88 NEXT_EDIT_MODELS,
99 { topMargin: number; bottomMargin: number }
1010 > = {
11- "mercury-coder-nextedit": {
11+ "mercury-coder": {
1212 topMargin: 0,
1313 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
1515 instinct: { topMargin: 1, bottomMargin: 5 },
1616 };
1717
18+export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>";
19+
1820 // Model 1-specific tokens.
1921 export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
2022 export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
2123 export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
2224 export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>";
2325 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.
2527
2628 You have access to the following information to help you make informed suggestions:
2729
@@ -64,4 +66,4 @@
6466 export const MERCURY_EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>";
6567 export const MERCURY_CURSOR = "<|cursor|>";
6668 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 @@
1111 } from "../../autocomplete/util/types";
1212 import { ConfigHandler } from "../../config/ConfigHandler";
1313 import { IDE, ILLM } from "../../index";
14+import { isSecurityConcern } from "../../indexing/ignore";
1415 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
1516
1617 /**
@@ -61,6 +62,10 @@
6162 throw new Error("No config available");
6263 }
6364
65+ if (isSecurityConcern(input.filepath)) {
66+ throw new Error("File is a security concern, autocomplete disabled");
67+ }
68+
6469 // Use provided autocomplete model or fall back to configured autocomplete model
6570 let finalModel: ILLM;
6671 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 @@
11 import Handlebars from "handlebars";
2-import { Position } from "../..";
3-import { SnippetPayload } from "../../autocomplete/snippets";
4-import { HelperVars } from "../../autocomplete/util/HelperVars";
52 import { NEXT_EDIT_MODELS } from "../../llm/constants";
63 import {
74 INSTINCT_USER_PROMPT_PREFIX,
@@ -12,242 +9,39 @@
129 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1310 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
1411 } 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`,
4421 },
4522 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:`,
4724 },
4825 };
4926
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;
7730
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);
8533 }
8634
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);
15537 }
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- };
23638 }
23739
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;
25347 }
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";
62 import { NEXT_EDIT_MODELS } from "../../llm/constants";
73 import {
8- INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
94 INSTINCT_USER_PROMPT_PREFIX,
105 MERCURY_CURRENT_FILE_CONTENT_CLOSE,
116 MERCURY_CURRENT_FILE_CONTENT_OPEN,
12- MERCURY_CURSOR,
137 MERCURY_EDIT_DIFF_HISTORY_CLOSE,
148 MERCURY_EDIT_DIFF_HISTORY_OPEN,
159 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1610 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
1711 } from "../constants";
1812 import {
19- renderDefaultSystemPrompt,
20- renderDefaultUserPrompt,
21- renderPrompt,
13+ NEXT_EDIT_MODEL_TEMPLATES,
14+ PromptTemplateRenderer,
15+ getTemplateForModel,
2216 } from "./NextEditPromptEngine";
2317
2418 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+ );
6427 });
6528
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}}}");
8242 });
8343
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}}}");
11356 });
57+ });
11458
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");
11970 });
120- });
12171
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);
12575
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 ");
12979 });
130- });
13180
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");
20995 });
21096 });
21197
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.");
237110 });
238111 });
239112 });
modified core/nextEdit/templating/mercuryCoderNextEdit.ts +4 −0
@@ -3,6 +3,8 @@
33 MERCURY_CODE_TO_EDIT_CLOSE,
44 MERCURY_CODE_TO_EDIT_OPEN,
55 MERCURY_CURSOR,
6+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
7+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
68 } from "../constants";
79 import { insertCursorToken } from "./utils";
810
@@ -11,8 +13,10 @@
1113 ) {
1214 return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => {
1315 const block = [
16+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
1417 `code_snippet_file_path: ${snippet.filepath}`,
1518 snippet.content,
19+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
1620 ].join("\n");
1721
1822 return (
modified core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +7 −1
@@ -4,6 +4,8 @@
44 MERCURY_CODE_TO_EDIT_CLOSE,
55 MERCURY_CODE_TO_EDIT_OPEN,
66 MERCURY_CURSOR,
7+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
8+ MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
79 } from "../constants";
810 import {
911 currentFileContentBlock,
@@ -25,10 +27,14 @@
2527 const result = recentlyViewedCodeSnippetsBlock(snippets);
2628
2729 const expected =
30+ `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` +
2831 "code_snippet_file_path: /path/to/file1.ts\n" +
2932 "const a = 1;\n" +
33+ `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE}\n` +
34+ `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` +
3035 "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;
3238
3339 expect(result).toBe(expected);
3440 });
modified core/nextEdit/types.ts +36 −0
@@ -5,7 +5,9 @@
55 RangeInFile,
66 TabAutocompleteOptions,
77 } from "../";
8+import { SnippetPayload } from "../autocomplete/snippets";
89 import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
10+import { HelperVars } from "../autocomplete/util/HelperVars";
911
1012 export type RecentlyEditedRange = RangeInFile & {
1113 timestamp: number;
@@ -61,6 +63,7 @@
6163 cursorPosition: { line: number; character: number };
6264 finalCursorPosition: { line: number; character: number };
6365 accepted?: boolean;
66+ aborted?: boolean;
6467 editableRegionStartLine: number;
6568 editableRegionEndLine: number;
6669 diffLines: DiffLine[];
@@ -104,3 +107,36 @@
104107 editDiffHistory: string; // could be a singe large unified diff
105108 currentFilePath: string;
106109 }
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 @@
11 import { DiffLine } from "..";
2+import { NEXT_EDIT_MODELS } from "../llm/constants";
23
34 export function isNextEditTest(): boolean {
45 const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
@@ -21,3 +22,11 @@
2122 (diff.line.trim() === "" || /^\s+$/.test(diff.line)),
2223 );
2324 }
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 @@
11 import { describe, expect, test, vi } from "vitest";
22 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";
49
510 describe("isNextEditTest", () => {
611 test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
@@ -57,3 +62,35 @@
5762 expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
5863 });
5964 });
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 @@
77 "vitest": "vitest run",
88 "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
99 "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",
1112 "lint": "eslint . --ext ts",
1213 "lint:fix": "eslint . --ext ts --fix",
1314 "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 @@
3334 "@types/pg": "^8.11.6",
3435 "@types/plist": "^3.0.5",
3536 "@types/request": "^2.48.12",
37+ "@types/shell-quote": "^1.7.5",
3638 "@types/tar": "^6.1.13",
3739 "@types/uuid": "^9.0.7",
3840 "@types/win-ca": "^3.5.4",
41+ "@typescript-eslint/eslint-plugin": "^8.40.0",
42+ "@typescript-eslint/parser": "^8.40.0",
3943 "cross-env": "^7.0.3",
4044 "esbuild": "0.17.19",
4145 "eslint": "^8",
@@ -58,6 +62,7 @@
5862 "@continuedev/fetch": "file:../packages/fetch",
5963 "@continuedev/llm-info": "file:../packages/llm-info",
6064 "@continuedev/openai-adapters": "file:../packages/openai-adapters",
65+ "@continuedev/terminal-security": "file:../packages/terminal-security",
6166 "@modelcontextprotocol/sdk": "^1.12.0",
6267 "@mozilla/readability": "^0.5.0",
6368 "@octokit/rest": "^20.1.1",
@@ -66,7 +71,6 @@
6671 "@sentry/esbuild-plugin": "^4.0.2",
6772 "@sentry/node": "^9.43.0",
6873 "@sentry/vite-plugin": "^4.0.2",
69- "@typescript-eslint/eslint-plugin": "^7.8.0",
7074 "@xenova/transformers": "2.14.0",
7175 "adf-to-md": "^1.1.0",
7276 "async-mutex": "^0.5.0",
@@ -85,7 +89,7 @@
8589 "http-proxy-agent": "^7.0.1",
8690 "https-proxy-agent": "^7.0.3",
8791 "iconv-lite": "^0.6.3",
88- "ignore": "^5.3.1",
92+ "ignore": "^7.0.5",
8993 "is-localhost-ip": "^2.0.0",
9094 "jinja-js": "0.1.8",
9195 "js-tiktoken": "^1.0.8",
@@ -98,7 +102,7 @@
98102 "node-html-markdown": "^1.3.0",
99103 "ollama": "^0.4.6",
100104 "onnxruntime-node": "1.14.0",
101- "openai": "^4.104.0",
105+ "openai": "^5.13.1",
102106 "p-limit": "^6.1.0",
103107 "partial-json": "^0.1.7",
104108 "pg": "^8.11.3",
@@ -109,6 +113,7 @@
109113 "quick-lru": "^7.0.0",
110114 "replicate": "^0.26.0",
111115 "request": "^2.88.2",
116+ "shell-quote": "^1.8.3",
112117 "socket.io-client": "^4.7.3",
113118 "sqlite": "^5.1.1",
114119 "sqlite3": "^5.1.7",
modified core/protocol/core.ts +19 −4
@@ -4,6 +4,7 @@
44 DevDataLogEvent,
55 ModelRole,
66 } from "@continuedev/config-yaml";
7+import { ToolPolicy } from "@continuedev/terminal-security";
78
89 import {
910 AutocompleteInput,
@@ -34,7 +35,7 @@
3435 RangeInFileWithNextEditInfo,
3536 SerializedContinueConfig,
3637 Session,
37- SessionMetadata,
38+ BaseSessionMetadata,
3839 SiteIndexingConfig,
3940 SlashCommandDescWithSource,
4041 StreamDiffLinesPayload,
@@ -48,9 +49,12 @@
4849 ControlPlaneEnv,
4950 ControlPlaneSessionInfo,
5051 } 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";
5356 import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
57+import { NextEditOutcome } from "../nextEdit/types";
5458
5559 export enum OnboardingModes {
5660 API_KEY = "API Key",
@@ -70,9 +74,13 @@
7074 cancelApply: [undefined, void];
7175
7276 // History
73- "history/list": [ListHistoryOptions, SessionMetadata[]];
77+ "history/list": [
78+ ListHistoryOptions,
79+ (BaseSessionMetadata | RemoteSessionMetadata)[],
80+ ];
7481 "history/delete": [{ id: string }, void];
7582 "history/load": [{ id: string }, Session];
83+ "history/loadRemote": [{ remoteId: string }, Session];
7684 "history/save": [Session, void];
7785 "history/share": [{ id: string; outputDir?: string }, void];
7886 "history/clear": [undefined, void];
@@ -87,6 +95,7 @@
8795 ];
8896 "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
8997 "config/newPromptFile": [undefined, void];
98+ "config/newAssistantFile": [undefined, void];
9099 "config/ideSettingsUpdate": [IdeSettings, void];
91100 "config/getSerializedProfileInfo": [
92101 undefined,
@@ -285,6 +294,7 @@
285294 "docs/getSuggestedDocs": [undefined, void];
286295 "docs/initStatuses": [undefined, void];
287296 "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails];
297+ "docs/getIndexedPages": [{ startUrl: string }, string[]];
288298 addAutocompleteModel: [{ model: ModelDescription }, void];
289299
290300 "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
@@ -292,6 +302,10 @@
292302 { toolCall: ToolCall },
293303 { contextItems: ContextItem[]; errorMessage?: string },
294304 ];
305+ "tools/evaluatePolicy": [
306+ { toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
307+ { policy: ToolPolicy; displayValue?: string },
308+ ];
295309 "clipboardCache/add": [{ content: string }, void];
296310 "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
297311 "controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
@@ -307,5 +321,6 @@
307321 ];
308322 "process/markAsBackgrounded": [{ toolCallId: string }, void];
309323 "process/isBackgrounded": [{ toolCallId: string }, boolean];
324+ "process/killTerminalProcess": [{ toolCallId: string }, void];
310325 "mdm/setLicenseKey": [{ licenseKey: string }, boolean];
311326 };
modified core/protocol/ide.ts +1 −0
@@ -51,6 +51,7 @@
5151 getPinnedFiles: [undefined, string[]];
5252 showLines: [{ filepath: string; startLine: number; endLine: number }, void];
5353 readRangeInFile: [{ filepath: string; range: Range }, string];
54+ readFileAsDataUrl: [{ filepath: string }, string];
5455 getDiff: [{ includeUnstaged: boolean }, string[]];
5556 getTerminalContents: [undefined, string];
5657 getDebugLocals: [{ threadIndex: number }, string];
modified core/protocol/passThrough.ts +5 −0
@@ -13,11 +13,13 @@
1313 "history/list",
1414 "history/delete",
1515 "history/load",
16+ "history/loadRemote",
1617 "history/save",
1718 "history/clear",
1819 "devdata/log",
1920 "config/addModel",
2021 "config/newPromptFile",
22+ "config/newAssistantFile",
2123 "config/ideSettingsUpdate",
2224 "config/addLocalWorkspaceBlock",
2325 "config/getSerializedProfileInfo",
@@ -70,12 +72,14 @@
7072 "indexing/setPaused",
7173 "docs/initStatuses",
7274 "docs/getDetails",
75+ "docs/getIndexedPages",
7376 //
7477 "onboarding/complete",
7578 "addAutocompleteModel",
7679 "didChangeSelectedProfile",
7780 "didChangeSelectedOrg",
7881 "tools/call",
82+ "tools/evaluatePolicy",
7983 "controlPlane/getEnvironment",
8084 "controlPlane/getFreeTrialStatus",
8185 "controlPlane/getModelsAddOnUpgradeUrl",
@@ -83,6 +87,7 @@
8387 "isItemTooBig",
8488 "process/markAsBackgrounded",
8589 "process/isBackgrounded",
90+ "process/killTerminalProcess",
8691 ];
8792
8893 // Message types to pass through from core to webview
modified core/test/fixtures.ts +1 −3
@@ -12,13 +12,11 @@
1212
1313 export const testControlPlaneClient = new ControlPlaneClient(
1414 Promise.resolve(undefined),
15- ideSettingsPromise,
16- testIde.getIdeInfo(),
15+ testIde,
1716 );
1817
1918 export const testConfigHandler = new ConfigHandler(
2019 testIde,
21- ideSettingsPromise,
2220 new LLMLogger(),
2321 Promise.resolve(undefined),
2422 );
modified core/tools/builtIn.ts +5 −2
@@ -1,7 +1,9 @@
11 export enum BuiltInToolNames {
22 ReadFile = "read_file",
3+ ReadFileRange = "read_file_range",
34 EditExistingFile = "edit_existing_file",
4- SearchAndReplaceInFile = "search_and_replace_in_file",
5+ SingleFindAndReplace = "single_find_and_replace",
6+ MultiEdit = "multi_edit",
57 ReadCurrentlyOpenFile = "read_currently_open_file",
68 CreateNewFile = "create_new_file",
79 RunTerminalCommand = "run_terminal_command",
@@ -24,5 +26,6 @@
2426
2527 export const CLIENT_TOOLS_IMPLS = [
2628 BuiltInToolNames.EditExistingFile,
27- BuiltInToolNames.SearchAndReplaceInFile,
29+ BuiltInToolNames.SingleFindAndReplace,
30+ BuiltInToolNames.MultiEdit,
2831 ];
modified core/tools/callTool.ts +13 −4
@@ -1,3 +1,4 @@
1+import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
12 import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
23 import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
34 import { canParseUrl } from "../util/url";
@@ -12,6 +13,8 @@
1213 import { lsToolImpl } from "./implementations/lsTool";
1314 import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
1415 import { readFileImpl } from "./implementations/readFile";
16+
17+import { readFileRangeImpl } from "./implementations/readFileRange";
1518 import { requestRuleImpl } from "./implementations/requestRule";
1619 import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
1720 import { searchWebImpl } from "./implementations/searchWeb";
@@ -85,10 +88,14 @@
8588 if (!client) {
8689 throw new Error("MCP connection not found");
8790 }
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+ );
9299
93100 if (response.isError === true) {
94101 throw new Error(JSON.stringify(response.content));
@@ -145,6 +152,8 @@
145152 switch (functionName) {
146153 case BuiltInToolNames.ReadFile:
147154 return await readFileImpl(args, extras);
155+ case BuiltInToolNames.ReadFileRange:
156+ return await readFileRangeImpl(args, extras);
148157 case BuiltInToolNames.CreateNewFile:
149158 return await createNewFileImpl(args, extras);
150159 case BuiltInToolNames.GrepSearch:
modified core/tools/definitions/createNewFile.ts +3 −3
@@ -4,9 +4,9 @@
44 export const createNewFileTool: Tool = {
55 type: "function",
66 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 }}}",
1010 group: BUILT_IN_GROUP_NAME,
1111 readonly: false,
1212 isInstant: true,
modified core/tools/definitions/createRuleBlock.ts +1 −0
@@ -84,4 +84,5 @@
8484 ["alwaysApply", "false"],
8585 ],
8686 },
87+ toolCallIcon: "PencilIcon",
8788 };
modified core/tools/definitions/editFile.ts +4 −2
@@ -1,13 +1,15 @@
11 import { Tool } from "../..";
22 import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
33 import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
4-import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
54
65 export interface EditToolArgs {
76 filepath: string;
87 changes: string;
98 }
109
10+export const NO_PARALLEL_TOOL_CALLING_INSTRUCTION =
11+ "This tool CANNOT be called in parallel with other tools.";
12+
1113 const CHANGES_DESCRIPTION =
1214 "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 ...'";
1315
@@ -22,7 +24,7 @@
2224 isInstant: false,
2325 function: {
2426 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}`,
2628 parameters: {
2729 type: "object",
2830 required: ["filepath", "changes"],
modified core/tools/definitions/fetchUrlContent.ts +2 −1
@@ -6,7 +6,7 @@
66 displayTitle: "Read URL",
77 wouldLikeTo: "fetch {{{ url }}}",
88 isCurrently: "fetching {{{ url }}}",
9- hasAlready: "viewed {{{ url }}}",
9+ hasAlready: "fetched {{{ url }}}",
1010 readonly: true,
1111 isInstant: true,
1212 group: BUILT_IN_GROUP_NAME,
@@ -30,4 +30,5 @@
3030 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:`,
3131 exampleArgs: [["url", "https://example.com"]],
3232 },
33+ toolCallIcon: "GlobeAltIcon",
3334 };
modified core/tools/definitions/globSearch.ts +5 −4
@@ -4,16 +4,16 @@
44 export const globSearchTool: Tool = {
55 type: "function",
66 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 }}}"',
1010 readonly: true,
1111 isInstant: true,
1212 group: BUILT_IN_GROUP_NAME,
1313 function: {
1414 name: BuiltInToolNames.FileGlobSearch,
1515 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",
1717 parameters: {
1818 type: "object",
1919 required: ["pattern"],
@@ -30,4 +30,5 @@
3030 prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
3131 exampleArgs: [["pattern", "*.py"]],
3232 },
33+ toolCallIcon: "MagnifyingGlassIcon",
3334 };
modified core/tools/definitions/grepSearch.ts +5 −4
@@ -4,16 +4,16 @@
44 export const grepSearchTool: Tool = {
55 type: "function",
66 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 }}}"',
1010 readonly: true,
1111 isInstant: true,
1212 group: BUILT_IN_GROUP_NAME,
1313 function: {
1414 name: BuiltInToolNames.GrepSearch,
1515 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",
1717 parameters: {
1818 type: "object",
1919 required: ["query"],
@@ -31,4 +31,5 @@
3131 prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
3232 exampleArgs: [["query", ".*main_services.*"]],
3333 },
34+ toolCallIcon: "MagnifyingGlassIcon",
3435 };
modified core/tools/definitions/index.ts +4 −1
@@ -6,12 +6,15 @@
66 export { globSearchTool } from "./globSearch";
77 export { grepSearchTool } from "./grepSearch";
88 export { lsTool } from "./ls";
9+export { multiEditTool } from "./multiEdit";
910 export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
1011 export { readFileTool } from "./readFile";
12+
13+export { readFileRangeTool } from "./readFileRange";
1114 export { requestRuleTool } from "./requestRule";
1215 export { runTerminalCommandTool } from "./runTerminalCommand";
13-export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
1416 export { searchWebTool } from "./searchWeb";
17+export { singleFindAndReplaceTool } from "./singleFindAndReplace";
1518 export { viewDiffTool } from "./viewDiff";
1619 export { viewRepoMapTool } from "./viewRepoMap";
1720 export { viewSubdirectoryTool } from "./viewSubdirectory";
modified core/tools/definitions/ls.ts +4 −3
@@ -5,9 +5,9 @@
55 export const lsTool: Tool = {
66 type: "function",
77 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 }}}",
1111 readonly: true,
1212 isInstant: true,
1313 group: BUILT_IN_GROUP_NAME,
@@ -38,4 +38,5 @@
3838 ["recursive", "false"],
3939 ],
4040 },
41+ toolCallIcon: "FolderIcon",
4142 };
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 @@
66 displayTitle: "Read Currently Open File",
77 wouldLikeTo: "read the current file",
88 isCurrently: "reading the current file",
9- hasAlready: "viewed the current file",
9+ hasAlready: "read the current file",
1010 readonly: true,
1111 isInstant: true,
1212 group: BUILT_IN_GROUP_NAME,
1313 function: {
1414 name: BuiltInToolNames.ReadCurrentlyOpenFile,
1515 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.",
1717 parameters: {
1818 type: "object",
1919 properties: {},
@@ -24,4 +24,5 @@
2424 prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
2525 If the user is asking about a file and you don't see any code, use this to check the current file`,
2626 },
27+ toolCallIcon: "DocumentTextIcon",
2728 };
modified core/tools/definitions/readFile.ts +2 −1
@@ -6,7 +6,7 @@
66 displayTitle: "Read File",
77 wouldLikeTo: "read {{{ filepath }}}",
88 isCurrently: "reading {{{ filepath }}}",
9- hasAlready: "viewed {{{ filepath }}}",
9+ hasAlready: "read {{{ filepath }}}",
1010 readonly: true,
1111 isInstant: true,
1212 group: BUILT_IN_GROUP_NAME,
@@ -31,4 +31,5 @@
3131 exampleArgs: [["filepath", "path/to/the_file.txt"]],
3232 },
3333 defaultToolPolicy: "allowedWithoutPermission",
34+ toolCallIcon: "DocumentIcon",
3435 };
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 @@
11 import os from "os";
22 import { Tool } from "../..";
33 import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
4+import {
5+ evaluateTerminalCommandSecurity,
6+ ToolPolicy,
7+} from "@continuedev/terminal-security";
48
59 /**
610 * Get the preferred shell for the current platform
@@ -56,6 +60,15 @@
5660 },
5761 },
5862 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+ },
5972 systemMessageDescription: {
6073 prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
6174 ${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 @@
3030 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:`,
3131 exampleArgs: [["query", "What is the current weather in San Francisco?"]],
3232 },
33+ toolCallIcon: "GlobeAltIcon",
3334 };
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 @@
77 const mockParams: ConfigDependentToolParams = {
88 rules: [],
99 enableExperimentalTools: false,
10+ isSignedIn: false,
11+ isRemote: false,
12+ modelName: "a model",
1013 };
1114
1215 // Helper function to get the actual tool object
modified core/tools/definitions/viewDiff.ts +1 −0
@@ -23,4 +23,5 @@
2323 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.`,
2424 },
2525 defaultToolPolicy: "allowedWithoutPermission",
26+ toolCallIcon: "CodeBracketIcon",
2627 };
modified core/tools/definitions/viewRepoMap.ts +1 −0
@@ -23,4 +23,5 @@
2323 prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
2424 },
2525 defaultToolPolicy: "allowedWithPermission",
26+ toolCallIcon: "MapIcon",
2627 };
modified core/tools/definitions/viewSubdirectory.ts +1 −0
@@ -30,4 +30,5 @@
3030 exampleArgs: [["directory_path", "path/to/subdirectory"]],
3131 },
3232 defaultToolPolicy: "allowedWithPermission",
33+ toolCallIcon: "FolderOpenIcon",
3334 };
modified core/tools/implementations/fetchUrlContent.ts +2 −2
@@ -27,8 +27,8 @@
2727 // Add truncation warning if needed
2828 if (truncatedUrls.length > 0) {
2929 processedItems.push({
30- name: "URL content truncation warning",
31- description: "Informs that URL content was truncated",
30+ name: "Truncation warning",
31+ description: "",
3232 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.`,
3333 });
3434 }
modified core/tools/implementations/fetchUrlContent.vitest.ts +2 −2
@@ -54,7 +54,7 @@
5454
5555 expect(result).toHaveLength(2); // Original item + warning
5656 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");
5858 expect(result[1].content).toContain("was truncated");
5959 expect(result[1].content).toContain("20000 character limit");
6060 });
@@ -87,5 +87,5 @@
8787 expect(result).toHaveLength(3); // Two original items + warning
8888 expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
8989 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");
9191 });
modified core/tools/implementations/globSearch.ts +12 −2
@@ -10,10 +10,20 @@
1010 pattern,
1111 MAX_AGENT_GLOB_RESULTS,
1212 );
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+ }
1323 const contextItems: ContextItem[] = [
1424 {
1525 name: "File results",
16- description: "Results from file glob search",
26+ description: "glob search",
1727 content: results.join("\n"),
1828 },
1929 ];
@@ -22,7 +32,7 @@
2232 if (results.length === MAX_AGENT_GLOB_RESULTS) {
2333 contextItems.push({
2434 name: "Truncation warning",
25- description: "Inform the model that results were truncated",
35+ description: "",
2636 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`,
2737 });
2838 }
modified core/tools/implementations/grepSearch.ts +54 −14
@@ -1,18 +1,15 @@
11 import { ToolImpl } from ".";
22 import { ContextItem } from "../..";
33 import { formatGrepSearchResults } from "../../util/grepSearch";
4+import { prepareQueryForRipgrep } from "../../util/regexValidator";
45 import { getStringArg } from "../parseArgs";
56
67 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
89
910 function splitGrepResultsByFile(content: string): ContextItem[] {
1011 const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
1112
12- if (matches.length === 0) {
13- return [];
14- }
15-
1613 const contextItems: ContextItem[] = [];
1714
1815 for (let i = 0; i < matches.length; i++) {
@@ -42,16 +39,48 @@
4239 }
4340
4441 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+
5169 const { formatted, numResults, truncated } = formatGrepSearchResults(
5270 results,
5371 DEFAULT_GREP_SEARCH_CHAR_LIMIT,
5472 );
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+
5584 const truncationReasons: string[] = [];
5685 if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
5786 truncationReasons.push(
@@ -64,7 +93,7 @@
6493 );
6594 }
6695
67- let contextItems: ContextItem[] = [];
96+ let contextItems: ContextItem[];
6897
6998 const splitByFile: boolean = args?.splitByFile || false;
7099 if (splitByFile) {
@@ -79,10 +108,21 @@
79108 ];
80109 }
81110
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+
82122 if (truncationReasons.length > 0) {
83123 contextItems.push({
84- name: "Search truncation warning",
85- description: "Informs the model that search results were truncated",
124+ name: "Truncation warning",
125+ description: "",
86126 content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
87127 });
88128 }
modified core/tools/implementations/lsTool.ts +5 −2
@@ -1,3 +1,5 @@
1+import ignore from "ignore";
2+
13 import { ToolImpl } from ".";
24 import { walkDir } from "../../indexing/walkDir";
35 import { resolveRelativePathInDir } from "../../util/ideUtils";
@@ -27,6 +29,7 @@
2729 returnRelativeUrisPaths: true,
2830 include: "both",
2931 recursive: args?.recursive ?? false,
32+ overrideDefaultIgnores: ignore(), // Show all directories including dist/, build/, etc.
3033 });
3134
3235 const lines = entries.slice(0, MAX_LS_TOOL_LINES);
@@ -50,8 +53,8 @@
5053 warningContent += ". Try using a non-recursive search";
5154 }
5255 contextItems.push({
53- name: "ls truncation warning",
54- description: "Informs the model that ls results were truncated",
56+ name: "Truncation warning",
57+ description: "",
5558 content: warningContent,
5659 });
5760 }
modified core/tools/implementations/readCurrentlyOpenFile.ts +3 −1
@@ -1,12 +1,14 @@
11 import { getUriDescription } from "../../util/uri";
22
33 import { ToolImpl } from ".";
4+import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
45 import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
56
6-export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
7+export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => {
78 const result = await extras.ide.getCurrentFile();
89
910 if (result) {
11+ throwIfFileIsSecurityConcern(result.path);
1012 await throwIfFileExceedsHalfOfContext(
1113 result.path,
1214 result.contents,
modified core/tools/implementations/readFile.ts +2 −0
@@ -2,11 +2,13 @@
22 import { getUriPathBasename } from "../../util/uri";
33
44 import { ToolImpl } from ".";
5+import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
56 import { getStringArg } from "../parseArgs";
67 import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
78
89 export const readFileImpl: ToolImpl = async (args, extras) => {
910 const filepath = getStringArg(args, "filepath");
11+ throwIfFileIsSecurityConcern(filepath);
1012
1113 const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
1214 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 @@
3636 import { ToolImpl } from ".";
3737 import {
3838 isProcessBackgrounded,
39+ markProcessAsRunning,
3940 removeBackgroundedProcess,
40-} from "../../util/processTerminalBackgroundStates";
41+ removeRunningProcess,
42+ updateProcessOutput,
43+} from "../../util/processTerminalStates";
4144 import { getBooleanArg, getStringArg } from "../parseArgs";
4245
4346 const asyncExec = util.promisify(childProcess.exec);
@@ -120,6 +123,16 @@
120123 env: getColorEnv(), // Add enhanced environment for colors
121124 });
122125
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+
123136 childProc.stdout?.on("data", (data) => {
124137 // Skip if this process has been backgrounded
125138 if (isProcessBackgrounded(toolCallId)) return;
@@ -127,6 +140,11 @@
127140 const newOutput = getDecodedOutput(data);
128141 terminalOutput += newOutput;
129142
143+ // Update the tracked output for potential cancellation notifications
144+ if (toolCallId && waitForCompletion) {
145+ updateProcessOutput(toolCallId, terminalOutput);
146+ }
147+
130148 // Send partial output to UI
131149 if (extras.onPartialOutput) {
132150 const status = waitForCompletion
@@ -153,6 +171,11 @@
153171 const newOutput = getDecodedOutput(data);
154172 terminalOutput += newOutput;
155173
174+ // Update the tracked output for potential cancellation notifications
175+ if (toolCallId && waitForCompletion) {
176+ updateProcessOutput(toolCallId, terminalOutput);
177+ }
178+
156179 // Send partial output to UI, status is not required
157180 if (extras.onPartialOutput) {
158181 extras.onPartialOutput({
@@ -182,15 +205,19 @@
182205 }
183206
184207 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);
189216 }
190217
191218 if (waitForCompletion) {
192219 // Normal completion, resolve now
193- if (code === 0) {
220+ if (!code || code === 0) {
194221 const status = "Command completed";
195222 resolve([
196223 {
@@ -234,10 +261,14 @@
234261 });
235262
236263 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);
241272 }
242273
243274 reject(error);
@@ -281,6 +312,11 @@
281312 },
282313 );
283314
315+ // Track this process for foreground cancellation
316+ if (toolCallId) {
317+ markProcessAsRunning(toolCallId, childProc, undefined, "");
318+ }
319+
284320 let stdout = "";
285321 let stderr = "";
286322
@@ -293,6 +329,11 @@
293329 });
294330
295331 childProc.on("close", (code) => {
332+ // Clean up process tracking
333+ if (toolCallId) {
334+ removeRunningProcess(toolCallId);
335+ }
336+
296337 if (code === 0) {
297338 resolve({ stdout, stderr });
298339 } else {
@@ -305,6 +346,10 @@
305346 });
306347
307348 childProc.on("error", (error) => {
349+ // Clean up process tracking
350+ if (toolCallId) {
351+ removeRunningProcess(toolCallId);
352+ }
308353 reject(error);
309354 });
310355 },
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 @@
2929 // Add truncation warning if needed
3030 if (truncatedResults.length > 0) {
3131 processedResults.push({
32- name: "Web search truncation warning",
33- description: "Informs that search results were truncated",
32+ name: "Truncation warning",
33+ description: "",
3434 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.`,
3535 });
3636 }
modified core/tools/implementations/searchWeb.vitest.ts +2 −2
@@ -62,7 +62,7 @@
6262 expect(result).toHaveLength(3); // Two results + warning
6363 expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
6464 expect(result[1].content).toBe(shortContent);
65- expect(result[2].name).toBe("Web search truncation warning");
65+ expect(result[2].name).toBe("Truncation warning");
6666 expect(result[2].content).toContain("truncated");
6767 expect(result[2].content).toContain("Result 1");
6868 expect(result[2].content).not.toContain("Result 2");
@@ -100,7 +100,7 @@
100100 expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
101101 expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
102102 expect(result[2].content).toBe(shortContent);
103- expect(result[3].name).toBe("Web search truncation warning");
103+ expect(result[3].name).toBe("Truncation warning");
104104 expect(result[3].content).toContain("Result 1");
105105 expect(result[3].content).toContain("Result 2");
106106 expect(result[3].content).not.toContain("Result 3");
modified core/tools/implementations/viewDiff.ts +13 −2
@@ -9,6 +9,17 @@
99 // TODO includeUnstaged should be an option
1010
1111 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+
1223 const diffLines = combinedDiff.split("\n");
1324
1425 let truncated = false;
@@ -29,8 +40,8 @@
2940
3041 if (truncated) {
3142 contextItems.push({
32- name: "Diff truncation warning",
33- description: "Informs that git diff was truncated",
43+ name: "Truncation warning",
44+ description: "",
3445 content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
3546 });
3647 }
modified core/tools/implementations/viewDiff.vitest.ts +2 −2
@@ -58,7 +58,7 @@
5858 expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
5959
6060 // Check the warning
61- expect(result[1].name).toBe("Diff truncation warning");
61+ expect(result[1].name).toBe("Truncation warning");
6262 expect(result[1].content).toContain("truncated");
6363 expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
6464 });
@@ -83,5 +83,5 @@
8383 expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
8484
8585 // Check the warning
86- expect(result[1].name).toBe("Diff truncation warning");
86+ expect(result[1].name).toBe("Truncation warning");
8787 });
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";
23 import * as toolDefinitions from "./definitions";
34
45 // 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 = () => [
107 toolDefinitions.readFileTool,
118 toolDefinitions.createNewFileTool,
129 toolDefinitions.runTerminalCommandTool,
1310 toolDefinitions.globSearchTool,
14- toolDefinitions.searchWebTool,
1511 toolDefinitions.viewDiffTool,
1612 toolDefinitions.readCurrentlyOpenFileTool,
1713 toolDefinitions.lsTool,
@@ -21,22 +17,37 @@
2117
2218 export const getConfigDependentToolDefinitions = (
2319 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+ }
3851
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 @@
11 import { MCPServerStatus, MCPTool } from "..";
2-
32 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+
510 if (tool.name.startsWith(serverPrefix)) {
611 return tool.name;
712 }
modified core/tools/mcpToolName.vitest.ts +52 −0
@@ -5,6 +5,7 @@
55 const createMcpServer = (name: string): MCPServerStatus => ({
66 name,
77 errors: [],
8+ infos: [],
89 prompts: [],
910 tools: [],
1011 resources: [],
@@ -56,3 +57,54 @@
5657 const result = getMCPToolName(server, tool);
5758 expect(result).toBe("gitlab_create_merge_request");
5859 });
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 @@
2020 ): string {
2121 if (!args || !(argName in args) || typeof args[argName] !== "string") {
2222 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)`,
2424 );
2525 }
2626 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`);
2828 }
2929 return args[argName];
3030 }
@@ -40,6 +40,24 @@
4040 return getStringArg(args, argName, allowEmpty);
4141 }
4242
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+
4361 export function getBooleanArg(args: any, argName: string, required = false) {
4462 if (!args || !(argName in args)) {
4563 if (required) {
modified core/tools/parseArgs.vitest.ts +92 −8
@@ -2,6 +2,7 @@
22 import { ToolCallDelta } from "..";
33 import {
44 getBooleanArg,
5+ getNumberArg,
56 getOptionalStringArg,
67 getStringArg,
78 safeParseToolCallArgs,
@@ -102,26 +103,26 @@
102103 it("should throw error when argument is missing", () => {
103104 const args = { otherArg: "test" };
104105 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)",
106107 );
107108 });
108109
109110 it("should throw error when argument is not a string", () => {
110111 const args = { name: 123 };
111112 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)",
113114 );
114115 });
115116
116117 it("should throw error when argument is empty and empty not allowed", () => {
117118 const args = { name: "" };
118119 expect(() => getStringArg(args, "name")).toThrowError(
119- "Argument name must not be empty",
120+ "Argument name must not be empty or whitespace-only",
120121 );
121122
122123 const argsWithSpace = { name: " " };
123124 expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
124- "Argument name must not be empty",
125+ "Argument name must not be empty or whitespace-only",
125126 );
126127 });
127128
@@ -137,10 +138,10 @@
137138
138139 it("should handle null or undefined args", () => {
139140 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)",
141142 );
142143 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)",
144145 );
145146 });
146147 });
@@ -161,14 +162,14 @@
161162 it("should throw error when argument is not a string", () => {
162163 const args = { name: 123 };
163164 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)",
165166 );
166167 });
167168
168169 it("should throw error when argument is empty and empty not allowed", () => {
169170 const args = { name: "" };
170171 expect(() => getOptionalStringArg(args, "name")).toThrowError(
171- "Argument name must not be empty",
172+ "Argument name must not be empty or whitespace-only",
172173 );
173174 });
174175
@@ -246,3 +247,86 @@
246247 );
247248 });
248249 });
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 @@
3939 */
4040 hasDismissedConfigTsNoticeJetBrains: boolean;
4141 hasAlreadyCreatedAPromptFile: boolean;
42+ hasShownUnsupportedPlatformWarning: boolean;
4243 showConfigUpdateToast: boolean;
4344 isSupportedLanceDbCpuTargetForLinux: boolean;
4445 sharedConfig: SharedConfigSchema;
4546 failedDocs: SiteIndexingConfig[];
46- shownDeprecatedProviderWarnings: {
47- [providerTitle: string]: boolean;
48- };
47+ shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
48+ autoUpdateCli: boolean;
4949 mcpOauthStorage: {
5050 [serverUrl: string]: {
5151 clientInformation?: OAuthClientInformationFull;
@@ -65,16 +65,7 @@
6565 ) {
6666 const filepath = getGlobalContextFilePath();
6767 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));
7869 } else {
7970 const data = fs.readFileSync(filepath, "utf-8");
8071
@@ -112,10 +103,7 @@
112103 }
113104
114105 // 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 };
119107
120108 fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
121109 return;
@@ -173,10 +161,7 @@
173161 newValues: Partial<SharedConfigSchema>,
174162 ): SharedConfigSchema {
175163 const currentSharedConfig = this.getSharedConfig();
176- const updatedSharedConfig = {
177- ...currentSharedConfig,
178- ...newValues,
179- };
164+ const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
180165 this.update("sharedConfig", updatedSharedConfig);
181166 return updatedSharedConfig;
182167 }
@@ -188,10 +173,7 @@
188173 ): GlobalContextModelSelections {
189174 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
190175 const forProfile = currentSelections[profileId] ?? {};
191- const newSelections = {
192- ...forProfile,
193- [role]: title,
194- };
176+ const newSelections = { ...forProfile, [role]: title };
195177
196178 this.update("selectedModelsByProfileId", {
197179 ...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 @@
55 import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
66 import type { IMessenger } from "../protocol/messenger";
77 import { renderChatMessage } from "./messageContent";
8+import { convertFromUnifiedHistory } from "./messageConversion";
89
910 export class ChatDescriber {
1011 static maxTokens = 12;
@@ -46,6 +47,66 @@
4647 return removeQuotesAndEscapes(renderChatMessage(titleResponse));
4748 }
4849
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+
49110 // // TODO: Allow the user to manually set specific/tailored prompts to generate their titles
50111 // static async setup() {
51112 // if(config?.prompt) {
modified core/util/errors.ts +41 −0
@@ -10,3 +10,44 @@
1010 }
1111 return err;
1212 }
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 @@
9393 const offset = 10;
9494
9595 const sessions = historyManager.list({ offset: offset, limit: limit });
96+ // Sessions are now reversed, so newest (99) comes first
9697 const sessionIds = Array.from({ length: limit }, (_, i) =>
97- (i + offset).toString(),
98+ (99 - offset - i).toString(),
9899 );
99100 const isSessionIdInList = (sessionId: string) =>
100101 sessions.some((session) => session.sessionId === sessionId);
@@ -105,7 +106,10 @@
105106 const limit = 25;
106107
107108 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+ );
109113
110114 const isSessionIdInList = (sessionId: string) =>
111115 sessions.some((session) => session.sessionId === sessionId);
modified core/util/history.ts +13 −10
@@ -1,6 +1,6 @@
11 import * as fs from "fs";
22
3-import { Session, SessionMetadata } from "../index.js";
3+import { Session, BaseSessionMetadata } from "../index.js";
44 import { ListHistoryOptions } from "../protocol/core.js";
55
66 import { NEW_SESSION_TITLE } from "./constants.js";
@@ -22,18 +22,21 @@
2222 }
2323
2424 export class HistoryManager {
25- list(options: ListHistoryOptions): SessionMetadata[] {
25+ list(options: ListHistoryOptions): BaseSessionMetadata[] {
2626 const filepath = getSessionsListPath();
2727 if (!fs.existsSync(filepath)) {
2828 return [];
2929 }
3030 const content = fs.readFileSync(filepath, "utf8");
3131
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();
3740
3841 // Apply limit and offset
3942 if (options.limit) {
@@ -56,7 +59,7 @@
5659 const sessionsListFile = getSessionsListPath();
5760 const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
5861 let sessionsList =
59- safeParseArray<SessionMetadata>(
62+ safeParseArray<BaseSessionMetadata>(
6063 sessionsListRaw,
6164 "Error parsing sessions.json",
6265 ) ?? [];
@@ -115,7 +118,7 @@
115118 try {
116119 const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
117120
118- let sessionsList: SessionMetadata[];
121+ let sessionsList: BaseSessionMetadata[];
119122 try {
120123 sessionsList = JSON.parse(rawSessionsList);
121124 } catch (e) {
@@ -138,7 +141,7 @@
138141 }
139142
140143 if (!found) {
141- const sessionMetadata: SessionMetadata = {
144+ const sessionMetadata: BaseSessionMetadata = {
142145 sessionId: session.sessionId,
143146 title: session.title,
144147 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 @@
3535 return contextItems.map((item) => item.content).join("\n\n");
3636 }
3737
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+
3853 export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
3954 switch (message.role) {
4055 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 @@
2121 transform: true,
2222 showWhateverWeHaveAtXMs: 300,
2323 // Experimental options: true = enabled, false = disabled, number = enabled w priority
24- experimental_includeClipboard: true,
24+ experimental_includeClipboard: false,
2525 experimental_includeRecentlyVisitedRanges: true,
2626 experimental_includeRecentlyEditedRanges: true,
2727 experimental_includeDiff: true,
modified core/util/paths.ts +5 −6
@@ -9,7 +9,7 @@
99 import dotenv from "dotenv";
1010
1111 import { IdeType, SerializedContinueConfig } from "../";
12-import { defaultConfig, defaultConfigJetBrains } from "../config/default";
12+import { defaultConfig } from "../config/default";
1313 import Types from "../config/types";
1414
1515 dotenv.config();
@@ -110,7 +110,10 @@
110110 const p = path.join(getContinueGlobalPath(), "config.yaml");
111111 if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) {
112112 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));
114117 } else {
115118 fs.writeFileSync(p, YAML.stringify(defaultConfig));
116119 }
@@ -393,10 +396,6 @@
393396 return getGlobalFolderWithName("prompts");
394397 }
395398
396-export function getGlobalAssistantsPath(): string {
397- return getGlobalFolderWithName("assistants");
398-}
399-
400399 export function readAllGlobalPromptFiles(
401400 folderPath: string = getGlobalPromptsPath(),
402401 ): { path: string; content: string }[] {
modified core/util/posthog.ts +2 −0
@@ -5,6 +5,7 @@
55
66 import type { PostHog as PostHogType } from "posthog-node";
77 import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
8+import { TokensBatchingService } from "./TokensBatchingService.js";
89
910 export enum PosthogFeatureFlag {
1011 AutocompleteTimeout = "autocomplete-timeout",
@@ -99,6 +100,7 @@
99100 }
100101
101102 static shutdownPosthogClient() {
103+ TokensBatchingService.getInstance().shutdown();
102104 Telemetry.client?.shutdown();
103105 }
104106
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";
22 import * as Sentry from "@sentry/node";
33 import os from "node:os";
44 import { IdeInfo } from "../../index.js";
@@ -25,7 +25,7 @@
2525
2626 // Filter integrations that use the global variable
2727 const integrations = Sentry.getDefaultIntegrations({}).filter(
28- (defaultIntegration) => {
28+ (defaultIntegration: Integration) => {
2929 // Remove integrations that might interfere with shared environments
3030 return ![
3131 "OnUncaughtException",
@@ -52,7 +52,7 @@
5252 sendDefaultPii: false,
5353
5454 // Strip sensitive data and add basic properties before sending events
55- beforeSend(event) {
55+ beforeSend(event: Event) {
5656 // First apply anonymization
5757 const anonymizedEvent = anonymizeSentryEvent(event);
5858 if (!anonymizedEvent) return null;
@@ -197,7 +197,7 @@
197197 }
198198
199199 // Use withScope from Sentry to isolate the span context
200- return Sentry.withScope((isolatedScope) => {
200+ return Sentry.withScope((isolatedScope: Sentry.Scope) => {
201201 isolatedScope.setClient(client);
202202 return Sentry.startSpan(
203203 {
modified core/util/sentry/anonymization.ts +3 −2
@@ -1,4 +1,5 @@
1-import { ErrorEvent } from "@sentry/core";
1+import * as Sentry from "@sentry/node";
2+import { type Event } from "@sentry/core";
23 /**
34 * Minimalist Sentry anonymization utilities
45 */
@@ -75,7 +76,7 @@
7576 /**
7677 * Main anonymization function - minimalist approach like Rasa
7778 */
78-export function anonymizeSentryEvent(event: ErrorEvent): any | null {
79+export function anonymizeSentryEvent(event: any): any | null {
7980 try {
8081 // Deep copy to avoid mutating the original event
8182 const anonymized = structuredClone(event);
modified docs/chat/how-to-use-it.mdx +1 −1
@@ -2,7 +2,7 @@
22 title: "Chat"
33 sidebarTitle: "How To Use AI Chat"
44 icon: "circle-question"
5-description: "Learn how to use Continue's AI chat assistant to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
5+description: "Learn how to use Continue's AI chat agent to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
66 ---
77
88 <Frame>
modified docs/customization/mcp-tools.mdx +5 −5
@@ -1,11 +1,11 @@
11 ---
2-title: "MCP Blocks"
2+title: "MCP servers"
33 description: "Learn how to use Model Context Protocol (MCP) blocks in Continue to integrate external tools, connect databases, and extend your development environment."
44 ---
55
6-Model Context Protocol (MCP) blocks let Continue connect to external tools, systems, and databases by running MCP servers.
6+Model Context Protocol (MCP) servers let Continue connect to external tools, systems, and databases by running MCP servers.
77
8-These blocks make it possible to:
8+These servers make it possible to:
99
1010 - **Enable integration** with external tools and systems
1111 - **Create extensible interfaces** for custom capabilities
@@ -13,8 +13,8 @@
1313 - **Allow partners** to contribute specialized functionality
1414 - **Connect to databases** to understand schema and data models during development
1515
16-![MCP Blocks Overview](/images/customization/images/mcp-blocks-overview-c9a104f9b586779c156f9cf34da197c2.png)
16+![MCP servers overview](/images/customization/images/mcp-blocks-overview-c9a104f9b586779c156f9cf34da197c2.png)
1717
18-## Learn More About MCP Blocks
18+## Learn More About MCP servers
1919
2020 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 @@
11 ---
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:"
44 ---
55
6+import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
7+
68 - **[Chat](/customize/model-roles/chat)**: Power conversational interactions about code and provide detailed guidance
79 - **[Edit](/customize/model-roles/edit)**: Handle complex code transformations and refactoring tasks
810 - **[Apply](/customize/model-roles/apply)**: Execute targeted code modifications with high accuracy
@@ -10,10 +12,118 @@
1012 - **[Embedding](/customize/model-roles/embeddings)**: Transform code into vector representations for semantic search
1113 - **[Reranker](/customize/model-roles/reranking)**: Improve search relevance by ordering results based on semantic meaning
1214
13-![Model Blocks Overview](/images/customization/images/model-blocks-overview-36c30e7e01928d7a9b5b26ff1639c34b.png)
15+![Models Overview](/images/customization/images/model-blocks-overview-36c30e7e01928d7a9b5b26ff1639c34b.png)
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
14120
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
16124
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
18126
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 @@
11 ---
22 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"
44 ---
55
66 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 @@
1313
1414 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).
1515
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-
2016 ## Create a Slash Command
2117
2218 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 @@
2521
2622 Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools)
2723
28-Whatever you choose, you'll probably start by editing your Assistant.
24+Whatever you choose, you'll probably start by editing your Agent.
2925
30-## Edit Your Assistant
26+## Edit Your Agent
3127
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.
3329
34-![configure an assistant](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png)
30+![configure an agent](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png)
3531
36-## Manage Your Assistant
32+## Manage Your Agent
3733
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 @@
11 ---
2-title: "Prompt Blocks"
2+title: "Prompts"
33 description: "These are the specialized instructions that shape how models respond:"
44 ---
55
@@ -9,8 +9,8 @@
99 - **Can be shared and reused** across multiple assistants
1010 - **Act as automated code reviewers** that ensure consistency across teams
1111
12-![Prompt Blocks Overview](/images/customization/images/prompts-blocks-overview-17194d870840576f9a0dde548f2c70ec.png)
12+![Prompts Overview](/images/customization/images/prompts-blocks-overview-17194d870840576f9a0dde548f2c70ec.png)
1313
1414 ## Learn More
1515
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 @@
11 ---
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."
44 ---
55
6-Think of these as the guardrails for your AI coding assistants:
6+Think of these as the guardrails for your AI coding agents:
77
88 - **Enforce company-specific coding standards** and security practices
99 - **Implement quality checks** that match your engineering culture
1010 - **Create paved paths** for developers to follow organizational best practices
1111
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.
1313
1414 ## How Rules Work
1515
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.
1717
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-![Add documentation form](/images/docs-form.png)
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-![More Page @docs indexes section](/images/docs-indexes.png)
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-![Documentation indexing peek](/images/docs-indexing-peek.png)
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 @@
437437
438438 You'll then be able to type "@" and see "MCP" in the context providers dropdown.
439439
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-
866440 ### How to Request a New Context Provider in Continue
867441
868442 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 @@
55 sidebarTitle: Autocomplete
66 ---
77
8+import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
9+
10+## Model Recommendations for Autocomplete
11+
12+<ModelRecommendations role="autocomplete" />
13+
814 ## How to Set Up Autocomplete in Continue with Codestral (Recommended)
915
1016 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 @@
123129 ### Customize Autocomplete User Settings in the Continue Extension
124130
125131 {/* - `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:
127133
128134 - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
129135 - `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 @@
11 ---
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
44 keywords: [config, settings, customize]
5-sidebarTitle: "Assistant Configuration"
5+sidebarTitle: "Agent Configuration"
66 ---
77
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.
99
10-![configure an assistant](/images/configure-continue.png)
10+![configure an agent](/images/configure-continue.png)
1111
12-## How to Manage Hub Assistants
12+## How to Manage Hub Agents
1313
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)
1515
16-## How to Configure Local Assistants with YAML
16+## How to Configure Local Agents with YAML
1717
1818 Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
1919
2020 - `~/.continue/config.yaml` (MacOS / Linux)
2121 - `%USERPROFILE%\.continue\config.yaml` (Windows)
2222
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`.
2424
2525 ![local-config-open-steps](/images/local-config-open-steps.png)
2626
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+![Context Items](/images/customize/images/context-provider-example-0c96ff77286fa970b23dddfdc1fa986a.png)
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 @@
1313
1414 You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories.
1515
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).
1917
2018 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 @@
1919 Currently custom tools can be configured using the Model Context
2020 Protocol standard to unify prompts, context, and tool use.
2121
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
2323 explore available MCP server blocks
2424 [here](https://hub.continue.dev/explore/mcp).
2525
@@ -27,7 +27,7 @@
2727
2828 ## Quick Start: How to Set Up Your First MCP Server
2929
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:
3131
3232 1. Create a folder called `.continue/mcpServers` at the top level of your workspace
3333 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 @@
231231 | Model | Tool Use | Image Input | Context Window |
232232 | :------------- | -------- | ----------- | -------------- |
233233 | Qwen 3 Coder | Yes | No | 32k |
234+| Qwen 2.5 VL | No | Yes | 128k |
234235 | Devstral Small | Yes | No | 32k |
235236 | Llama 3.1 | Yes | No | 128k |
236237 | Llama 3 | Yes | No | 8k |
237238 | Mistral | Yes | No | 32k |
238239 | Codestral | Yes | No | 32k |
239-| Gemma 3 4B | Yes | No | 8k |
240+| Gemma 3 4B | Yes | Yes | 128k |
240241
241242 ### Notes
242243
modified docs/customize/deep-dives/rules.mdx +2 −2
@@ -42,7 +42,7 @@
4242
4343 ## How to Create Rules Blocks
4444
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.
4646
4747 ![add local rules button](/images/add-local-rules.png)
4848
@@ -53,7 +53,7 @@
5353
5454 </Info>
5555
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.
5757
5858 Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
5959
modified docs/customize/deep-dives/rules.mdx.backup +3 −3
@@ -39,7 +39,7 @@
3939
4040 ## Creating `rules` blocks
4141
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.
4343
4444 ![add local rules button](/images/add-local-rules.png)
4545
@@ -49,7 +49,7 @@
4949 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.
5050 </Info>
5151
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.
5353
5454 Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
5555
@@ -133,7 +133,7 @@
133133 Always give concise responses
134134 ```
135135
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`.
137137
138138 ### Examples
139139
modified docs/customize/deep-dives/slash-commands.mdx +3 −3
@@ -10,7 +10,7 @@
1010 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.
1111 ![slash-commands](/images/slash-commands.png)
1212
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.
1414
1515 <Note>
1616 **Recommended approach**: Use prompt files to create slash commands instead of
@@ -21,9 +21,9 @@
2121
2222 ## Ways to Create Slash Commands in Continue
2323
24-### Assistant Prompt Blocks
24+### Agent Prompt Blocks
2525
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).
2727
2828 ### Prompt Files
2929
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-![quick-actions](/images/quick-actions.png)
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-![context-menu](/images/context-menu.png)
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 @@
33 description: "Configure DeepInfra with Continue to access low-cost inference for open-source models like Mixtral-8x7B-Instruct, including API setup instructions"
44 ---
55
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
715
816 <Tabs>
917 <Tab title="YAML">
1018 ```yaml title="config.yaml"
1119 models:
12- - name: DeepInfra
20+ - name: <MODEL_NAME>
1321 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>
1624 ```
1725 </Tab>
18- <Tab title="JSON">
26+ <Tab title="JSON (Deprecated)">
1927 ```json title="config.json"
2028 {
2129 "models": [
2230 {
31+ "title": "<MODEL_NAME>",
2332 "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>"
2735 }
2836 ]
2937 }
@@ -31,4 +39,6 @@
3139 </Tab>
3240 </Tabs>
3341
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 @@
11 ---
22 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"
43 sidebarTitle: "Groq"
54 ---
65
76 <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)
118 </Info>
129
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
1711
1812 <Tabs>
1913 <Tab title="YAML">
2014 ```yaml title="config.yaml"
2115 models:
22- - name: Llama 3.3 70b Versatile
16+ - name: <MODEL_NAME>
2317 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>"
2820 ```
2921 </Tab>
30- <Tab title="JSON">
22+ <Tab title="JSON (Deprecated)">
3123 ```json title="config.json"
3224 {
3325 "models": [
3426 {
35- "title": "Llama 3.3 70b Versatile",
27+ "title": "<MODEL_NAME>",
3628 "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>"",
3931 }
4032 ]
4133 }
4234 ```
4335 </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 @@
11 ---
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"
43 ---
54
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>
78
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
3510
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 @@
11 ---
22 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"
43 ---
54
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>
78
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
1310
1411 <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 @@
11 ---
22 title: "Llama Stack"
3-description: "Configure Llama Stack with Continue"
43 keywords: [llama, stack, local, api, inference]
54 ---
65
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>
569
5710 <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>",
7426 "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 @@
11 ---
22 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"
43 ---
54
65 <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)
107 </Info>
118
12-## Chat model
13-
14-We recommend configuring **Nemotron-4-340B-Instruct** as your chat model.
9+## Configuration
1510
1611 <Tabs>
1712 <Tab title="YAML">
1813 ```yaml title="config.yaml"
1914 models:
20- - name: Nemotron-4-340B-Instruct
15+ - name: <MODEL_NAME>
2116 provider: nvidia
22- model: nvidia-nemotron-4-340b-instruct
17+ model: <MODEL_ID>
2318 apiKey: <YOUR_NVIDIA_API_KEY>
2419 ```
2520 </Tab>
26- <Tab title="JSON">
21+ <Tab title="JSON (Deprecated)">
2722 ```json title="config.json"
2823 {
2924 "models": [
3025 {
31- "title": "Nemotron-4-340B-Instruct",
26+ "title": "<MODEL_NAME>",
3227 "provider": "nvidia",
33- "model": "nvidia-nemotron-4-340b-instruct",
28+ "model": "<MODEL_ID>",
3429 "apiKey": "<YOUR_NVIDIA_API_KEY>"
3530 }
3631 ]
@@ -38,44 +33,3 @@
3833 ```
3934 </Tab>
4035 </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 @@
11 ---
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"
43 sidebarTitle: "Together AI"
54 ---
65
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
815
916 <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>
3340 </Tabs>
3441
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 @@
1515 | [Amazon Bedrock](/customize/model-providers/top-level/bedrock) | AWS service offering access to various foundation models | Chat, Edit, Apply, Embeddings |
1616 | [Ollama](/customize/model-providers/top-level/ollama) | Run open-source models locally with a simple interface | Chat, Edit, Apply, Embeddings, Autocomplete |
1717 | [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 |
2121 | [Vertex AI](/customize/model-providers/top-level/vertexai) | Google Cloud's machine learning platform | Chat, Edit, Apply, Embeddings |
2222 | [Inception](/customize/model-providers/top-level/inception) | On-premises open-source model runners | Chat, Edit, Apply |
2323
@@ -32,7 +32,8 @@
3232 | [Groq](/customize/model-providers/more/groq) | Ultra-fast inference for various open models |
3333 | [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models |
3434 | [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 |
3637 | [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation |
3738 | [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting |
3839 | [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services |
@@ -42,7 +43,7 @@
4243
4344 | Provider | Description |
4445 | :------------------------------------------------------- | :-------------------------------------------- |
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 |
4647 | [llama.cpp](/customize/model-providers/more/llamacpp) | Optimized C++ implementation for running LLMs |
4748 | [LlamaStack](/customize/model-providers/more/llamastack) | Stack for running Llama models locally |
4849 | [llamafile](/customize/model-providers/more/llamafile) | Self-contained executable model files |
@@ -72,9 +73,9 @@
7273
7374 ```yaml
7475 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
7879 apiKey: ${{ secrets.OPENAI_API_KEY }}
7980 roles:
8081 - chat
modified docs/customize/model-providers/top-level/anthropic.mdx +19 −40
@@ -1,37 +1,37 @@
11 ---
22 title: "How to Configure Anthropic Claude Models with Continue"
33 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"
54 sidebarTitle: "Anthropic"
65 ---
76
7+<Tip>
8+ **Discover Anthropic models [here](https://hub.continue.dev/anthropic)**
9+</Tip>
10+
811 <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)
1113 </Info>
1214
13-## How to Set Up Anthropic Chat Models
14-
15-We recommend configuring **Claude 4 Sonnet** as your chat model.
15+## Configuration
1616
1717 <Tabs>
1818 <Tab title="YAML">
1919 ```yaml title="config.yaml"
2020 models:
21- - name: Claude 4 Sonnet
21+ - name: <MODEL_NAME>
2222 provider: anthropic
23- model: claude-sonnet-4-20250514
23+ model: <MODEL_ID>
2424 apiKey: <YOUR_ANTHROPIC_API_KEY>
2525 ```
2626 </Tab>
27- <Tab title="JSON">
27+ <Tab title="JSON (Deprecated)">
2828 ```json title="config.json"
2929 {
3030 "models": [
3131 {
32- "title": "Claude 4 Sonnet",
32+ "title": "<MODEL_NAME>",
3333 "provider": "anthropic",
34- "model": "claude-sonnet-4-latest",
34+ "model": "<MODEL_ID>",
3535 "apiKey": "<YOUR_ANTHROPIC_API_KEY>"
3636 }
3737 ]
@@ -40,44 +40,23 @@
4040 </Tab>
4141 </Tabs>
4242
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>
6046
6147 ## How to Enable Prompt Caching with Claude
6248
6349 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.
6450
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-
7251 To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows:
7352
7453 <Tabs>
7554 <Tab title="YAML">
7655 ```yaml title="config.yaml"
7756 models:
78- - name: Anthropic
57+ - name: <MODEL_NAME>
7958 provider: anthropic
80- model: claude-sonnet-4-20250514
59+ model: <MODEL_ID>
8160 apiKey: <YOUR_ANTHROPIC_API_KEY>
8261 roles:
8362 - chat
@@ -85,7 +64,7 @@
8564 promptCaching: true
8665 ```
8766 </Tab>
88- <Tab title="JSON">
67+ <Tab title="JSON (Deprecated)">
8968 ```json title="config.json"
9069 {
9170 "models": [
@@ -94,9 +73,9 @@
9473 "cacheSystemMessage": true,
9574 "cacheConversation": true
9675 },
97- "title": "Anthropic",
76+ "title": "<MODEL_NAME>",
9877 "provider": "anthropic",
99- "model": "claude-sonnet-4-latest",
78+ "model": "<MODEL_ID>",
10079 "defaultCompletionOptions": {
10180 "promptCaching": true
10281 },
modified docs/customize/model-providers/top-level/azure.mdx +18 −116
@@ -1,29 +1,20 @@
11 ---
22 title: "How to Configure Azure AI Foundry with Continue"
33 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"
54 sidebarTitle: "Azure AI Foundry"
65 ---
76
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-
107 <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)
149 </Info>
1510
16-## How to Set Up Azure AI Foundry Chat Models
17-
18-We recommend configuring **GPT-4o** as your chat model.
19-
2011 <Tabs>
2112 <Tab title="YAML">
2213 ```yaml title="config.yaml"
2314 models:
24- - name: GPT-4o
15+ - name: <Model_NAME>
2516 provider: azure
26- model: gpt-4o
17+ model: <MODEL_ID>
2718 apiBase: <YOUR_DEPLOYMENT_BASE>
2819 apiKey: <YOUR_AZURE_API_KEY> # If you use subscription key, try using Azure gateway to rename it apiKey
2920 env:
@@ -32,13 +23,13 @@
3223 apiVersion: 2023-07-01-preview # Azure API version
3324 ```
3425 </Tab>
35- <Tab title="JSON">
26+ <Tab title="JSON (Deprecated)">
3627 ```json title="config.json"
3728 {
3829 "models": [{
39- "title": "GPT-4o",
30+ "title": "<MODEL_NAME>",
4031 "provider": "azure",
41- "model": "gpt-4o",
32+ "model": "<MODEL_ID>",
4233 "apiBase": "<YOUR_DEPLOYMENT_BASE>",
4334 "deployment": "<YOUR_DEPLOYMENT_NAME>",
4435 "apiKey": "<YOUR_AZURE_API_KEY>", // If you use subscription key, try using Azure gateway to rename it apiKey
@@ -49,101 +40,12 @@
4940 </Tab>
5041 </Tabs>
5142
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)
13744
13845 <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)
14347 </Info>
14448
145-## Azure OpenAI Service configuration
146-
14749 Azure OpenAI Service requires a handful of additional parameters to be configured, such as a deployment name and API base URL.
14850
14951 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 @@
15456 <Tab title="YAML">
15557 ```yaml title="config.yaml"
15658 models:
157- - name: GPT-4o Azure
158- model: gpt-4o
59+ - name: <MODEL_NAME>
60+ model: <MODEL_ID>
15961 provider: azure
16062 apiBase: https://just-an-example.openai.azure.com
16163 apiKey: <YOUR_AZURE_API_KEY>
16264 env:
163- apiVersion: 2023-03-15-preview
164- deployment: gpt-4o-july
65+ apiVersion: <API_VERSION>
66+ deployment: <MODEL_DEPLOYMENT>
16567 apiType: azure-openai
16668 ```
16769 </Tab>
168- <Tab title="JSON">
70+ <Tab title="JSON (Deprecated)">
16971 ```json title="config.json"
17072 {
171- "title": "GPT-4o Azure",
172- "model": "gpt-4o",
73+ "title": "<MODEL_NAME>",
74+ "model": "<MODEL_ID>",
17375 "provider": "azure",
17476 "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>",
17779 "apiKey": "<YOUR_AZURE_API_KEY>",
17880 "apiType": "azure-openai"
17981 }
18082 ```
18183 </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 @@
11 ---
22 title: "How to Configure Amazon Bedrock with Continue"
33 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"
54 sidebarTitle: "Amazon Bedrock"
65 ---
76
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>
910
10-## How to Set Up Amazon Bedrock Chat Models
11+<Info>
12+ Get started with [Amazon Bedrock](https://aws.amazon.com/bedrock/)
13+</Info>
1114
12-We recommend configuring **Claude 3.7 Sonnet** as your chat model.
15+## Configuration
1316
1417 <Tabs>
1518 <Tab title="YAML">
1619 ```yaml title="config.yaml"
1720 models:
18- - name: Claude 3.7 Sonnet
21+ - name: <MODEL_NAME>
1922 provider: bedrock
20- model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
23+ model: <MODEL_ID>
2124 env:
2225 region: us-east-1
2326 profile: bedrock
@@ -25,14 +28,14 @@
2528 - chat
2629 ```
2730 </Tab>
28- <Tab title="JSON">
31+ <Tab title="JSON (Deprecated)">
2932 ```json title="config.json"
3033 {
3134 "models": [
3235 {
33- "title": "Claude 3.7 Sonnet",
36+ "title": "<MODEL_NAME>",
3437 "provider": "bedrock",
35- "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
38+ "model": "<MODEL_ID>",
3639 "region": "us-east-1",
3740 "profile": "bedrock"
3841 }
@@ -42,109 +45,9 @@
4245 </Tab>
4346 </Tabs>
4447
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>
14851
14952 ## How to Enable Prompt Caching with Amazon Bedrock
15053
@@ -153,23 +56,11 @@
15356 `promptCaching: true` under `defaultCompletionOptions` in your model
15457 configuration.
15558
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-
16859 ```yaml title="config.yaml"
16960 models:
170- - name: Claude 3.7 Sonnet
61+ - name: <MODEL_NAME>
17162 provider: bedrock
172- model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
63+ model: <MODEL_ID>
17364 defaultCompletionOptions:
17465 promptCaching: true
17566 ```
@@ -194,9 +85,9 @@
19485 <Tab title="YAML">
19586 ```yaml title="config.yaml"
19687 models:
197- - name: Claude 3.7 Sonnet
88+ - name: <MODEL_NAME>
19889 provider: bedrock
199- model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
90+ model: <MODEL_ID>
20091 env:
20192 region: us-east-1
20293 accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants
@@ -205,17 +96,17 @@
20596 - chat
20697 ```
20798 </Tab>
208- <Tab title="JSON">
99+ <Tab title="JSON (Deprecated)">
209100 ```json title="config.json"
210101 {
211102 "models": [
212103 {
213- "title": "Claude 3.7 Sonnet",
104+ "title": "<MODEL_NAME>",
214105 "provider": "bedrock",
215- "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
106+ "model": "<MODEL_ID>",
216107 "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>"
219110 }
220111 ]
221112 }
@@ -231,23 +122,23 @@
231122 <Tab title="YAML">
232123 ```yaml title="config.yaml"
233124 models:
234- - name: AWS Bedrock deepseek-coder-6.7b-instruct
125+ - name: <MODEL_NAME>
235126 provider: bedrockimport
236- model: deepseek-coder-6.7b-instruct
127+ model: <MODEL_ID>
237128 env:
238129 region: us-west-2
239130 profile: bedrock
240131 modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX
241132 ```
242133 </Tab>
243- <Tab title="JSON">
134+ <Tab title="JSON (Deprecated)">
244135 ```json title="config.json"
245136 {
246137 "models": [
247138 {
248- "title": "AWS Bedrock deepseek-coder-6.7b-instruct",
139+ "title": "<MODEL_NAME>",
249140 "provider": "bedrockimport",
250- "model": "deepseek-coder-6.7b-instruct",
141+ "model": "<MODEL_ID>",
251142 "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX",
252143 "region": "us-west-2",
253144 "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 @@
11 ---
22 title: "How to Configure Gemini with Continue"
33 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"
54 sidebarTitle: "Gemini"
65 ---
76
7+<Tip>
8+ **Discover Google models [here](https://hub.continue.dev/?q=Gemini)**
9+</Tip>
10+
811 <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/)
1113 </Info>
1214
13-## How to Set Up Gemini Chat Models
14-
15-We recommend configuring **Gemini 2.0 Flash** as your chat model.
15+## Configuration
1616
1717 <Tabs>
1818 <Tab title="YAML">
1919 ```yaml title="config.yaml"
2020 models:
21- - name: Gemini 2.0 Flash
21+ - name: <MODEL_NAME>
2222 provider: gemini
23- model: gemini-2.0-flash
23+ model: <MODEL_ID>
2424 apiKey: <YOUR_GEMINI_API_KEY>
2525 ```
2626 </Tab>
27- <Tab title="JSON">
27+ <Tab title="JSON (Deprecated)">
2828 ```json title="config.json"
2929 {
3030 "models": [
3131 {
32- "title": "Gemini 2.0 Flash",
32+ "title": "<MODEL_NAME>",
3333 "provider": "gemini",
34- "model": "gemini-2.0-flash",
34+ "model": "<MODEL_ID>",
3535 "apiKey": "<YOUR_GEMINI_API_KEY>"
3636 }
3737 ]
@@ -40,43 +40,6 @@
4040 </Tab>
4141 </Tabs>
4242
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 @@
11 ---
22 title: "How to Configure Inception with Continue"
33 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"
54 sidebarTitle: "Inception"
65 ---
76
7+<Tip>
8+ **Discover Inception models [here](https://hub.continue.dev/inceptionlabs)**
9+</Tip>
10+
811 <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)
1113 </Info>
1214
13-## How to Set Up Inception Chat Models
14-
15-We recommend configuring **Mercury Coder Small** as your chat model.
15+## Configuration
1616
1717 <Tabs>
1818 <Tab title="YAML">
1919 ```yaml title="config.yaml"
2020 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>
2425 ```
2526 </Tab>
26- <Tab title="JSON">
27+ <Tab title="JSON (Deprecated)">
2728 ```json title="config.json"
2829 {
2930 "models": [
3031 {
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>",
6133 "provider": "inception",
62- "model": "mercury-coder-small",
34+ "model": "<MODEL_ID>",
6335 "apiKey": "<INCEPTION_API_KEY>"
6436 }
6537 ]
@@ -68,14 +40,6 @@
6840 </Tab>
6941 </Tabs>
7042
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 @@
11 ---
22 title: "How to Configure Ollama with Continue"
33 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"
54 sidebarTitle: "Ollama"
65 ---
76
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>
910
10-## How to Set Up Ollama Chat Models
11+<Info>
12+ Get started with [Ollama](https://ollama.com/download)
13+</Info>
1114
12-We recommend configuring **Llama3.1 8B** as your chat model.
15+## Configuration
1316
1417 <Tabs>
1518 <Tab title="YAML">
1619 ```yaml title="config.yaml"
1720 models:
18- - name: Llama3.1 8B
21+ - name: <MODEL_NAME>
1922 provider: ollama
20- model: llama3.1:8b
23+ model: <MODEL_ID>
24+ apiBase: http://<my endpoint>:11434 # if running a remote instance of Ollama
2125 ```
2226 </Tab>
23- <Tab title="JSON">
27+ <Tab title="JSON (Deprecated)">
2428 ```json title="config.json"
2529 {
2630 "models": [
2731 {
28- "title": "Llama3.1 8B",
32+ "title": "<MODEL_NAME>",
2933 "provider": "ollama",
30- "model": "llama3.1:8b"
34+ "model": "<MODEL_ID>"
35+ "apiBase": "http://<my endpoint>:11434" // if running a remote instance of Ollama
3136 }
3237 ]
3338 }
@@ -35,96 +40,9 @@
3540 </Tab>
3641 </Tabs>
3742
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>
12846
12947 ## How to Configure Model Capabilities in Ollama
13048
@@ -134,25 +52,25 @@
13452 <Tab title="YAML">
13553 ```yaml title="config.yaml"
13654 models:
137- - name: Custom Vision Model
55+ - name: <CUSTOM_MODEL_NAME>
13856 provider: ollama
139- model: my-custom-llava
57+ model: <CUSTOM_MODEL_ID>
14058 capabilities:
14159 - 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
14361 ```
14462 </Tab>
145- <Tab title="JSON">
63+ <Tab title="JSON (Deprecated)">
14664 ```json title="config.json"
14765 {
14866 "models": [
14967 {
150- "title": "Custom Vision Model",
68+ "title": "<CUSTOM_MODEL_NAME>",
15169 "provider": "ollama",
152- "model": "my-custom-llava",
70+ "model": "<CUSTOM_MODEL_ID>",
15371 "capabilities": {
154- "tools": true,
155- "uploadImage": true
72+ "tools": true, // Enable if your model supports function calling
73+ "uploadImage": true // Enable for vision models
15674 }
15775 }
15876 ]
@@ -162,6 +80,5 @@
16280 </Tabs>
16381
16482 <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
16784 </Note>
modified docs/customize/model-providers/top-level/openai.mdx +30 −73
@@ -1,37 +1,37 @@
11 ---
22 title: "How to Configure OpenAI Models with Continue"
33 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"
54 sidebarTitle: "OpenAI"
65 ---
76
7+<Tip>
8+ **Discover OpenAI models [here](https://hub.continue.dev/openai)**
9+</Tip>
10+
811 <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)
1113 </Info>
1214
13-## How to Set Up OpenAI Chat Models
14-
15-We recommend configuring **GPT-4o** as your chat model.
15+## Configuration
1616
1717 <Tabs>
1818 <Tab title="YAML">
1919 ```yaml title="config.yaml"
2020 models:
21- - name: GPT-4o
21+ - name: <MODEL_NAME>
2222 provider: openai
23- model: gpt-4o
23+ model: <MODEL_ID>
2424 apiKey: <YOUR_OPENAI_API_KEY>
2525 ```
2626 </Tab>
27- <Tab title="JSON">
27+ <Tab title="JSON (Deprecated)">
2828 ```json title="config.json"
2929 {
3030 "models": [
3131 {
32- "title": "GPT-4o",
33- "provider": "openai",
34- "model": "gpt-4o",
32+ "title": "<MODEL_NAME>",
33+ "provider": "openai",
34+ "model": "<MODEL_ID>",
3535 "apiKey": "<YOUR_OPENAI_API_KEY>"
3636 }
3737 ]
@@ -40,50 +40,13 @@
4040 </Tab>
4141 </Tabs>
4242
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>
8346
84-## How to Use OpenAI-Compatible Servers and APIs
47+## OpenAI API compatible providers
8548
86-OpenAI compatible servers
49+OpenAI API compatible providers include
8750
8851 - [KoboldCpp](https://github.com/lostruins/koboldcpp)
8952 - [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation)
@@ -93,35 +56,29 @@
9356 - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples)
9457 - [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html)
9558 - [BerriAI/litellm](https://github.com/BerriAI/litellm)
59+- [Tetrate Agent Router Service](https://router.tetrate.ai)
9660
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:
10562
10663 <Tabs>
10764 <Tab title="YAML">
10865 ```yaml title="config.yaml"
10966 models:
110- - name: OpenAI-compatible server / API
67+ - name: <OPENAI_API_COMPATIBLE_PROVIDER_MODEL>
11168 provider: openai
112- model: MODEL_NAME
69+ model: <MODEL_NAME>
11370 apiBase: http://localhost:8000/v1
11471 apiKey: <YOUR_CUSTOM_API_KEY>
11572 ```
11673 </Tab>
117- <Tab title="JSON">
74+ <Tab title="JSON (Deprecated)">
11875 ```json title="config.json"
11976 {
12077 "models": [
12178 {
122- "title": "OpenAI-compatible server / API",
79+ "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>",
12380 "provider": "openai",
124- "model": "MODEL_NAME",
81+ "model": "<MODEL_NAME>",
12582 "apiKey": "<YOUR_CUSTOM_API_KEY>",
12683 "apiBase": "http://localhost:8000/v1"
12784 }
@@ -139,22 +96,22 @@
13996 <Tab title="YAML">
14097 ```yaml title="config.yaml"
14198 models:
142- - name: OpenAI-compatible server / API
99+ - name: <OPENAI_API_COMPATIBLE_PROVIDER_MODEL>
143100 provider: openai
144- model: MODEL_NAME
101+ model: <MODEL_NAME>>
145102 apiBase: http://localhost:8000/v1
146103 useLegacyCompletionsEndpoint: true
147104 ```
148105 </Tab>
149- <Tab title="JSON">
106+ <Tab title="JSON (Deprecated)">
150107 ```json title="config.json"
151108 {
152109 "models": [
153110 {
154- "title": "OpenAI-compatible server / API",
111+ "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>",
155112 "provider": "openai",
156- "model": "MODEL_NAME",
157- "apiBase": "http://localhost:8000/v1",
113+ "model": "<MODEL_NAME>",
114+ "apiBase": "http://localhost:8000/v1",
158115 "useLegacyCompletionsEndpoint": true
159116 }
160117 ]
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+![Remix a model from Tetrate on Continue Hub](../assets/tetrate-remix.png)
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 @@
11 ---
22 title: "How to Configure Vertex AI with Continue"
33 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"
54 sidebarTitle: "Vertex AI"
65 ---
76
87 <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)
1310 </Info>
1411
15-## How to Set Up Vertex AI Chat Models
16-
17-We recommend configuring **Claude 3.5 Sonnet** as your chat model.
12+## Configuration
1813
1914 <Tabs>
2015 <Tab title="YAML">
2116 ```yaml title="config.yaml"
2217 models:
23- - name: Claude 3.5 Sonnet
18+ - name: <MODEL_NAME>
2419 provider: vertexai
25- model: claude-3-5-sonnet-20240620
20+ model: <MODEL_ID>
2621 env:
2722 projectId: <PROJECT_ID>
2823 region: us-east5
2924 ```
3025 </Tab>
31- <Tab title="JSON">
26+ <Tab title="JSON (Deprecated)">
3227 ```json title="config.json"
3328 {
3429 "models": [
3530 {
36- "title": "Claude 3.5 Sonnet",
31+ "title": "<MODEL_NAME>",
3732 "provider": "vertexai",
38- "model": "claude-3-5-sonnet-20240620",
33+ "model": "<MODEL_ID>",
3934 "projectId": "[PROJECT_ID]",
4035 "region": "us-east5"
4136 }
@@ -45,104 +40,32 @@
4540 </Tab>
4641 </Tabs>
4742
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
8344
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.
8546
8647 <Tabs>
8748 <Tab title="YAML">
8849 ```yaml title="config.yaml"
8950 models:
90- - name: Text Embedding-004
51+ - name: <MODEL_NAME>
9152 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>
11055 ```
11156 </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)">
13558 ```json title="config.json"
13659 {
13760 "models": [
13861 {
139- "title": "Gemini 2.5 Flash - VertexAI",
62+ "title": "<MODEL_NAME>",
14063 "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>",
14366 }
14467 ]
14568 }
14669 ```
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 @@
22 title: "Model roles"
33 sidebarTitle: Overview
44 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"
66 ---
77
88 <CardGroup>
modified docs/customize/model-roles/00-intro.mdx +5 −1
@@ -17,9 +17,13 @@
1717
1818 These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](/reference#models) for more details.
1919
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+
2024 ## Selecting model roles
2125
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.
2327
2428 ![Settings Active Models Section](/images/settings-model-roles.png)
2529
modified docs/customize/model-roles/apply.mdx +4 −0
@@ -9,6 +9,10 @@
99
1010 ## Recommended Apply models
1111
12+<Info>
13+ For the latest Apply model recommendations, see our [comprehensive model recommendations](/customization/models#recommended-models).
14+</Info>
15+
1216 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).
1317
1418 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.

Next files